diff --git a/.travis.yml b/.travis.yml index 56d5fa9bc..6d6441d9e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,5 +6,4 @@ jdk: notifications: slack: rooms: - - projectkorra:h9WFZqQ2o6fuCkI69ko28XgF#general - projectkorra:h9WFZqQ2o6fuCkI69ko28XgF#devs diff --git a/README.md b/README.md index e02819844..f2a18c527 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ You can view the changelogs for the plugin you're running in the thread created ## API -There are several ways Developers can hook into the ProjectKorra API. Developers looking to learn how to use our API, a tutorial on creating your own abilities can be found [here](http://projectkorra.com/wiki/index.php?title=Creating_A_ProjectKorra_Ability). Additionally, You can view the [Javadocs](http://projectkorra.com/docs) for more detailed information. +There are several ways Developers can hook into the ProjectKorra API. Developers looking to learn how to use our API, a tutorial on creating your own abilities can be found [here](https://github.com/ProjectKorra/ProjectKorra/wiki/Creating-an-Addon-Ability). Additionally, You can view the [Javadocs](http://projectkorra.com/docs) for more detailed information. ## Configuration @@ -42,13 +42,13 @@ The ProjectKorra (Core) configuration will have its own wiki page explaining all ## Commands / Permissions -An extensive list of the available commands and permissions can be found on the wiki by clicking [here](http://projectkorra.com/wiki/index.php?title=ProjectKorra_(Core)_Commands_and_Permissions) +An extensive list of the available commands and permissions can be found on the wiki by clicking [here](https://github.com/ProjectKorra/ProjectKorra/wiki/Commands) ## Bending Players may choose any of the disciplines below and play. Each discipline has its own page dedicated to it, below is just a brief summary of what each element is capable of doing. -### [Airbending](http://projectkorra.com/wiki/index.php?title=Airbending) +### [Airbending](https://github.com/ProjectKorra/ProjectKorra/wiki/Airbending) - Specializes in mobility and defense. - The land is an ideal spot for an airbender, despite being able to bend in water as well. @@ -57,7 +57,7 @@ Players may choose any of the disciplines below and play. Each discipline has it - Increases speed, decreasing rate of hunger, and takes no fall damage. - Comes with the Flight and SpiritualProjection subelements. -### [Waterbending](http://projectkorra.com/wiki/index.php?title=Waterbending) +### [Waterbending](https://github.com/ProjectKorra/ProjectKorra/wiki/Waterbending) - Specializes in maneuverability in and on the water. - Oceans are perfect for Waterbenders. @@ -66,7 +66,7 @@ Players may choose any of the disciplines below and play. Each discipline has it - Opens up possibilities in bodies of water that are otherwise closed to the other disciplines. - Comes with Bloodbending, Healing, Icebending and Plantbending subelements. -### [Earthbending](http://projectkorra.com/wiki/index.php?title=Earthbending) +### [Earthbending](https://github.com/ProjectKorra/ProjectKorra/wiki/Earthbending) - Specializes in manipulating the earth around them. - Any area containing land is perfect for an earthbender. @@ -74,7 +74,7 @@ Players may choose any of the disciplines below and play. Each discipline has it - Fundamentally the same as Waterbenders, with a mix of offensive and defensive playstyles. - Comes with the Sand, Metal and Lavabending subelements. -### [Firebending](http://projectkorra.com/wiki/index.php?title=Firebending) +### [Firebending](https://github.com/ProjectKorra/ProjectKorra/wiki/Firebending) - Very offensive playstyle. - Any environment other than water is suitable for Firebenders. @@ -82,10 +82,10 @@ Players may choose any of the disciplines below and play. Each discipline has it - Very little mobility and defense. - Comes with the Lightning and Combustion subelements. -### [Chiblocking](http://projectkorra.com/wiki/index.php?title=Chiblocking) +### [Chiblocking](https://github.com/ProjectKorra/ProjectKorra/wiki/Chiblocking) - Specializes in bare handed combat. - Can block a user's chi, temporarily disabling their bending. - Takes less fall damage, jump higher, and run faster. - Strikes deal more damage than normal. -- Not very good when it comes to defense. \ No newline at end of file +- Not very good when it comes to defense. diff --git a/pom.xml b/pom.xml index 76179b114..8fed805c7 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.projectkorra projectkorra - 1.8.6 + 1.8.7 jar ProjectKorra diff --git a/src/com/projectkorra/projectkorra/BendingManager.java b/src/com/projectkorra/projectkorra/BendingManager.java index e1e14b6c0..58c90eb0f 100644 --- a/src/com/projectkorra/projectkorra/BendingManager.java +++ b/src/com/projectkorra/projectkorra/BendingManager.java @@ -9,13 +9,13 @@ import org.bukkit.entity.Player; import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.earthbending.metal.MetalClips; import com.projectkorra.projectkorra.object.HorizontalVelocityTracker; import com.projectkorra.projectkorra.util.ActionBar; -import com.projectkorra.projectkorra.util.Flight; import com.projectkorra.projectkorra.util.RevertChecker; +import com.projectkorra.projectkorra.util.TempArmor; import com.projectkorra.projectkorra.util.TempPotionEffect; import com.projectkorra.projectkorra.waterbending.blood.Bloodbending; import com.projectkorra.rpg.RPGMethods; @@ -31,7 +31,7 @@ public class BendingManager implements Runnable { public BendingManager() { instance = this; - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); } public static BendingManager getInstance() { @@ -39,9 +39,9 @@ public static BendingManager getInstance() { } public void handleCooldowns() { - for (UUID uuid : BendingPlayer.getPlayers().keySet()) { - BendingPlayer bPlayer = BendingPlayer.getPlayers().get(uuid); - for (String abil : bPlayer.getCooldowns().keySet()) { + for (final UUID uuid : BendingPlayer.getPlayers().keySet()) { + final BendingPlayer bPlayer = BendingPlayer.getPlayers().get(uuid); + for (final String abil : bPlayer.getCooldowns().keySet()) { if (System.currentTimeMillis() >= bPlayer.getCooldown(abil)) { bPlayer.removeCooldown(abil); } @@ -50,12 +50,12 @@ public void handleCooldowns() { } public void handleDayNight() { - for (World world : Bukkit.getServer().getWorlds()) { - if (!times.containsKey(world)) { - if (FireAbility.isDay(world)) { - times.put(world, true); + for (final World world : Bukkit.getServer().getWorlds()) { + if (!this.times.containsKey(world)) { + if (ElementalAbility.isDay(world)) { + this.times.put(world, true); } else { - times.put(world, false); + this.times.put(world, false); } } else { if (GeneralMethods.hasRPG()) { @@ -63,11 +63,11 @@ public void handleDayNight() { continue; } } - if (times.get(world) && !FireAbility.isDay(world)) { + if (this.times.get(world) && !ElementalAbility.isDay(world)) { // The hashmap says it is day, but it is not. - times.put(world, false); // Sets time to night. - for (Player player : world.getPlayers()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + this.times.put(world, false); // Sets time to night. + for (final Player player : world.getPlayers()) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { continue; } @@ -80,11 +80,11 @@ public void handleDayNight() { } } - if (!times.get(world) && FireAbility.isDay(world)) { + if (!this.times.get(world) && ElementalAbility.isDay(world)) { // The hashmap says it is night, but it is day. - times.put(world, true); - for (Player player : world.getPlayers()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + this.times.put(world, true); + for (final Player player : world.getPlayers()) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { continue; } @@ -101,28 +101,30 @@ public void handleDayNight() { } } + @Override public void run() { try { - interval = System.currentTimeMillis() - time; - time = System.currentTimeMillis(); - ProjectKorra.time_step = interval; + this.interval = System.currentTimeMillis() - this.time; + this.time = System.currentTimeMillis(); + ProjectKorra.time_step = this.interval; CoreAbility.progressAll(); TempPotionEffect.progressAll(); - handleDayNight(); - Flight.handle(); + this.handleDayNight(); RevertChecker.revertAirBlocks(); HorizontalVelocityTracker.updateAll(); - handleCooldowns(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - if (MetalClips.isControlled(player)) { - ActionBar.sendActionBar(Element.METAL.getColor() + "* MetalClipped *", player); - } else if (Bloodbending.isBloodbent(player)) { + this.handleCooldowns(); + TempArmor.cleanup(); + + for (final Player player : Bukkit.getOnlinePlayers()) { + if (Bloodbending.isBloodbent(player)) { ActionBar.sendActionBar(Element.BLOOD.getColor() + "* Bloodbent *", player); + } else if (MetalClips.isControlled(player)) { + ActionBar.sendActionBar(Element.METAL.getColor() + "* MetalClipped *", player); } } } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/BendingPlayer.java b/src/com/projectkorra/projectkorra/BendingPlayer.java index 551a45971..0af3f487c 100644 --- a/src/com/projectkorra/projectkorra/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/BendingPlayer.java @@ -1,9 +1,12 @@ package com.projectkorra.projectkorra; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -19,6 +22,7 @@ import com.projectkorra.projectkorra.ability.AvatarAbility; import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.ability.util.PassiveManager; @@ -29,9 +33,8 @@ import com.projectkorra.projectkorra.event.PlayerCooldownChangeEvent; import com.projectkorra.projectkorra.event.PlayerCooldownChangeEvent.Result; import com.projectkorra.projectkorra.storage.DBConnection; +import com.projectkorra.projectkorra.util.Cooldown; import com.projectkorra.projectkorra.waterbending.blood.Bloodbending; -import com.projectkorra.spirits.SpiritElement; -import com.projectkorra.spirits.SpiritPlayer; /** * Class that presents a player and stores all bending information about the @@ -51,26 +54,26 @@ public class BendingPlayer { private boolean illumination; private boolean chiBlocked; private long slowTime; - private Player player; - private UUID uuid; - private String name; + private final Player player; + private final UUID uuid; + private final String name; private ChiAbility stance; - private ArrayList elements; - private ArrayList subelements; + private final ArrayList elements; + private final ArrayList subelements; private HashMap abilities; - private Map cooldowns; - private Map toggledElements; + private final Map cooldowns; + private final Map toggledElements; /** * Creates a new {@link BendingPlayer}. - * + * * @param uuid The unique identifier * @param playerName The playername * @param elements The known elements * @param abilities The known abilities * @param permaRemoved The permanent removed status */ - public BendingPlayer(UUID uuid, String playerName, ArrayList elements, ArrayList subelements, HashMap abilities, boolean permaRemoved) { + public BendingPlayer(final UUID uuid, final String playerName, final ArrayList elements, final ArrayList subelements, final HashMap abilities, final boolean permaRemoved) { this.uuid = uuid; this.name = playerName; this.elements = elements; @@ -82,11 +85,11 @@ public BendingPlayer(UUID uuid, String playerName, ArrayList elements, this.tremorSense = true; this.illumination = true; this.chiBlocked = false; - cooldowns = new ConcurrentHashMap(); - toggledElements = new ConcurrentHashMap(); - for (Element e : Element.getAllElements()) { + this.cooldowns = this.loadCooldowns(); + this.toggledElements = new ConcurrentHashMap(); + for (final Element e : Element.getAllElements()) { if (!e.equals(Element.AVATAR)) { - toggledElements.put(e, true); + this.toggledElements.put(e, true); } } @@ -94,35 +97,52 @@ public BendingPlayer(UUID uuid, String playerName, ArrayList elements, GeneralMethods.loadBendingPlayer(this); } - public void addCooldown(Ability ability, long cooldown) { - addCooldown(ability.getName(), cooldown); + public void addCooldown(final Ability ability, final long cooldown, final boolean database) { + this.addCooldown(ability.getName(), cooldown, database); } - public void addCooldown(Ability ability) { - addCooldown(ability, ability.getCooldown()); + public void addCooldown(final Ability ability, final boolean database) { + this.addCooldown(ability.getName(), ability.getCooldown(), database); + } + + public void addCooldown(final Ability ability, final long cooldown) { + this.addCooldown(ability, cooldown, false); + } + + public void addCooldown(final Ability ability) { + this.addCooldown(ability, false); + } + + public void addCooldown(final String ability, final long cooldown) { + this.addCooldown(ability, cooldown, false); } /** * Adds an ability to the cooldowns map while firing a * {@link PlayerCooldownChangeEvent}. - * + * * @param ability Name of the ability * @param cooldown The cooldown time + * @param database If the value should be saved to the database */ - public void addCooldown(String ability, long cooldown) { - PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(Bukkit.getPlayer(uuid), ability, cooldown, Result.ADDED); + public void addCooldown(final String ability, final long cooldown, final boolean database) { + if (cooldown <= 0) { + return; + } + final PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(Bukkit.getPlayer(this.uuid), ability, cooldown, Result.ADDED); Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { - this.cooldowns.put(ability, cooldown + System.currentTimeMillis()); + this.cooldowns.put(ability, new Cooldown(cooldown + System.currentTimeMillis(), database)); - Player player = event.getPlayer(); + final Player player = event.getPlayer(); if (player == null) { return; } - String abilityName = event.getAbility(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final String abilityName = event.getAbility(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer.getBoundAbility() != null && bPlayer.getBoundAbility().equals(CoreAbility.getAbility(abilityName))) { GeneralMethods.displayMovePreview(player); @@ -130,21 +150,56 @@ public void addCooldown(String ability, long cooldown) { } } + public Map loadCooldowns() { + final Map cooldowns = new ConcurrentHashMap<>(); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_cooldowns WHERE uuid = '" + this.uuid.toString() + "'")) { + while (rs.next()) { + final int cooldownId = rs.getInt("cooldown_id"); + final long value = rs.getLong("value"); + final String name = ProjectKorra.cooldowns.getCooldownName(cooldownId); + cooldowns.put(name, new Cooldown(value, true)); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + return cooldowns; + } + + public void saveCooldowns() { + DBConnection.sql.modifyQuery("DELETE FROM pk_cooldowns WHERE uuid = '" + this.uuid.toString() + "'", false); + for (final Entry entry : this.cooldowns.entrySet()) { + final String name = entry.getKey(); + final Cooldown cooldown = entry.getValue(); + final int cooldownId = ProjectKorra.cooldowns.getCooldownId(name, false); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT value FROM pk_cooldowns WHERE uuid = '" + this.uuid.toString() + "' AND cooldown_id = " + cooldownId)) { + if (rs.next()) { + DBConnection.sql.modifyQuery("UPDATE pk_cooldowns SET value = " + cooldown.getCooldown() + " WHERE uuid = '" + this.uuid.toString() + "' AND cooldown_id = " + cooldownId, false); + } else { + DBConnection.sql.modifyQuery("INSERT INTO pk_cooldowns (uuid, cooldown_id, value) VALUES ('" + this.uuid.toString() + "', " + cooldownId + ", " + cooldown.getCooldown() + ")", false); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + } + /** * Adds an element to the {@link BendingPlayer}'s known list. - * + * * @param element The element to add. */ - public void addElement(Element element) { + public void addElement(final Element element) { this.elements.add(element); } /** * Adds a subelement to the {@link BendingPlayer}'s known list. - * + * * @param subelement The subelement to add. */ - public void addSubElement(SubElement subelement) { + public void addSubElement(final SubElement subelement) { this.subelements.add(subelement); } @@ -152,125 +207,140 @@ public void addSubElement(SubElement subelement) { * Sets chiBlocked to true. */ public void blockChi() { - chiBlocked = true; + this.chiBlocked = true; } /** * Checks to see if a Player is effected by BloodBending. - * + * * @return true If {@link ChiMethods#isChiBlocked(String)} is true
* false If player is BloodBender and Bending is toggled on, or if * player is in AvatarState */ public boolean canBeBloodbent() { - if (isAvatarState()) { - if (isChiBlocked()) { + if (this.isAvatarState()) { + if (this.isChiBlocked()) { return true; } else { return false; } } - if (canBendIgnoreBindsCooldowns(CoreAbility.getAbility("Bloodbending")) && isToggled()) { + + if (this.canBendIgnoreBindsCooldowns(CoreAbility.getAbility("Bloodbending")) && this.isToggled()) { return false; } + return true; } - public boolean canBend(CoreAbility ability) { - return canBend(ability, false, false); + public boolean canBend(final CoreAbility ability) { + return this.canBend(ability, false, false); } - private boolean canBend(CoreAbility ability, boolean ignoreBinds, boolean ignoreCooldowns) { + private boolean canBend(final CoreAbility ability, final boolean ignoreBinds, final boolean ignoreCooldowns) { if (ability == null) { return false; } - List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); - Location playerLoc = player.getLocation(); + final List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); + final Location playerLoc = this.player.getLocation(); - if (!player.isOnline() || player.isDead()) { + if (!this.player.isOnline() || this.player.isDead()) { return false; - } else if (!canBind(ability)) { + } else if (!this.canBind(ability)) { return false; - } else if (ability.getPlayer() != null && ability.getLocation() != null && !ability.getLocation().getWorld().equals(player.getWorld())) { + } else if (ability.getPlayer() != null && ability.getLocation() != null && !ability.getLocation().getWorld().equals(this.player.getWorld())) { return false; - } else if (!ignoreCooldowns && isOnCooldown(ability.getName())) { + } else if (!ignoreCooldowns && this.isOnCooldown(ability.getName())) { return false; - } else if (!ignoreBinds && (!ability.getName().equals(getBoundAbilityName()))) { + } else if (!ignoreBinds && (!ability.getName().equals(this.getBoundAbilityName()))) { return false; - } else if (disabledWorlds != null && disabledWorlds.contains(player.getWorld().getName())) { + } else if (disabledWorlds != null && disabledWorlds.contains(this.player.getWorld().getName())) { return false; - } else if (Commands.isToggledForAll || !isToggled() || !isElementToggled(ability.getElement())) { + } else if (Commands.isToggledForAll || !this.isToggled() || !this.isElementToggled(ability.getElement())) { return false; - } else if (player.getGameMode() == GameMode.SPECTATOR) { + } else if (this.player.getGameMode() == GameMode.SPECTATOR) { return false; } - if (!ignoreCooldowns && cooldowns.containsKey(name)) { - if (cooldowns.get(name) + getConfig().getLong("Properties.GlobalCooldown") >= System.currentTimeMillis()) { + if (!ignoreCooldowns && this.cooldowns.containsKey(this.name)) { + if (this.cooldowns.get(this.name).getCooldown() + getConfig().getLong("Properties.GlobalCooldown") >= System.currentTimeMillis()) { return false; } - cooldowns.remove(name); + + this.cooldowns.remove(this.name); } - if (isChiBlocked() || isParalyzed() || (isBloodbent() && !ability.getName().equalsIgnoreCase("AvatarState")) || isControlledByMetalClips()) { + if (this.isChiBlocked() || this.isParalyzed() || (this.isBloodbent() && !ability.getName().equalsIgnoreCase("AvatarState")) || this.isControlledByMetalClips()) { return false; - } else if (GeneralMethods.isRegionProtectedFromBuild(player, ability.getName(), playerLoc)) { + } else if (GeneralMethods.isRegionProtectedFromBuild(this.player, ability.getName(), playerLoc)) { return false; - } else if (ability instanceof FireAbility && FireAbility.isSolarEclipse(player.getWorld())) { + } else if (ability instanceof FireAbility && ElementalAbility.isSolarEclipse(this.player.getWorld())) { return false; - } else if (ability instanceof WaterAbility && WaterAbility.isLunarEclipse(player.getWorld())) { + } else if (ability instanceof WaterAbility && ElementalAbility.isLunarEclipse(this.player.getWorld())) { return false; } + return true; } - public boolean canBendIgnoreBinds(CoreAbility ability) { - return canBend(ability, true, false); + public boolean canBendIgnoreBinds(final CoreAbility ability) { + return this.canBend(ability, true, false); } - public boolean canBendIgnoreBindsCooldowns(CoreAbility ability) { - return canBend(ability, true, true); + public boolean canBendIgnoreBindsCooldowns(final CoreAbility ability) { + return this.canBend(ability, true, true); } - public boolean canBendIgnoreCooldowns(CoreAbility ability) { - return canBend(ability, false, true); + public boolean canBendIgnoreCooldowns(final CoreAbility ability) { + return this.canBend(ability, false, true); } - public boolean canBendPassive(Element element) { + public boolean canBendPassive(final CoreAbility ability) { + if (ability == null) { + return false; // If the passive is disabled. + } + final Element element = ability.getElement(); if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { return false; } - List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); + final List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); - if (element == null || player == null) { + if (element == null || this.player == null) { return false; - } else if (!player.hasPermission("bending." + element.getName() + ".passive")) { + } else if (!this.player.hasPermission("bending." + element.getName() + ".passive")) { return false; - } else if (!hasElement(element)) { + } else if (!this.hasElement(element)) { return false; - } else if (disabledWorlds != null && disabledWorlds.contains(player.getWorld().getName())) { + } else if (disabledWorlds != null && disabledWorlds.contains(this.player.getWorld().getName())) { + return false; + } else if (this.player.getGameMode() == GameMode.SPECTATOR) { return false; } + return true; } - public boolean canUsePassive(Element element) { - if (!isToggled() || !isElementToggled(element)) { + public boolean canUsePassive(final CoreAbility ability) { + final Element element = ability.getElement(); + if (!this.isToggled() || !this.isElementToggled(element)) { return false; - } else if (isChiBlocked() || isParalyzed() || isBloodbent()) { + } else if (this.isChiBlocked() || this.isParalyzed() || this.isBloodbent()) { return false; - } else if (GeneralMethods.isRegionProtectedFromBuild(player, player.getLocation())) { + } else if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.player.getLocation())) { + return false; + } else if (this.isOnCooldown(ability)) { return false; } + return true; } public boolean canCurrentlyBendWithWeapons() { - if (getBoundAbility() != null && player.getInventory().getItemInMainHand() != null) { - boolean hasWeapon = GeneralMethods.isWeapon(player.getInventory().getItemInMainHand().getType()); - boolean noWeaponElement = GeneralMethods.getElementsWithNoWeaponBending().contains(getBoundAbility().getElement()); + if (this.getBoundAbility() != null && this.player.getInventory().getItemInMainHand() != null) { + final boolean hasWeapon = GeneralMethods.isWeapon(this.player.getInventory().getItemInMainHand().getType()); + final boolean noWeaponElement = GeneralMethods.getElementsWithNoWeaponBending().contains(this.getBoundAbility().getElement()); if (hasWeapon) { if (noWeaponElement) { @@ -282,205 +352,240 @@ public boolean canCurrentlyBendWithWeapons() { return true; } + return false; } /** * Checks to see if {@link BendingPlayer} can be slowed. - * + * * @return true If player can be slowed */ public boolean canBeSlowed() { - return (System.currentTimeMillis() > slowTime); + return (System.currentTimeMillis() > this.slowTime); } - public boolean canBind(CoreAbility ability) { - if (ability == null || !player.isOnline() || !ability.isEnabled()) { + public boolean canBind(final CoreAbility ability) { + if (ability == null || !this.player.isOnline() || !ability.isEnabled()) { return false; - } else if (!player.hasPermission("bending.ability." + ability.getName())) { + } else if (!this.player.hasPermission("bending.ability." + ability.getName())) { return false; - } else if (!hasElement(ability.getElement()) && !(ability instanceof AvatarAbility && !((AvatarAbility) ability).requireAvatar())) { + } else if (!this.hasElement(ability.getElement()) && !(ability instanceof AvatarAbility && !((AvatarAbility) ability).requireAvatar())) { return false; } else if (ability.getElement() instanceof SubElement) { - SubElement subElement = (SubElement) ability.getElement(); - if (!hasElement(subElement.getParentElement())) { + final SubElement subElement = (SubElement) ability.getElement(); + if (!this.hasElement(subElement.getParentElement())) { return false; } - if (!hasSubElement(subElement)) { + + if (!this.hasSubElement(subElement)) { return false; } - if (GeneralMethods.hasSpirits()) { - if (GeneralMethods.hasSpirits()) { - SpiritPlayer sPlayer = SpiritPlayer.getSpiritPlayer(player); - if (subElement.equals(SpiritElement.DARK) && sPlayer.isLightSpirit()) { - return false; - } - - if (subElement.equals(SpiritElement.LIGHT) && sPlayer.isDarkSpirit()) { - return false; - } - } - } } + return true; } /** * Checks to see if a player can BloodBend. - * + * * @return true If player has permission node "bending.earth.bloodbending" */ public boolean canBloodbend() { - return subelements.contains(SubElement.BLOOD); + return this.subelements.contains(Element.BLOOD); } public boolean canBloodbendAtAnytime() { - return canBloodbend() && player.hasPermission("bending.water.bloodbending.anytime"); + return this.canBloodbend() && this.player.hasPermission("bending.water.bloodbending.anytime"); } public boolean canCombustionbend() { - return subelements.contains(SubElement.COMBUSTION); + return this.subelements.contains(Element.COMBUSTION); } public boolean canIcebend() { - return subelements.contains(SubElement.ICE); + return this.subelements.contains(Element.ICE); } /** * Checks to see if a player can LavaBend. - * + * * @return true If player has permission node "bending.earth.lavabending" */ public boolean canLavabend() { - return subelements.contains(SubElement.LAVA); + return this.subelements.contains(Element.LAVA); } public boolean canLightningbend() { - return subelements.contains(SubElement.LIGHTNING); + return this.subelements.contains(Element.LIGHTNING); } /** * Checks to see if a player can MetalBend. - * + * * @param player The player to check * @return true If player has permission node "bending.earth.metalbending" */ public boolean canMetalbend() { - return subelements.contains(SubElement.METAL); + return this.subelements.contains(Element.METAL); } /** * Checks to see if a player can PlantBend. - * + * * @param player The player to check * @return true If player has permission node "bending.ability.plantbending" */ public boolean canPlantbend() { - return subelements.contains(SubElement.PLANT); + return this.subelements.contains(Element.PLANT); } /** * Checks to see if a player can SandBend. - * + * * @param player The player to check * @return true If player has permission node "bending.earth.sandbending" */ public boolean canSandbend() { - return subelements.contains(SubElement.SAND); + return this.subelements.contains(Element.SAND); } /** * Checks to see if a player can use Flight. - * + * * @return true If player has permission node "bending.air.flight" */ public boolean canUseFlight() { - return subelements.contains(SubElement.FLIGHT); + return this.subelements.contains(Element.FLIGHT); } /** * Checks to see if a player can use SpiritualProjection. - * + * * @param player The player to check * @return true If player has permission node * "bending.air.spiritualprojection" */ public boolean canUseSpiritualProjection() { - return subelements.contains(SubElement.SPIRITUAL); + return this.subelements.contains(Element.SPIRITUAL); } /** * Checks to see if a player can use Water Healing. - * + * * @return true If player has permission node "bending.water.healing" */ public boolean canWaterHeal() { - return subelements.contains(SubElement.HEALING); + return this.subelements.contains(Element.HEALING); } /** * Checks to see if a player can bend a specific sub element. Used when * checking addon sub elements. - * + * * @param sub SubElement to check for. * @return true If the player has permission to bend that subelement. */ - public boolean canUseSubElement(SubElement sub) { - return subelements.contains(sub); + public boolean canUseSubElement(final SubElement sub) { + return this.subelements.contains(sub); } /** * Gets the map of abilities that the {@link BendingPlayer} knows. - * + * * @return map of abilities */ public HashMap getAbilities() { return this.abilities; } + public static BendingPlayer getBendingPlayer(final OfflinePlayer oPlayer) { + if (oPlayer == null) { + return null; + } + + return BendingPlayer.getPlayers().get(oPlayer.getUniqueId()); + } + + public static BendingPlayer getBendingPlayer(final Player player) { + if (player == null) { + return null; + } + + return getBendingPlayer(player.getName()); + } + + /** + * Attempts to get a {@link BendingPlayer} from specified player name. this + * method tries to get a {@link Player} object and gets the uuid and then + * calls {@link #getBendingPlayer(UUID)} + * + * @param playerName The name of the Player + * @return The BendingPlayer object if {@link BendingPlayer#PLAYERS} + * contains the player name + * + * @see #getBendingPlayer(UUID) + */ + public static BendingPlayer getBendingPlayer(final String playerName) { + if (playerName == null) { + return null; + } + + final Player player = Bukkit.getPlayer(playerName); + final OfflinePlayer oPlayer = player != null ? Bukkit.getOfflinePlayer(player.getUniqueId()) : null; + + return getBendingPlayer(oPlayer); + } + + private static FileConfiguration getConfig() { + return ConfigManager.getConfig(); + } + public CoreAbility getBoundAbility() { - return CoreAbility.getAbility(getBoundAbilityName()); + return CoreAbility.getAbility(this.getBoundAbilityName()); } /** * Gets the Ability bound to the slot that the player is in. - * + * * @return The Ability name bounded to the slot */ public String getBoundAbilityName() { - int slot = player.getInventory().getHeldItemSlot() + 1; - String name = getAbilities().get(slot); + final int slot = this.player.getInventory().getHeldItemSlot() + 1; + final String name = this.getAbilities().get(slot); + return name != null ? name : ""; } /** * Gets the cooldown time of the ability. - * + * * @param ability The ability to check * @return the cooldown time *

* or -1 if cooldown doesn't exist *

*/ - public long getCooldown(String ability) { - if (cooldowns.containsKey(ability)) { - return cooldowns.get(ability); + public long getCooldown(final String ability) { + if (this.cooldowns.containsKey(ability)) { + return this.cooldowns.get(ability).getCooldown(); } + return -1; } /** * Gets the map of cooldowns of the {@link BendingPlayer}. - * + * * @return map of cooldowns */ - public Map getCooldowns() { - return cooldowns; + public Map getCooldowns() { + return this.cooldowns; } /** * Gets the list of elements the {@link BendingPlayer} knows. - * + * * @return a list of elements */ public List getElements() { @@ -489,25 +594,43 @@ public List getElements() { /** * Gets the name of the {@link BendingPlayer}. - * + * * @return the player name */ public String getName() { return this.name; } + /** + * Gets the bukkit Player this {@link BendingPlayer} is wrapping. + * + * @return Player object this BendingPlayer is wrapping. + */ + public Player getPlayer() { + return this.player; + } + + /** + * Gets the map of {@link BendingPlayer}s. + * + * @return {@link #PLAYERS} + */ + public static Map getPlayers() { + return PLAYERS; + } + /** * Gets the {@link ChiAbility Chi stance} the player is in - * + * * @return The player's stance object */ public ChiAbility getStance() { - return stance; + return this.stance; } /** * Gets the list of subelements the {@link BendingPlayer} knows. - * + * * @return a list of subelements */ public List getSubElements() { @@ -516,7 +639,7 @@ public List getSubElements() { /** * Gets the unique identifier of the {@link BendingPlayer}. - * + * * @return the uuid */ public UUID getUUID() { @@ -525,7 +648,7 @@ public UUID getUUID() { /** * Convenience method to {@link #getUUID()} as a string. - * + * * @return string version of uuid */ public String getUUIDString() { @@ -534,25 +657,25 @@ public String getUUIDString() { /** * Checks to see if the {@link BendingPlayer} knows a specific element. - * + * * @param element The element to check * @return true If the player knows the element */ - public boolean hasElement(Element element) { + public boolean hasElement(final Element element) { if (element == null) { return false; } else if (element == Element.AVATAR) { // At the moment we'll allow for both permissions to return true. // Later on we can consider deleting the bending.ability.avatarstate option. - return player.hasPermission("bending.avatar") || player.hasPermission("bending.ability.AvatarState"); + return this.player.hasPermission("bending.avatar") || this.player.hasPermission("bending.ability.AvatarState"); } else if (!(element instanceof SubElement)) { return this.elements.contains(element); } else { - return hasSubElement((SubElement) element); + return this.hasSubElement((SubElement) element); } } - public boolean hasSubElement(SubElement sub) { + public boolean hasSubElement(final SubElement sub) { if (sub == null) { return false; } else { @@ -562,27 +685,37 @@ public boolean hasSubElement(SubElement sub) { /** * Returns whether the player has permission to bend the subelement - * + * * @param sub The SubElement */ - public boolean hasSubElementPermission(SubElement sub) { + public boolean hasSubElementPermission(final SubElement sub) { if (sub == null) { return false; } - return player.hasPermission("bending." + sub.getParentElement().getName().toLowerCase() + "." + sub.getName().toLowerCase() + sub.getType().getBending()); + + return this.player.hasPermission("bending." + sub.getParentElement().getName().toLowerCase() + "." + sub.getName().toLowerCase() + sub.getType().getBending()); } public boolean isAvatarState() { - return CoreAbility.hasAbility(player, AvatarState.class); + return CoreAbility.hasAbility(this.player, AvatarState.class); } public boolean isBloodbent() { - return Bloodbending.isBloodbent(player); + return Bloodbending.isBloodbent(this.player); + } + + /** + * Checks to see if the {@link BendingPlayer} is a bender. + * + * @return true If the player is a bender. + */ + public boolean isBender() { + return !this.elements.isEmpty(); } /** * Checks to see if the {@link BendingPlayer} is chi blocked. - * + * * @return true If the player is chi blocked */ public boolean isChiBlocked() { @@ -590,40 +723,42 @@ public boolean isChiBlocked() { } public boolean isControlledByMetalClips() { - return MetalClips.isControlled(player); + return MetalClips.isControlled(this.player); } - public boolean isElementToggled(Element element) { - if (element != null && toggledElements.containsKey(element)) { - return toggledElements.get(element); + public boolean isElementToggled(final Element element) { + if (element != null && this.toggledElements.containsKey(element)) { + return this.toggledElements.get(element); } + return true; } - public boolean isOnCooldown(Ability ability) { - return isOnCooldown(ability.getName()); + public boolean isOnCooldown(final Ability ability) { + return this.isOnCooldown(ability.getName()); } /** * Checks to see if a specific ability is on cooldown. - * + * * @param ability The ability name to check * @return true if the cooldown map contains the ability */ - public boolean isOnCooldown(String ability) { + public boolean isOnCooldown(final String ability) { if (this.cooldowns.containsKey(ability)) { - return System.currentTimeMillis() < cooldowns.get(ability); + return System.currentTimeMillis() < this.cooldowns.get(ability).getCooldown(); } + return false; } public boolean isParalyzed() { - return player.hasMetadata("movement:stop"); + return this.player.hasMetadata("movement:stop"); } /** * Checks if the {@link BendingPlayer} is permaremoved. - * + * * @return true If the player is permaremoved */ public boolean isPermaRemoved() { @@ -632,7 +767,7 @@ public boolean isPermaRemoved() { /** * Checks if the {@link BendingPlayer} has bending toggled on. - * + * * @return true If bending is toggled on */ public boolean isToggled() { @@ -641,7 +776,7 @@ public boolean isToggled() { /** * Checks if the {@link BendingPlayer} is tremor sensing. - * + * * @return true if player is tremor sensing */ public boolean isTremorSensing() { @@ -650,37 +785,37 @@ public boolean isTremorSensing() { /** * Checks if the {@link BendingPlayer} is using illumination. - * + * * @return true if player is using illumination */ public boolean isIlluminating() { return this.illumination; } - public void removeCooldown(CoreAbility ability) { + public void removeCooldown(final CoreAbility ability) { if (ability != null) { - removeCooldown(ability.getName()); + this.removeCooldown(ability.getName()); } } /** * Removes the cooldown of an ability. - * + * * @param ability The ability's cooldown to remove */ - public void removeCooldown(String ability) { - if (Bukkit.getPlayer(uuid) == null) { + public void removeCooldown(final String ability) { + if (Bukkit.getPlayer(this.uuid) == null) { return; } - PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(Bukkit.getPlayer(uuid), ability, 0, Result.REMOVED); + final PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(Bukkit.getPlayer(this.uuid), ability, 0, Result.REMOVED); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { this.cooldowns.remove(ability); - Player player = event.getPlayer(); - String abilityName = event.getAbility(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Player player = event.getPlayer(); + final String abilityName = event.getAbility(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer.getBoundAbility() != null && bPlayer.getBoundAbility().equals(CoreAbility.getAbility(abilityName))) { GeneralMethods.displayMovePreview(player); @@ -691,135 +826,91 @@ public void removeCooldown(String ability) { /** * Sets the {@link BendingPlayer}'s abilities. This method also saves the * abilities to the database. - * + * * @param abilities The abilities to set/save */ - public void setAbilities(HashMap abilities) { + public void setAbilities(final HashMap abilities) { this.abilities = abilities; + for (int i = 1; i <= 9; i++) { - DBConnection.sql.modifyQuery("UPDATE pk_players SET slot" + i + " = '" + abilities.get(i) + "' WHERE uuid = '" + uuid + "'"); + DBConnection.sql.modifyQuery("UPDATE pk_players SET slot" + i + " = '" + abilities.get(i) + "' WHERE uuid = '" + this.uuid + "'"); } } /** * Sets the {@link BendingPlayer}'s element. If the player had elements * before they will be overwritten. - * + * * @param e The element to set */ - public void setElement(Element element) { + public void setElement(final Element element) { this.elements.clear(); this.elements.add(element); } /** * Sets the permanent removed state of the {@link BendingPlayer}. - * + * * @param permaRemoved */ - public void setPermaRemoved(boolean permaRemoved) { + public void setPermaRemoved(final boolean permaRemoved) { this.permaRemoved = permaRemoved; } /** * Sets the player's {@link ChiAbility Chi stance} - * + * * @param stance The player's new stance object */ - public void setStance(ChiAbility stance) { + public void setStance(final ChiAbility stance) { this.stance = stance; } /** * Slow the {@link BendingPlayer} for a certain amount of time. - * + * * @param cooldown The amount of time to slow. */ - public void slow(long cooldown) { - slowTime = System.currentTimeMillis() + cooldown; + public void slow(final long cooldown) { + this.slowTime = System.currentTimeMillis() + cooldown; } /** * Toggles the {@link BendingPlayer}'s bending. */ public void toggleBending() { - toggled = !toggled; - PassiveManager.registerPassives(player); + this.toggled = !this.toggled; + PassiveManager.registerPassives(this.player); } - public void toggleElement(Element element) { + public void toggleElement(final Element element) { if (element == null) { return; } - toggledElements.put(element, !toggledElements.get(element)); - PassiveManager.registerPassives(player); + + this.toggledElements.put(element, !this.toggledElements.get(element)); + PassiveManager.registerPassives(this.player); } /** * Toggles the {@link BendingPlayer}'s tremor sensing. */ public void toggleTremorSense() { - tremorSense = !tremorSense; + this.tremorSense = !this.tremorSense; } /** * Toggles the {@link BendingPlayer}'s illumination. */ public void toggleIllumination() { - illumination = !illumination; + this.illumination = !this.illumination; } /** * Sets the {@link BendingPlayer}'s chi blocked to false. */ public void unblockChi() { - chiBlocked = false; - } - - public static BendingPlayer getBendingPlayer(OfflinePlayer oPlayer) { - if (oPlayer == null) { - return null; - } - return BendingPlayer.getPlayers().get(oPlayer.getUniqueId()); - } - - public static BendingPlayer getBendingPlayer(Player player) { - if (player == null) { - return null; - } - return getBendingPlayer(player.getName()); - } - - /** - * Attempts to get a {@link BendingPlayer} from specified player name. this - * method tries to get a {@link Player} object and gets the uuid and then - * calls {@link #getBendingPlayer(UUID)} - * - * @param playerName The name of the Player - * @return The BendingPlayer object if {@link BendingPlayer#PLAYERS} - * contains the player name - * - * @see #getBendingPlayer(UUID) - */ - public static BendingPlayer getBendingPlayer(String playerName) { - if (playerName == null) { - return null; - } - Player player = Bukkit.getPlayer(playerName); - OfflinePlayer oPlayer = player != null ? Bukkit.getOfflinePlayer(player.getUniqueId()) : null; - return getBendingPlayer(oPlayer); - } - - private static FileConfiguration getConfig() { - return ConfigManager.getConfig(); + this.chiBlocked = false; } - /** - * Gets the map of {@link BendingPlayer}s. - * - * @return {@link #PLAYERS} - */ - public static Map getPlayers() { - return PLAYERS; - } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/Element.java b/src/com/projectkorra/projectkorra/Element.java index 1caf25680..f898d1691 100644 --- a/src/com/projectkorra/projectkorra/Element.java +++ b/src/com/projectkorra/projectkorra/Element.java @@ -1,15 +1,15 @@ package com.projectkorra.projectkorra; -import org.bukkit.ChatColor; -import org.bukkit.plugin.Plugin; - -import com.projectkorra.projectkorra.configuration.ConfigManager; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; +import org.bukkit.ChatColor; +import org.bukkit.plugin.Plugin; + +import com.projectkorra.projectkorra.configuration.ConfigManager; + public class Element { public enum ElementType { @@ -19,26 +19,26 @@ public enum ElementType { private String bender; private String bend; - ElementType(String bending, String bender, String bend) { + ElementType(final String bending, final String bender, final String bend) { this.bending = bending; this.bender = bender; this.bend = bend; } public String getBending() { - return bending; + return this.bending; } public String getBender() { - return bender; + return this.bender; } public String getBend() { - return bend; + return this.bend; } } - private static final HashMap ALL_ELEMENTS = new HashMap<>(); // Must be initialized first + private static final HashMap ALL_ELEMENTS = new HashMap<>(); // Must be initialized first. public static final Element AIR = new Element("Air"); public static final Element WATER = new Element("Water"); @@ -62,42 +62,42 @@ public String getBend() { private static final Element[] MAIN_ELEMENTS = { AIR, WATER, EARTH, FIRE, CHI }; private static final SubElement[] SUB_ELEMENTS = { FLIGHT, SPIRITUAL, BLOOD, HEALING, ICE, PLANT, LAVA, METAL, SAND, LIGHTNING, COMBUSTION }; - private String name; - private ElementType type; - private Plugin plugin; + private final String name; + private final ElementType type; + private final Plugin plugin; /** * To be used when creating a new Element. Do not use for comparing * Elements. - * + * * @param name Name of the new Element. */ - public Element(String name) { + public Element(final String name) { this(name, ElementType.BENDING, ProjectKorra.plugin); } /** * To be used when creating a new Element. Do not use for comparing * Elements. - * + * * @param name Name of the new Element. * @param type ElementType specifies if its a regular element or chi style * element. */ - public Element(String name, ElementType type) { + public Element(final String name, final ElementType type) { this(name, type, ProjectKorra.plugin); } /** * To be used when creating a new Element. Do not use for comparing * Elements. - * + * * @param name Name of the new Element. * @param type ElementType specifies if its a regular element or chi style * element. * @param plugin The plugin that is adding the element. */ - public Element(String name, ElementType type, Plugin plugin) { + public Element(final String name, final ElementType type, final Plugin plugin) { this.name = name; this.type = type; this.plugin = plugin; @@ -105,42 +105,44 @@ public Element(String name, ElementType type, Plugin plugin) { } public String getPrefix() { - String name_ = name; - if (this instanceof SubElement) + String name_ = this.name; + if (this instanceof SubElement) { name_ = ((SubElement) this).parentElement.name; - return getColor() + ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Prefixes." + name_)) + " "; + } + return this.getColor() + ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Prefixes." + name_)) + " "; } public ChatColor getColor() { - String color = this.plugin.getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + name) : plugin.getConfig().getString("Chat.Colors." + name); + final String color = this.plugin.getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + this.name) : this.plugin.getConfig().getString("Chat.Colors." + this.name); return color != null ? ChatColor.valueOf(color) : ChatColor.WHITE; } public ChatColor getSubColor() { - String color = this.plugin.getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + name + "Sub") : plugin.getConfig().getString("Chat.Colors." + name + "Sub"); + final String color = this.plugin.getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + this.name + "Sub") : this.plugin.getConfig().getString("Chat.Colors." + this.name + "Sub"); return color != null ? ChatColor.valueOf(color) : ChatColor.WHITE; } public String getName() { - return name; + return this.name; } public Plugin getPlugin() { - return plugin; + return this.plugin; } public ElementType getType() { - if (type == null) + if (this.type == null) { return ElementType.NO_SUFFIX; - return type; + } + return this.type; } @Override public String toString() { - return getColor() + getName(); + return this.getColor() + this.getName(); } - public static Element getElement(String name) { + public static Element getElement(final String name) { if (name == null) { return null; } @@ -150,13 +152,13 @@ public static Element getElement(String name) { /** * Returns an array of all official and addon elements excluding * subelements. - * + * * @return Array of all official and addon elements. */ public static Element[] getAllElements() { - List ae = new ArrayList(); + final List ae = new ArrayList(); ae.addAll(Arrays.asList(getMainElements())); - for (Element e : ALL_ELEMENTS.values()) { + for (final Element e : ALL_ELEMENTS.values()) { if (!ae.contains(e) && !(e instanceof SubElement)) { ae.add(e); } @@ -166,7 +168,7 @@ public static Element[] getAllElements() { /** * Returns an array of all the official elements and subelements. - * + * * @return Array of all official elements and subelements. */ public static Element[] getElements() { @@ -175,7 +177,7 @@ public static Element[] getElements() { /** * Returns an array of all the official elements. - * + * * @return Array of all official elements. */ public static Element[] getMainElements() { @@ -184,12 +186,12 @@ public static Element[] getMainElements() { /** * Returns an array of all the addon elements. - * + * * @return Array of all addon elements. */ public static Element[] getAddonElements() { - List ae = new ArrayList(); - for (Element e : getAllElements()) { + final List ae = new ArrayList(); + for (final Element e : getAllElements()) { if (!Arrays.asList(getMainElements()).contains(e)) { ae.add(e); } @@ -200,13 +202,13 @@ public static Element[] getAddonElements() { /** * Returns all subelements, official and addon. - * + * * @return Array of all the subelements. */ public static SubElement[] getAllSubElements() { - List se = new ArrayList(); + final List se = new ArrayList(); se.addAll(Arrays.asList(getSubElements())); - for (Element e : ALL_ELEMENTS.values()) { + for (final Element e : ALL_ELEMENTS.values()) { if (!se.contains(e) && e instanceof SubElement) { se.add((SubElement) e); } @@ -216,7 +218,7 @@ public static SubElement[] getAllSubElements() { /** * Return official subelements. - * + * * @return Array of official subelements. */ public static SubElement[] getSubElements() { @@ -225,13 +227,13 @@ public static SubElement[] getSubElements() { /** * Return all subelements belonging to a parent element. - * + * * @param element * @return Array of all subelements belonging to a parent element. */ - public static SubElement[] getSubElements(Element element) { - List se = new ArrayList(); - for (SubElement sub : getAllSubElements()) { + public static SubElement[] getSubElements(final Element element) { + final List se = new ArrayList(); + for (final SubElement sub : getAllSubElements()) { if (sub.getParentElement().equals(element)) { se.add(sub); } @@ -241,12 +243,12 @@ public static SubElement[] getSubElements(Element element) { /** * Returns an array of all the addon subelements. - * + * * @return Array of all addon subelements. */ public static SubElement[] getAddonSubElements() { - List ae = new ArrayList(); - for (SubElement e : getAllSubElements()) { + final List ae = new ArrayList(); + for (final SubElement e : getAllSubElements()) { if (!Arrays.asList(getSubElements()).contains(e)) { ae.add(e); } @@ -256,13 +258,13 @@ public static SubElement[] getAddonSubElements() { /** * Returns array of addon subelements belonging to a parent element. - * + * * @param element * @return Array of addon subelements belonging to a parent element. */ - public static SubElement[] getAddonSubElements(Element element) { - List se = new ArrayList(); - for (SubElement sub : getAllSubElements()) { + public static SubElement[] getAddonSubElements(final Element element) { + final List se = new ArrayList(); + for (final SubElement sub : getAllSubElements()) { if (sub.getParentElement().equals(element) && !Arrays.asList(getSubElements()).contains(sub)) { se.add(sub); } @@ -270,14 +272,14 @@ public static SubElement[] getAddonSubElements(Element element) { return se.toArray(new SubElement[se.size()]); } - public static Element fromString(String element) { + public static Element fromString(final String element) { if (element == null || element.equals("")) { return null; } if (getElement(element) != null) { return getElement(element); } - for (String s : ALL_ELEMENTS.keySet()) { + for (final String s : ALL_ELEMENTS.keySet()) { if (element.length() <= 1 && getElement(s) instanceof SubElement) { continue; } @@ -292,50 +294,50 @@ public static Element fromString(String element) { public static class SubElement extends Element { - private Element parentElement; + private final Element parentElement; /** * To be used when creating a new SubElement. Do not use for comparing * SubElements. - * + * * @param name Name of the new SubElement. * @param parentElement ParentElement of the SubElement. */ - public SubElement(String name, Element parentElement) { + public SubElement(final String name, final Element parentElement) { this(name, parentElement, ElementType.BENDING, ProjectKorra.plugin); } /** * To be used when creating a new SubElement. Do not use for comparing * SubElements. - * + * * @param name Name of the new SubElement. * @param parentElement ParentElement of the SubElement. * @param type ElementType specifies if its a regular element or chi * style element. */ - public SubElement(String name, Element parentElement, ElementType type) { + public SubElement(final String name, final Element parentElement, final ElementType type) { this(name, parentElement, type, ProjectKorra.plugin); } /** * To be used when creating a new SubElement. Do not use for comparing * SubElements. - * + * * @param name Name of the new SubElement. * @param parentElement ParentElement of the SubElement. * @param type ElementType specifies if its a regular element or chi * style element. * @param plugin The plugin that is adding the element. */ - public SubElement(String name, Element parentElement, ElementType type, Plugin plugin) { + public SubElement(final String name, final Element parentElement, final ElementType type, final Plugin plugin) { super(name, type, plugin); this.parentElement = parentElement; } @Override public ChatColor getColor() { - String color = getPlugin().getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + parentElement.name + "Sub") : getPlugin().getConfig().getString("Chat.Colors." + parentElement.name + "Sub"); + final String color = this.getPlugin().getName().equalsIgnoreCase("ProjectKorra") ? ConfigManager.languageConfig.get().getString("Chat.Colors." + this.parentElement.name + "Sub") : this.getPlugin().getConfig().getString("Chat.Colors." + this.parentElement.name + "Sub"); return color != null ? ChatColor.valueOf(color) : ChatColor.WHITE; } diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index 3103ec0ef..bd80a3c6c 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -91,6 +91,7 @@ import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.ability.PassiveAbility; import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.ability.util.CollisionInitializer; @@ -104,8 +105,6 @@ import com.projectkorra.projectkorra.airbending.AirSpout; import com.projectkorra.projectkorra.airbending.AirSuction; import com.projectkorra.projectkorra.airbending.AirSwipe; -import com.projectkorra.projectkorra.chiblocking.AcrobatStance; -import com.projectkorra.projectkorra.chiblocking.WarriorStance; import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.earthbending.EarthBlast; import com.projectkorra.projectkorra.earthbending.passive.EarthPassive; @@ -119,12 +118,14 @@ import com.projectkorra.projectkorra.storage.DBConnection; import com.projectkorra.projectkorra.util.ActionBar; import com.projectkorra.projectkorra.util.BlockCacheElement; -import com.projectkorra.projectkorra.util.Flight; +import com.projectkorra.projectkorra.util.MovementHandler; import com.projectkorra.projectkorra.util.ParticleEffect; import com.projectkorra.projectkorra.util.ReflectionHandler; import com.projectkorra.projectkorra.util.ReflectionHandler.PackageType; import com.projectkorra.projectkorra.util.TempArmor; +import com.projectkorra.projectkorra.util.TempArmorStand; import com.projectkorra.projectkorra.util.TempBlock; +import com.projectkorra.projectkorra.util.TimeUtil; import com.projectkorra.projectkorra.waterbending.WaterManipulation; import com.projectkorra.projectkorra.waterbending.WaterSpout; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; @@ -139,10 +140,9 @@ import net.sacredlabyrinth.Phaed.PreciousStones.PreciousStones; import net.sacredlabyrinth.Phaed.PreciousStones.field.FieldFlag; -@SuppressWarnings("deprecation") public class GeneralMethods { - public static final Material[] NON_OPAQUE = { Material.AIR, Material.SAPLING, Material.WATER, Material.STATIONARY_WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.WEB, Material.LONG_GRASS, Material.DEAD_BUSH, Material.YELLOW_FLOWER, Material.RED_ROSE, Material.BROWN_MUSHROOM, Material.RED_MUSHROOM, Material.TORCH, Material.FIRE, Material.REDSTONE_WIRE, Material.CROPS, Material.LADDER, Material.RAILS, Material.SIGN_POST, Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, Material.REDSTONE_TORCH_OFF, Material.REDSTONE_TORCH_ON, Material.STONE_BUTTON, Material.SNOW, Material.SUGAR_CANE_BLOCK, Material.PORTAL, Material.DIODE_BLOCK_OFF, Material.DIODE_BLOCK_ON, Material.PUMPKIN_STEM, Material.MELON_STEM, Material.VINE, Material.WATER_LILY, Material.NETHER_WART_BLOCK, Material.ENDER_PORTAL, Material.COCOA, Material.TRIPWIRE_HOOK, Material.TRIPWIRE, Material.FLOWER_POT, Material.CARROT, Material.POTATO, Material.WOOD_BUTTON, Material.GOLD_PLATE, Material.IRON_PLATE, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON, Material.DAYLIGHT_DETECTOR, Material.CARPET, Material.DOUBLE_PLANT, Material.STANDING_BANNER, Material.WALL_BANNER, Material.DAYLIGHT_DETECTOR_INVERTED,Material.END_ROD, Material.CHORUS_PLANT, Material.CHORUS_FLOWER, Material.BEETROOT_BLOCK, Material.END_GATEWAY }; + public static final Material[] NON_OPAQUE = { Material.AIR, Material.SAPLING, Material.WATER, Material.STATIONARY_WATER, Material.LAVA, Material.STATIONARY_LAVA, Material.POWERED_RAIL, Material.DETECTOR_RAIL, Material.WEB, Material.LONG_GRASS, Material.DEAD_BUSH, Material.YELLOW_FLOWER, Material.RED_ROSE, Material.BROWN_MUSHROOM, Material.RED_MUSHROOM, Material.TORCH, Material.FIRE, Material.REDSTONE_WIRE, Material.CROPS, Material.LADDER, Material.RAILS, Material.SIGN_POST, Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, Material.REDSTONE_TORCH_OFF, Material.REDSTONE_TORCH_ON, Material.STONE_BUTTON, Material.SNOW, Material.SUGAR_CANE_BLOCK, Material.PORTAL, Material.DIODE_BLOCK_OFF, Material.DIODE_BLOCK_ON, Material.PUMPKIN_STEM, Material.MELON_STEM, Material.VINE, Material.WATER_LILY, Material.NETHER_STALK, Material.ENDER_PORTAL, Material.COCOA, Material.TRIPWIRE_HOOK, Material.TRIPWIRE, Material.FLOWER_POT, Material.CARROT, Material.POTATO, Material.WOOD_BUTTON, Material.GOLD_PLATE, Material.IRON_PLATE, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON, Material.DAYLIGHT_DETECTOR, Material.CARPET, Material.DOUBLE_PLANT, Material.STANDING_BANNER, Material.WALL_BANNER, Material.DAYLIGHT_DETECTOR_INVERTED, Material.END_ROD, Material.CHORUS_PLANT, Material.CHORUS_FLOWER, Material.BEETROOT_BLOCK, Material.END_GATEWAY }; public static final Material[] INTERACTABLE_MATERIALS = { Material.ACACIA_DOOR, Material.ACACIA_FENCE_GATE, Material.ANVIL, Material.BEACON, Material.BED_BLOCK, Material.BIRCH_DOOR, Material.BIRCH_FENCE_GATE, Material.BOAT, Material.BREWING_STAND, Material.BURNING_FURNACE, Material.CAKE_BLOCK, Material.CHEST, Material.COMMAND, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE_GATE, Material.DISPENSER, Material.DRAGON_EGG, Material.DROPPER, Material.ENCHANTMENT_TABLE, Material.ENDER_CHEST, Material.ENDER_PORTAL_FRAME, Material.FENCE_GATE, Material.FURNACE, Material.HOPPER, Material.HOPPER_MINECART, Material.COMMAND_MINECART, Material.JUKEBOX, Material.JUNGLE_DOOR, Material.JUNGLE_FENCE_GATE, Material.LEVER, Material.MINECART, Material.NOTE_BLOCK, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE_GATE, Material.STONE_BUTTON, Material.TRAPPED_CHEST, Material.TRAP_DOOR, Material.WOOD_BUTTON, Material.WOOD_DOOR, Material.WORKBENCH }; // Represents PlayerName, previously checked blocks, and whether they were true or false @@ -153,14 +153,14 @@ public class GeneralMethods { private static Method getAbsorption; private static Method setAbsorption; - public GeneralMethods(ProjectKorra plugin) { + public GeneralMethods(final ProjectKorra plugin) { GeneralMethods.plugin = plugin; try { getAbsorption = ReflectionHandler.getMethod("EntityHuman", PackageType.MINECRAFT_SERVER, "getAbsorptionHearts"); setAbsorption = ReflectionHandler.getMethod("EntityHuman", PackageType.MINECRAFT_SERVER, "setAbsorptionHearts", Float.class); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } @@ -168,42 +168,42 @@ public GeneralMethods(ProjectKorra plugin) { /** * Checks to see if an AbilityExists. Uses method * {@link #getAbility(String)} to check if it exists. - * + * * @param string Ability Name * @return true if ability exists */ - public static boolean abilityExists(String string) { + public static boolean abilityExists(final String string) { return CoreAbility.getAbility(string) != null; } /** * Binds a Ability to the hotbar slot that the player is on. - * + * * @param player The player to bind to * @param ability The ability name to Bind * @see #bindAbility(Player, String, int) */ - public static void bindAbility(Player player, String ability) { - int slot = player.getInventory().getHeldItemSlot() + 1; + public static void bindAbility(final Player player, final String ability) { + final int slot = player.getInventory().getHeldItemSlot() + 1; bindAbility(player, ability, slot); } /** * Binds a Ability to a specific hotbar slot. - * + * * @param player The player to bind to * @param ability * @param slot * @see #bindAbility(Player, String) */ - public static void bindAbility(Player player, String ability, int slot) { + public static void bindAbility(final Player player, final String ability, final int slot) { if (MultiAbilityManager.playerAbilities.containsKey(player)) { GeneralMethods.sendBrandingMessage(player, ChatColor.RED + "You can't edit your binds right now!"); return; } - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player.getName()); - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player.getName()); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (bPlayer == null) { return; @@ -226,9 +226,9 @@ public static void bindAbility(Player player, String ability, int slot) { * AirShield. */ @Deprecated - public static boolean blockAbilities(Player player, List abilitiesToBlock, Location loc, double radius) { + public static boolean blockAbilities(final Player player, final List abilitiesToBlock, final Location loc, final double radius) { boolean hasBlocked = false; - for (String ability : abilitiesToBlock) { + for (final String ability : abilitiesToBlock) { if (ability.equalsIgnoreCase("FireBlast")) { hasBlocked = FireBlast.annihilateBlasts(loc, radius, player) || hasBlocked; } else if (ability.equalsIgnoreCase("EarthBlast")) { @@ -252,17 +252,17 @@ public static boolean blockAbilities(Player player, List abilitiesToBloc } else if (ability.equalsIgnoreCase("AirSpout")) { hasBlocked = AirSpout.removeSpouts(loc, radius, player) || hasBlocked; } else if (ability.equalsIgnoreCase("Twister")) { - //hasBlocked = AirCombo.removeAroundPoint(player, "Twister", loc, radius) || hasBlocked; + // hasBlocked = AirCombo.removeAroundPoint(player, "Twister", loc, radius) || hasBlocked; } else if (ability.equalsIgnoreCase("AirStream")) { - //hasBlocked = AirCombo.removeAroundPoint(player, "AirStream", loc, radius) || hasBlocked; + // hasBlocked = AirCombo.removeAroundPoint(player, "AirStream", loc, radius) || hasBlocked; } else if (ability.equalsIgnoreCase("AirSweep")) { - //hasBlocked = AirCombo.removeAroundPoint(player, "AirSweep", loc, radius) || hasBlocked; + // hasBlocked = AirCombo.removeAroundPoint(player, "AirSweep", loc, radius) || hasBlocked; } else if (ability.equalsIgnoreCase("FireKick")) { - //hasBlocked = FireCombo.removeAroundPoint(player, "FireKick", loc, radius) || hasBlocked; + // hasBlocked = FireCombo.removeAroundPoint(player, "FireKick", loc, radius) || hasBlocked; } else if (ability.equalsIgnoreCase("FireSpin")) { - //hasBlocked = FireCombo.removeAroundPoint(player, "FireSpin", loc, radius) || hasBlocked; + // hasBlocked = FireCombo.removeAroundPoint(player, "FireSpin", loc, radius) || hasBlocked; } else if (ability.equalsIgnoreCase("FireWheel")) { - //hasBlocked = FireCombo.removeAroundPoint(player, "FireWheel", loc, radius) || hasBlocked; + // hasBlocked = FireCombo.removeAroundPoint(player, "FireWheel", loc, radius) || hasBlocked; } } return hasBlocked; @@ -270,21 +270,52 @@ public static boolean blockAbilities(Player player, List abilitiesToBloc /** * Breaks a block and sets it to {@link Material#AIR AIR}. - * + * * @param block The block to break */ - public static void breakBlock(Block block) { + public static void breakBlock(final Block block) { block.breakNaturally(new ItemStack(Material.AIR)); } - public static boolean canView(Player player, String ability) { + public static boolean canView(final Player player, final String ability) { return player.hasPermission("bending.ability." + ability); } + /** + * Checks if there is a diagonal wall in front of the location in the given + * direction, in any 2 dimensions and all 3 + * + * @param location spot to check + * @param direction which way to check + * @return true if diagonal wall is found + */ + public static boolean checkDiagonalWall(final Location location, final Vector direction) { + final boolean[] xyzsolid = { false, false, false }; + for (int i = 0; i < 3; i++) { + double value; + if (i == 0) { + value = direction.getX(); + } else if (i == 1) { + value = direction.getY(); + } else { + value = direction.getZ(); + } + final BlockFace face = GeneralMethods.getBlockFaceFromValue(i, value); + if (face == null) { + continue; + } + xyzsolid[i] = location.getBlock().getRelative(face).getType().isSolid(); + } + final boolean a = xyzsolid[0] && xyzsolid[2]; + final boolean b = xyzsolid[0] && xyzsolid[1]; + final boolean c = xyzsolid[1] && xyzsolid[2]; + return (a || b || c || (a && b)); + } + /** * Creates a {@link BendingPlayer} with the data from the database. This * runs when a player logs in. - * + * * @param uuid The UUID of the player * @param player The player name * @throws SQLException @@ -294,36 +325,35 @@ public static void createBendingPlayer(final UUID uuid, final String player) { @Override public void run() { - createBendingPlayerAsynchronously(uuid, player); // "async" + createBendingPlayerAsynchronously(uuid, player); } - - }.runTask(ProjectKorra.plugin); + + }.runTaskAsynchronously(ProjectKorra.plugin); } private static void createBendingPlayerAsynchronously(final UUID uuid, final String player) { - ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM pk_players WHERE uuid = '" + uuid.toString() + "'"); + final ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM pk_players WHERE uuid = '" + uuid.toString() + "'"); try { if (!rs2.next()) { // Data doesn't exist, we want a completely new player. - DBConnection.sql.modifyQuery("INSERT INTO pk_players (uuid, player, slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9) VALUES ('" + - uuid.toString() + "', '" + player + "', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null')"); + DBConnection.sql.modifyQuery("INSERT INTO pk_players (uuid, player, slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9) VALUES ('" + uuid.toString() + "', '" + player + "', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null')"); new BendingPlayer(uuid, player, new ArrayList(), new ArrayList(), new HashMap(), false); ProjectKorra.log.info("Created new BendingPlayer for " + player); } else { // The player has at least played before. - String player2 = rs2.getString("player"); + final String player2 = rs2.getString("player"); if (!player.equalsIgnoreCase(player2)) { DBConnection.sql.modifyQuery("UPDATE pk_players SET player = '" + player + "' WHERE uuid = '" + uuid.toString() + "'"); // They have changed names. ProjectKorra.log.info("Updating Player Name for " + player); } - String subelement = rs2.getString("subelement"); - String element = rs2.getString("element"); - String permaremoved = rs2.getString("permaremoved"); + final String subelement = rs2.getString("subelement"); + final String element = rs2.getString("element"); + final String permaremoved = rs2.getString("permaremoved"); boolean p = false; final ArrayList elements = new ArrayList(); if (element != null && !element.equals("NULL")) { - boolean hasAddon = element.contains(";"); - String[] split = element.split(";"); + final boolean hasAddon = element.contains(";"); + final String[] split = element.split(";"); if (split[0] != null) { // Player has an element. if (split[0].contains("a")) { elements.add(Element.AIR); @@ -351,20 +381,20 @@ private static void createBendingPlayerAsynchronously(final UUID uuid, final Str */ final CopyOnWriteArrayList addonClone = new CopyOnWriteArrayList(Arrays.asList(split[split.length - 1].split(","))); final long startTime = System.currentTimeMillis(); - final long timeoutLength = 30000; // How long until it should time out attempting to load addons in + final long timeoutLength = 30000; // How long until it should time out attempting to load addons in. new BukkitRunnable() { @Override public void run() { if (addonClone.isEmpty()) { ProjectKorra.log.info("Successfully loaded in all addon elements!"); - cancel(); + this.cancel(); } else if (System.currentTimeMillis() - startTime > timeoutLength) { ProjectKorra.log.severe("ProjectKorra has timed out after attempting to load in the following addon elements: " + addonClone.toString()); ProjectKorra.log.severe("These elements have taken too long to load in, resulting in users having lost these element."); - cancel(); + this.cancel(); } else { ProjectKorra.log.info("Attempting to load in the following addon elements... " + addonClone.toString()); - for (String addon : addonClone) { + for (final String addon : addonClone) { if (Element.getElement(addon) != null) { elements.add(Element.getElement(addon)); addonClone.remove(addon); @@ -379,11 +409,11 @@ public void run() { final ArrayList subelements = new ArrayList(); boolean shouldSave = false; if (subelement != null && !subelement.equals("NULL")) { - boolean hasAddon = subelement.contains(";"); - String[] split = subelement.split(";"); + final boolean hasAddon = subelement.contains(";"); + final String[] split = subelement.split(";"); if (subelement.equals("-")) { - Player playero = Bukkit.getPlayer(uuid); - for (SubElement sub : Element.getAllSubElements()) { + final Player playero = Bukkit.getPlayer(uuid); + for (final SubElement sub : Element.getAllSubElements()) { if ((playero != null && playero.hasPermission("bending." + sub.getParentElement().getName().toLowerCase() + "." + sub.getName().toLowerCase() + sub.getType().getBending())) && elements.contains(sub.getParentElement())) { subelements.add(sub); shouldSave = true && playero != null; @@ -426,20 +456,20 @@ public void run() { if (hasAddon) { final CopyOnWriteArrayList addonClone = new CopyOnWriteArrayList(Arrays.asList(split[split.length - 1].split(","))); final long startTime = System.currentTimeMillis(); - final long timeoutLength = 30000; // How long until it should time out attempting to load addons in + final long timeoutLength = 30000; // How long until it should time out attempting to load addons in. new BukkitRunnable() { @Override public void run() { if (addonClone.isEmpty()) { ProjectKorra.log.info("Successfully loaded in all addon subelements!"); - cancel(); + this.cancel(); } else if (System.currentTimeMillis() - startTime > timeoutLength) { ProjectKorra.log.severe("ProjectKorra has timed out after attempting to load in the following addon subelements: " + addonClone.toString()); ProjectKorra.log.severe("These subelements have taken too long to load in, resulting in users having lost these subelement."); - cancel(); + this.cancel(); } else { ProjectKorra.log.info("Attempting to load in the following addon subelements... " + addonClone.toString()); - for (String addon : addonClone) { + for (final String addon : addonClone) { if (Element.getElement(addon) != null && Element.getElement(addon) instanceof SubElement) { subelements.add((SubElement) Element.getElement(addon)); addonClone.remove(addon); @@ -455,24 +485,24 @@ public void run() { final HashMap abilities = new HashMap(); final ConcurrentHashMap abilitiesClone = new ConcurrentHashMap(abilities); for (int i = 1; i <= 9; i++) { - String ability = rs2.getString("slot" + i); + final String ability = rs2.getString("slot" + i); abilitiesClone.put(i, ability); } final long startTime = System.currentTimeMillis(); - final long timeoutLength = 30000; // How long until it should time out attempting to load addons in + final long timeoutLength = 30000; // How long until it should time out attempting to load addons in. new BukkitRunnable() { @Override public void run() { if (abilitiesClone.isEmpty()) { - //All abilities loaded. - cancel(); + // All abilities loaded. + this.cancel(); } else if (System.currentTimeMillis() - startTime > timeoutLength) { ProjectKorra.log.severe("ProjectKorra has timed out after attempting to load in the following external abilities: " + abilitiesClone.values().toString()); ProjectKorra.log.severe("These abilities have taken too long to load in, resulting in users having lost them if bound."); - cancel(); + this.cancel(); } else { - for (int slot : abilitiesClone.keySet()) { - String ability = abilitiesClone.get(slot); + for (final int slot : abilitiesClone.keySet()) { + final String ability = abilitiesClone.get(slot); if (ability.equalsIgnoreCase("null")) { abilitiesClone.remove(slot); continue; @@ -501,7 +531,7 @@ public void run() { }.runTask(ProjectKorra.plugin); } } - catch (SQLException ex) { + catch (final SQLException ex) { ex.printStackTrace(); } } @@ -509,12 +539,12 @@ public void run() { /** * Deserializes the configuration file "bendingPlayers.yml" of the old * BendingPlugin and creates a converted.yml ready for conversion. - * + * * @throws IOException If the "bendingPlayers.yml" file is not found */ public static void deserializeFile() { - File readFile = new File(".", "bendingPlayers.yml"); - File writeFile = new File(".", "converted.yml"); + final File readFile = new File(".", "bendingPlayers.yml"); + final File writeFile = new File(".", "converted.yml"); if (readFile.exists()) { try (DataInputStream input = new DataInputStream(new FileInputStream(readFile)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); @@ -527,100 +557,50 @@ public static void deserializeFile() { } } } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } } } - public static void displayColoredParticle(Location loc, ParticleEffect type, String hexVal, float xOffset, float yOffset, float zOffset) { - int R = 0; - int G = 0; - int B = 0; - + public static void displayColoredParticle(final Location loc, ParticleEffect type, final String hexVal, final float xOffset, final float yOffset, final float zOffset) { + int r = 0; + int g = 0; + int b = 0; if (hexVal.length() <= 6) { - R = Integer.valueOf(hexVal.substring(0, 2), 16); - G = Integer.valueOf(hexVal.substring(2, 4), 16); - B = Integer.valueOf(hexVal.substring(4, 6), 16); - if (R <= 0) { - R = 1; - } + r = Integer.valueOf(hexVal.substring(0, 2), 16).intValue(); + g = Integer.valueOf(hexVal.substring(2, 4), 16).intValue(); + b = Integer.valueOf(hexVal.substring(4, 6), 16).intValue(); } else if (hexVal.length() <= 7 && hexVal.substring(0, 1).equals("#")) { - R = Integer.valueOf(hexVal.substring(1, 3), 16); - G = Integer.valueOf(hexVal.substring(3, 5), 16); - B = Integer.valueOf(hexVal.substring(5, 7), 16); - if (R <= 0) { - R = 1; - } + r = Integer.valueOf(hexVal.substring(1, 3), 16).intValue(); + g = Integer.valueOf(hexVal.substring(3, 5), 16).intValue(); + b = Integer.valueOf(hexVal.substring(5, 7), 16).intValue(); } - - loc.setX(loc.getX() + Math.random() * (xOffset / 2 - -(xOffset / 2))); - loc.setY(loc.getY() + Math.random() * (yOffset / 2 - -(yOffset / 2))); - loc.setZ(loc.getZ() + Math.random() * (zOffset / 2 - -(zOffset / 2))); - - if (type == ParticleEffect.RED_DUST || type == ParticleEffect.REDSTONE) { - ParticleEffect.RED_DUST.display(R, G, B, 0.004F, 0, loc, 255.0); - } else if (type == ParticleEffect.SPELL_MOB || type == ParticleEffect.MOB_SPELL) { - ParticleEffect.SPELL_MOB.display((float) 255 - R, (float) 255 - G, (float) 255 - B, 1, 0, loc, 255.0); - } else if (type == ParticleEffect.SPELL_MOB_AMBIENT || type == ParticleEffect.MOB_SPELL_AMBIENT) { - ParticleEffect.SPELL_MOB_AMBIENT.display((float) 255 - R, (float) 255 - G, (float) 255 - B, 1, 0, loc, 255.0); - } else { - ParticleEffect.RED_DUST.display(0, 0, 0, 0.004F, 0, loc, 255.0D); + float red = r / 255.0F; + final float green = g / 255.0F; + final float blue = b / 255.0F; + if (red <= 0) { + red = 1 / 255.0F; } - } - - public static void displayColoredParticle(Location loc, String hexVal) { - int R = 0; - int G = 0; - int B = 0; + loc.setX(loc.getX() + Math.random() * xOffset); + loc.setY(loc.getY() + Math.random() * yOffset); + loc.setZ(loc.getZ() + Math.random() * zOffset); - if (hexVal.length() <= 6) { - R = Integer.valueOf(hexVal.substring(0, 2), 16); - G = Integer.valueOf(hexVal.substring(2, 4), 16); - B = Integer.valueOf(hexVal.substring(4, 6), 16); - if (R <= 0) { - R = 1; - } - } else if (hexVal.length() <= 7 && hexVal.substring(0, 1).equals("#")) { - R = Integer.valueOf(hexVal.substring(1, 3), 16); - G = Integer.valueOf(hexVal.substring(3, 5), 16); - B = Integer.valueOf(hexVal.substring(5, 7), 16); - if (R <= 0) { - R = 1; - } + if (type != ParticleEffect.RED_DUST && type != ParticleEffect.REDSTONE && type != ParticleEffect.SPELL_MOB && type != ParticleEffect.MOB_SPELL && type != ParticleEffect.SPELL_MOB_AMBIENT && type != ParticleEffect.MOB_SPELL_AMBIENT) { + type = ParticleEffect.RED_DUST; } - ParticleEffect.RED_DUST.display(R, G, B, 0.004F, 0, loc, 257D); + type.display(red, green, blue, 1F, 0, loc, 255.0); } - public static void displayColoredParticle(Location loc, String hexVal, float xOffset, float yOffset, float zOffset) { - int R = 0; - int G = 0; - int B = 0; - - if (hexVal.length() <= 6) { - R = Integer.valueOf(hexVal.substring(0, 2), 16); - G = Integer.valueOf(hexVal.substring(2, 4), 16); - B = Integer.valueOf(hexVal.substring(4, 6), 16); - if (R <= 0) { - R = 1; - } - } else if (hexVal.length() <= 7 && hexVal.substring(0, 1).equals("#")) { - R = Integer.valueOf(hexVal.substring(1, 3), 16); - G = Integer.valueOf(hexVal.substring(3, 5), 16); - B = Integer.valueOf(hexVal.substring(5, 7), 16); - if (R <= 0) { - R = 1; - } - } - - loc.setX(loc.getX() + Math.random() * (xOffset / 2 - -(xOffset / 2))); - loc.setY(loc.getY() + Math.random() * (yOffset / 2 - -(yOffset / 2))); - loc.setZ(loc.getZ() + Math.random() * (zOffset / 2 - -(zOffset / 2))); + public static void displayColoredParticle(final Location loc, final String hexVal) { + displayColoredParticle(loc, ParticleEffect.RED_DUST, hexVal, 0, 0, 0); + } - ParticleEffect.RED_DUST.display(R, G, B, 0.004F, 0, loc, 257D); + public static void displayColoredParticle(final Location loc, final String hexVal, final float xOffset, final float yOffset, final float zOffset) { + displayColoredParticle(loc, ParticleEffect.RED_DUST, hexVal, xOffset, yOffset, zOffset); } - public static void displayParticleVector(Location loc, ParticleEffect type, float xTrans, float yTrans, float zTrans) { + public static void displayParticleVector(final Location loc, final ParticleEffect type, final float xTrans, final float yTrans, final float zTrans) { if (type == ParticleEffect.FIREWORKS_SPARK) { ParticleEffect.FIREWORKS_SPARK.display(xTrans, yTrans, zTrans, 0.09F, 0, loc, 257D); } else if (type == ParticleEffect.SMOKE || type == ParticleEffect.SMOKE_NORMAL) { @@ -644,30 +624,38 @@ public static void displayParticleVector(Location loc, ParticleEffect type, floa /** * Drops a {@code Collection} of items on a specified block. - * + * * @param block The block to drop items on. * @param items The items to drop. */ - public static void dropItems(Block block, Collection items) { - for (ItemStack item : items) { + public static void dropItems(final Block block, final Collection items) { + for (final ItemStack item : items) { block.getWorld().dropItem(block.getLocation(), item); } } - public static void displayMovePreview(Player player) { + public static void displayMovePreview(final Player player) { displayMovePreview(player, player.getInventory().getHeldItemSlot() + 1); } - - public static void displayMovePreview(Player player, int slot) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + + public static void displayMovePreview(final Player player, final int slot) { + if (!ConfigManager.defaultConfig.get().getBoolean("Properties.BendingPreview")) { + return; + } + + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (bPlayer == null) { + return; + } String displayedMessage = bPlayer.getAbilities().get(slot); - CoreAbility ability = CoreAbility.getAbility(displayedMessage); - + final CoreAbility ability = CoreAbility.getAbility(displayedMessage); + if (ability != null && bPlayer != null) { if (bPlayer.isOnCooldown(ability)) { - displayedMessage = ability.getElement().getColor() + "" + ChatColor.STRIKETHROUGH + ability.getName(); + final long cooldown = bPlayer.getCooldown(ability.getName()) - System.currentTimeMillis(); + displayedMessage = ability.getElement().getColor() + "" + ChatColor.STRIKETHROUGH + ability.getName() + "" + ability.getElement().getColor() + " - " + TimeUtil.formatTime(cooldown); } else { - if (bPlayer.getStance() instanceof AcrobatStance && ability.getName().equals("AcrobatStance") || bPlayer.getStance() instanceof WarriorStance && ability.getName().equals("WarriorStance")) { + if (bPlayer.getStance() != null && bPlayer.getStance().getName().equals(ability.getName())) { displayedMessage = ability.getElement().getColor() + "" + ChatColor.UNDERLINE + ability.getName(); } else { displayedMessage = ability.getElement().getColor() + ability.getName(); @@ -680,58 +668,94 @@ public static void displayMovePreview(Player player, int slot) { ActionBar.sendActionBar(displayedMessage, player); } - public static float getAbsorbationHealth(Player player) { + public static float getAbsorbationHealth(final Player player) { try { - Object entityplayer = ActionBar.getHandle.invoke(player); - Object hearts = getAbsorption.invoke(entityplayer); - //player.sendMessage(hearts.toString()); + final Object entityplayer = ActionBar.getHandle.invoke(player); + final Object hearts = getAbsorption.invoke(entityplayer); return (float) hearts; } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } return 0; } - public static void setAbsorbationHealth(Player player, float hearts) { + public static void setAbsorbationHealth(final Player player, final float hearts) { try { - Object entityplayer = ActionBar.getHandle.invoke(player); + final Object entityplayer = ActionBar.getHandle.invoke(player); setAbsorption.invoke(entityplayer, hearts); - //player.sendMessage(hearts.toString()); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } - public static List getBlocksAlongLine(Location ploc, Location tloc, World w) { - List blocks = new ArrayList(); + /** + * This gets the BlockFace in the specified dimension of a certain value + * + * @param xyz 0 for x, 1 for y, 2 for z + * @param value vector value for which direction to check + * @return BlockFace for block in specified dimension and value + */ + public static BlockFace getBlockFaceFromValue(final int xyz, final double value) { + switch (xyz) { + case 0: + if (value > 0) { + return BlockFace.EAST; + } else if (value < 0) { + return BlockFace.WEST; + } else { + return BlockFace.SELF; + } + case 1: + if (value > 0) { + return BlockFace.UP; + } else if (value < 0) { + return BlockFace.DOWN; + } else { + return BlockFace.SELF; + } + case 2: + if (value > 0) { + return BlockFace.SOUTH; + } else if (value < 0) { + return BlockFace.NORTH; + } else { + return BlockFace.SELF; + } + default: + return null; + } + } + + public static List getBlocksAlongLine(final Location ploc, final Location tloc, final World w) { + final List blocks = new ArrayList(); - //Next we will name each coordinate - int x1 = ploc.getBlockX(); - int y1 = ploc.getBlockY(); - int z1 = ploc.getBlockZ(); + // Next we will name each coordinate + final int x1 = ploc.getBlockX(); + final int y1 = ploc.getBlockY(); + final int z1 = ploc.getBlockZ(); - int x2 = tloc.getBlockX(); - int y2 = tloc.getBlockY(); - int z2 = tloc.getBlockZ(); + final int x2 = tloc.getBlockX(); + final int y2 = tloc.getBlockY(); + final int z2 = tloc.getBlockZ(); - //Then we create the following integers + // Then we create the following integers int xMin, yMin, zMin; int xMax, yMax, zMax; int x, y, z; - //Now we need to make sure xMin is always lower then xMax - if (x1 > x2) { //If x1 is a higher number then x2 + // Now we need to make sure xMin is always lower then xMax + if (x1 > x2) { // If x1 is a higher number then x2 xMin = x2; xMax = x1; } else { xMin = x1; xMax = x2; } - //Same with Y + // Same with Y if (y1 > y2) { yMin = y2; yMax = y1; @@ -740,7 +764,7 @@ public static List getBlocksAlongLine(Location ploc, Location tloc, World yMax = y2; } - //And Z + // And Z if (z1 > z2) { zMin = z2; zMax = z1; @@ -749,42 +773,42 @@ public static List getBlocksAlongLine(Location ploc, Location tloc, World zMax = z2; } - //Now it's time for the loop + // Now it's time for the loop for (x = xMin; x <= xMax; x++) { for (y = yMin; y <= yMax; y++) { for (z = zMin; z <= zMax; z++) { - Block b = new Location(w, x, y, z).getBlock(); + final Block b = new Location(w, x, y, z).getBlock(); blocks.add(b); } } } - //And last but not least, we return with the list + // And last but not least, we return with the list return blocks; } /** * Gets a {@code List} within the specified radius around the * specified location. - * + * * @param location The base location * @param radius The block radius from location to include within the list * of blocks * @return The list of Blocks */ - public static List getBlocksAroundPoint(Location location, double radius) { - List blocks = new ArrayList(); + public static List getBlocksAroundPoint(final Location location, final double radius) { + final List blocks = new ArrayList(); - int xorg = location.getBlockX(); - int yorg = location.getBlockY(); - int zorg = location.getBlockZ(); + final int xorg = location.getBlockX(); + final int yorg = location.getBlockY(); + final int zorg = location.getBlockZ(); - int r = (int) radius * 4; + final int r = (int) radius * 4; for (int x = xorg - r; x <= xorg + r; x++) { for (int y = yorg - r; y <= yorg + r; y++) { for (int z = zorg - r; z <= zorg + r; z++) { - Block block = location.getWorld().getBlockAt(x, y, z); + final Block block = location.getWorld().getBlockAt(x, y, z); if (block.getLocation().distanceSquared(location) <= radius * radius) { blocks.add(block); } @@ -794,8 +818,8 @@ public static List getBlocksAroundPoint(Location location, double radius) return blocks; } - public static BlockFace getCardinalDirection(Vector vector) { - BlockFace[] faces = { BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.EAST, BlockFace.SOUTH_EAST, BlockFace.SOUTH, BlockFace.SOUTH_WEST, BlockFace.WEST, BlockFace.NORTH_WEST }; + public static BlockFace getCardinalDirection(final Vector vector) { + final BlockFace[] faces = { BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.EAST, BlockFace.SOUTH_EAST, BlockFace.SOUTH, BlockFace.SOUTH_WEST, BlockFace.WEST, BlockFace.NORTH_WEST }; Vector n, ne, e, se, s, sw, w, nw; w = new Vector(-1, 0, 0); n = new Vector(0, 0, -1); @@ -806,12 +830,12 @@ public static BlockFace getCardinalDirection(Vector vector) { nw = n.clone().add(w.clone()).normalize(); sw = s.clone().add(w.clone()).normalize(); - Vector[] vectors = { n, ne, e, se, s, sw, w, nw }; + final Vector[] vectors = { n, ne, e, se, s, sw, w, nw }; double comp = 0; int besti = 0; for (int i = 0; i < vectors.length; i++) { - double dot = vector.dot(vectors[i]); + final double dot = vector.dot(vectors[i]); if (dot > comp) { comp = dot; besti = i; @@ -820,19 +844,19 @@ public static BlockFace getCardinalDirection(Vector vector) { return faces[besti]; } - public static List getCircle(Location loc, int radius, int height, boolean hollow, boolean sphere, int plusY) { - List circleblocks = new ArrayList(); - int cx = loc.getBlockX(); - int cy = loc.getBlockY(); - int cz = loc.getBlockZ(); + public static List getCircle(final Location loc, final int radius, final int height, final boolean hollow, final boolean sphere, final int plusY) { + final List circleblocks = new ArrayList(); + final int cx = loc.getBlockX(); + final int cy = loc.getBlockY(); + final int cz = loc.getBlockZ(); for (int x = cx - radius; x <= cx + radius; x++) { for (int z = cz - radius; z <= cz + radius; z++) { for (int y = (sphere ? cy - radius : cy); y < (sphere ? cy + radius : cy + height); y++) { - double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0); + final double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0); if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1))) { - Location l = new Location(loc.getWorld(), x, y + plusY, z); + final Location l = new Location(loc.getWorld(), x, y + plusY, z); circleblocks.add(l); } } @@ -842,12 +866,12 @@ public static List getCircle(Location loc, int radius, int height, boo } public static String getCurrentDate() { - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); + final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + final Date date = new Date(); return dateFormat.format(date); } - public static Vector getDirection(Location location, Location destination) { + public static Vector getDirection(final Location location, final Location destination) { double x1, y1, z1; double x0, y0, z0; @@ -862,8 +886,8 @@ public static Vector getDirection(Location location, Location destination) { return new Vector(x1 - x0, y1 - y0, z1 - z0); } - public static double getDistanceFromLine(Vector line, Location pointonline, Location point) { - Vector AP = new Vector(); + public static double getDistanceFromLine(final Vector line, final Location pointonline, final Location point) { + final Vector AP = new Vector(); double Ax, Ay, Az; Ax = pointonline.getX(); Ay = pointonline.getY(); @@ -883,18 +907,18 @@ public static double getDistanceFromLine(Vector line, Location pointonline, Loca /** * Gets a {@code Collection} of item drops from a single block. - * + * * @param block The single block * @param type The Material type to change the block into * @param data The block data to change the block into * @param breakitem Unused * @return The item drops fromt the specified block */ - public static Collection getDrops(Block block, Material type, byte data, ItemStack breakitem) { - BlockState tempstate = block.getState(); + public static Collection getDrops(final Block block, final Material type, final byte data, final ItemStack breakitem) { + final BlockState tempstate = block.getState(); block.setType(type); block.setData(data); - Collection item = block.getDrops(); + final Collection item = block.getDrops(); tempstate.update(true); return item; } @@ -902,20 +926,20 @@ public static Collection getDrops(Block block, Material type, byte da /** * Gets a {@code List} of entities around a specified radius from * the specified area - * + * * @param location The base location * @param radius The radius of blocks to look for entities from the location * @return A list of entities around a point */ - public static List getEntitiesAroundPoint(Location location, double radius) { - List entities = new ArrayList(); - World world = location.getWorld(); + public static List getEntitiesAroundPoint(final Location location, final double radius) { + final List entities = new ArrayList(); + final World world = location.getWorld(); // To find chunks we use chunk coordinates (not block coordinates!) - int smallX = (int) (location.getX() - radius) >> 4; - int bigX = (int) (location.getX() + radius) >> 4; - int smallZ = (int) (location.getZ() - radius) >> 4; - int bigZ = (int) (location.getZ() + radius) >> 4; + final int smallX = (int) (location.getX() - radius) >> 4; + final int bigX = (int) (location.getX() + radius) >> 4; + final int smallZ = (int) (location.getZ() - radius) >> 4; + final int bigZ = (int) (location.getZ() + radius) >> 4; for (int x = smallX; x <= bigX; x++) { for (int z = smallZ; z <= bigZ; z++) { @@ -925,12 +949,12 @@ public static List getEntitiesAroundPoint(Location location, double radi } } - Iterator entityIterator = entities.iterator(); + final Iterator entityIterator = entities.iterator(); while (entityIterator.hasNext()) { - Entity e = entityIterator.next(); + final Entity e = entityIterator.next(); if (e.getWorld().equals(location.getWorld()) && e.getLocation().distanceSquared(location) > radius * radius) { entityIterator.remove(); - } else if (e instanceof Player && ((Player) e).getGameMode().equals(GameMode.SPECTATOR)) { + } else if (e instanceof Player && (((Player) e).isDead() || ((Player) e).getGameMode().equals(GameMode.SPECTATOR))) { entityIterator.remove(); } } @@ -943,20 +967,19 @@ public static long getGlobalCooldown() { } /** - * + * * @param one One location being tested * @param two Another location being tested * @return The horizontal distance between two locations */ - public static double getHorizontalDistance(Location one, Location two) { - double x = one.getX() - two.getX(); - double z = one.getZ() - two.getZ(); + public static double getHorizontalDistance(final Location one, final Location two) { + final double x = one.getX() - two.getX(); + final double z = one.getZ() - two.getZ(); return Math.sqrt((x * x) + (z * z)); } - @SuppressWarnings("incomplete-switch") - public static int getIntCardinalDirection(Vector vector) { - BlockFace face = getCardinalDirection(vector); + public static int getIntCardinalDirection(final Vector vector) { + final BlockFace face = getCardinalDirection(vector); switch (face) { case SOUTH: @@ -975,8 +998,9 @@ public static int getIntCardinalDirection(Vector vector) { return 5; case SOUTH_EAST: return 8; + default: + return 4; } - return 4; } public static Plugin getItems() { @@ -989,12 +1013,12 @@ public static Plugin getItems() { /** * Returns the last ability used by a player. Also checks if a combo was * used. - * + * * @param player The player to check * @return name of last ability used */ - public static String getLastUsedAbility(Player player, boolean checkCombos) { - List lastUsedAbility = ComboManager.getRecentlyUsedAbilities(player, 1); + public static String getLastUsedAbility(final Player player, final boolean checkCombos) { + final List lastUsedAbility = ComboManager.getRecentlyUsedAbilities(player, 1); if (!lastUsedAbility.isEmpty()) { if (ComboManager.checkForValidCombo(player) != null && checkCombos) { return ComboManager.checkForValidCombo(player).getName(); @@ -1008,30 +1032,30 @@ public static String getLastUsedAbility(Player player, boolean checkCombos) { /** * Gets a location with a specified distance away from the left side of a * location. - * + * * @param location The origin location * @param distance The distance to the left * @return the location of the distance to the left */ - public static Location getLeftSide(Location location, double distance) { - float angle = location.getYaw() / 60; + public static Location getLeftSide(final Location location, final double distance) { + final float angle = location.getYaw() / 60; return location.clone().add(new Vector(Math.cos(angle), 0, Math.sin(angle)).normalize().multiply(distance)); } - public static int getMaxPresets(Player player) { + public static int getMaxPresets(final Player player) { if (player.isOp()) { - return 500; + return 100; } int cap = 0; - for (int i = 0; i <= 500; i++) { - if (player.hasPermission("bending.command.presets.create." + i)) { + for (int i = 0; i <= 10; i++) { + if (player.hasPermission("bending.command.preset.create." + i)) { cap = i; } } return cap; } - public static Vector getOrthogonalVector(Vector axis, double degrees, double length) { + public static Vector getOrthogonalVector(final Vector axis, final double degrees, final double length) { Vector ortho = new Vector(axis.getY(), -axis.getX(), 0); ortho = ortho.normalize(); ortho = ortho.multiply(length); @@ -1039,9 +1063,9 @@ public static Vector getOrthogonalVector(Vector axis, double degrees, double len return rotateVectorAroundVector(axis, ortho, degrees); } - public static Collection getPlayersAroundPoint(Location location, double distance) { - Collection players = new HashSet(); - for (Player player : Bukkit.getOnlinePlayers()) { + public static Collection getPlayersAroundPoint(final Location location, final double distance) { + final Collection players = new HashSet(); + for (final Player player : Bukkit.getOnlinePlayers()) { if (player.getLocation().getWorld().equals(location.getWorld())) { if (player.getLocation().distanceSquared(location) <= distance * distance) { players.add(player); @@ -1051,20 +1075,20 @@ public static Collection getPlayersAroundPoint(Location location, double return players; } - public static Location getPointOnLine(Location origin, Location target, double distance) { + public static Location getPointOnLine(final Location origin, final Location target, final double distance) { return origin.clone().add(getDirection(origin, target).normalize().multiply(distance)); } /** * Returns a location with a specified distance away from the right side of * a location. - * + * * @param location The origin location * @param distance The distance to the right * @return the location of the distance to the right */ - public static Location getRightSide(Location location, double distance) { - float angle = location.getYaw() / 60; + public static Location getRightSide(final Location location, final double distance) { + final float angle = location.getYaw() / 60; return location.clone().subtract(new Vector(Math.cos(angle), 0, Math.sin(angle)).normalize().multiply(distance)); } @@ -1089,15 +1113,14 @@ public static Plugin getSpirits() { return null; } - @SuppressWarnings("unused") - public static Entity getTargetedEntity(Player player, double range, List avoid) { + public static Entity getTargetedEntity(final Player player, final double range, final List avoid) { double longestr = range + 1; Entity target = null; - Location origin = player.getEyeLocation(); - Vector direction = player.getEyeLocation().getDirection().normalize(); - for (Entity entity : origin.getWorld().getEntities()) { + final Location origin = player.getEyeLocation(); + final Vector direction = player.getEyeLocation().getDirection().normalize(); + for (final Entity entity : origin.getWorld().getEntities()) { if (entity instanceof Player) { - if (((Player)entity).getGameMode().equals(GameMode.SPECTATOR)) { + if (((Player) entity).isDead() || ((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) { continue; } } @@ -1112,25 +1135,20 @@ public static Entity getTargetedEntity(Player player, double range, List } } if (target != null) { - List blocklist = new ArrayList(); - blocklist = GeneralMethods.getBlocksAlongLine(player.getLocation(), target.getLocation(), player.getWorld()); - for (Block isAir : blocklist) { - if (GeneralMethods.isObstructed(origin, target.getLocation())) { - target = null; - break; - } + if (GeneralMethods.isObstructed(origin, target.getLocation())) { + target = null; } } return target; } - public static Entity getTargetedEntity(Player player, double range) { + public static Entity getTargetedEntity(final Player player, final double range) { return getTargetedEntity(player, range, new ArrayList()); } - public static Location getTargetedLocation(Player player, double originselectrange, Material... nonOpaque2) { - Location origin = player.getEyeLocation(); - Vector direction = origin.getDirection(); + public static Location getTargetedLocation(final Player player, final double originselectrange, final Material... nonOpaque2) { + final Location origin = player.getEyeLocation(); + final Vector direction = origin.getDirection(); HashSet trans = new HashSet(); trans.add(Material.AIR); @@ -1138,26 +1156,26 @@ public static Location getTargetedLocation(Player player, double originselectran if (nonOpaque2 == null) { trans = null; } else { - for (Material material : nonOpaque2) { + for (final Material material : nonOpaque2) { trans.add(material); } } - Block block = player.getTargetBlock(trans, (int) originselectrange + 1); + final Block block = player.getTargetBlock(trans, (int) originselectrange + 1); double distance = originselectrange; if (block.getWorld().equals(origin.getWorld())) { distance = block.getLocation().distance(origin) - 1.5; } - Location location = origin.add(direction.multiply(distance)); + final Location location = origin.add(direction.multiply(distance)); return location; } - public static Location getTargetedLocation(Player player, int range) { + public static Location getTargetedLocation(final Player player, final int range) { return getTargetedLocation(player, range, Material.AIR); } - public static Block getTopBlock(Location loc, int range) { + public static Block getTopBlock(final Location loc, final int range) { return getTopBlock(loc, range, range); } @@ -1165,13 +1183,13 @@ public static Block getTopBlock(Location loc, int range) { * Returns the top block based around loc. PositiveY is the maximum amount * of distance it will check upward. Similarly, negativeY is for downward. */ - public static Block getTopBlock(Location loc, int positiveY, int negativeY) { + public static Block getTopBlock(final Location loc, final int positiveY, final int negativeY) { Block blockHolder = loc.getBlock(); int y = 0; - //Only one of these while statements will go + // Only one of these while statements will go while (blockHolder.getType() != Material.AIR && Math.abs(y) < Math.abs(positiveY)) { y++; - Block tempBlock = loc.clone().add(0, y, 0).getBlock(); + final Block tempBlock = loc.clone().add(0, y, 0).getBlock(); if (tempBlock.getType() == Material.AIR) { return blockHolder; } @@ -1188,13 +1206,13 @@ public static Block getTopBlock(Location loc, int positiveY, int negativeY) { return blockHolder; } - public static Block getBottomBlock(Location loc, int positiveY, int negativeY) { + public static Block getBottomBlock(final Location loc, final int positiveY, final int negativeY) { Block blockHolder = loc.getBlock(); int y = 0; - //Only one of these while statements will go + // Only one of these while statements will go while (blockHolder.getType() != Material.AIR && Math.abs(y) < Math.abs(negativeY)) { y--; - Block tempblock = loc.clone().add(0, y, 0).getBlock(); + final Block tempblock = loc.clone().add(0, y, 0).getBlock(); if (tempblock.getType() == Material.AIR) { return blockHolder; } @@ -1214,18 +1232,23 @@ public static Block getBottomBlock(Location loc, int positiveY, int negativeY) { } public static ArrayList getElementsWithNoWeaponBending() { - ArrayList elements = new ArrayList(); + final ArrayList elements = new ArrayList(); - if (!plugin.getConfig().getBoolean("Properties.Air.CanBendWithWeapons")) + if (!plugin.getConfig().getBoolean("Properties.Air.CanBendWithWeapons")) { elements.add(Element.AIR); - if (!plugin.getConfig().getBoolean("Properties.Water.CanBendWithWeapons")) + } + if (!plugin.getConfig().getBoolean("Properties.Water.CanBendWithWeapons")) { elements.add(Element.WATER); - if (!plugin.getConfig().getBoolean("Properties.Earth.CanBendWithWeapons")) + } + if (!plugin.getConfig().getBoolean("Properties.Earth.CanBendWithWeapons")) { elements.add(Element.EARTH); - if (!plugin.getConfig().getBoolean("Properties.Fire.CanBendWithWeapons")) + } + if (!plugin.getConfig().getBoolean("Properties.Fire.CanBendWithWeapons")) { elements.add(Element.FIRE); - if (!plugin.getConfig().getBoolean("Properties.Chi.CanBendWithWeapons")) + } + if (!plugin.getConfig().getBoolean("Properties.Chi.CanBendWithWeapons")) { elements.add(Element.CHI); + } return elements; } @@ -1246,19 +1269,19 @@ public static boolean hasSpirits() { return Bukkit.getServer().getPluginManager().getPlugin("ProjectKorraSpirits") != null; } - public static boolean isAdjacentToThreeOrMoreSources(Block block) { + public static boolean isAdjacentToThreeOrMoreSources(final Block block) { if (block == null || (TempBlock.isTempBlock(block) && WaterAbility.isBendableWaterTempBlock(block))) { return false; } int sources = 0; - byte full = 0x0; - BlockFace[] faces = { BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH }; - for (BlockFace face : faces) { - Block blocki = block.getRelative(face); + final byte full = 0x0; + final BlockFace[] faces = { BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH }; + for (final BlockFace face : faces) { + final Block blocki = block.getRelative(face); if ((blocki.getType() == Material.LAVA || blocki.getType() == Material.STATIONARY_LAVA) && blocki.getData() == full && EarthPassive.canPhysicsChange(blocki)) { sources++; } - if ((WaterAbility.isWater(blocki) || WaterAbility.isIce(blocki)) && blocki.getData() == full && WaterManipulation.canPhysicsChange(blocki)) { + if ((ElementalAbility.isWater(blocki) || ElementalAbility.isIce(blocki)) && blocki.getData() == full && WaterManipulation.canPhysicsChange(blocki)) { sources++; } } @@ -1269,26 +1292,27 @@ public static boolean isImportEnabled() { return ConfigManager.defaultConfig.get().getBoolean("Properties.ImportEnabled"); } - public static boolean isInteractable(Block block) { + public static boolean isInteractable(final Block block) { return Arrays.asList(INTERACTABLE_MATERIALS).contains(block.getType()); } - public static boolean isObstructed(Location location1, Location location2) { - Vector loc1 = location1.toVector(); - Vector loc2 = location2.toVector(); + public static boolean isObstructed(final Location location1, final Location location2) { + final Vector loc1 = location1.toVector(); + final Vector loc2 = location2.toVector(); - Vector direction = loc2.subtract(loc1); + final Vector direction = loc2.subtract(loc1); direction.normalize(); Location loc; double max = 0; - if (location1.getWorld().equals(location2.getWorld())) + if (location1.getWorld().equals(location2.getWorld())) { max = location1.distance(location2); + } for (double i = 0; i <= max; i++) { loc = location1.clone().add(direction.clone().multiply(i)); - Material type = loc.getBlock().getType(); + final Material type = loc.getBlock().getType(); if (type != Material.AIR && !(ElementalAbility.getTransparentMaterialSet().contains(type) || ElementalAbility.isWater(loc.getBlock()))) { return true; } @@ -1304,15 +1328,15 @@ public static boolean isObstructed(Location location1, Location location2) { * block, instead of doing all 5 of those checks this method will now look * in the map first. */ - public static boolean isRegionProtectedFromBuild(Player player, String ability, Location loc) { + public static boolean isRegionProtectedFromBuild(final Player player, final String ability, final Location loc) { if (!BLOCK_CACHE.containsKey(player.getName())) { BLOCK_CACHE.put(player.getName(), new ConcurrentHashMap()); } - Map blockMap = BLOCK_CACHE.get(player.getName()); - Block block = loc.getBlock(); + final Map blockMap = BLOCK_CACHE.get(player.getName()); + final Block block = loc.getBlock(); if (blockMap.containsKey(block)) { - BlockCacheElement elem = blockMap.get(block); + final BlockCacheElement elem = blockMap.get(block); // both abilities must be equal to each other to use the cache if ((ability == null && elem.getAbility() == null) || (ability != null && elem.getAbility() != null && elem.getAbility().equals(ability))) { @@ -1320,34 +1344,34 @@ public static boolean isRegionProtectedFromBuild(Player player, String ability, } } - boolean value = isRegionProtectedFromBuildPostCache(player, ability, loc); + final boolean value = isRegionProtectedFromBuildPostCache(player, ability, loc); blockMap.put(block, new BlockCacheElement(player, block, ability, value, System.currentTimeMillis())); return value; } - public static boolean isRegionProtectedFromBuild(Ability ability, Location loc) { + public static boolean isRegionProtectedFromBuild(final Ability ability, final Location loc) { return isRegionProtectedFromBuild(ability.getPlayer(), ability.getName(), loc); } - public static boolean isRegionProtectedFromBuild(Player player, Location loc) { + public static boolean isRegionProtectedFromBuild(final Player player, final Location loc) { return isRegionProtectedFromBuild(player, null, loc); } - public static boolean isRegionProtectedFromBuildPostCache(Player player, String ability, Location loc) { - boolean allowHarmless = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.AllowHarmlessAbilities"); - boolean respectWorldGuard = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectWorldGuard"); - boolean respectPreciousStones = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectPreciousStones"); - boolean respectFactions = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectFactions"); - boolean respectTowny = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectTowny"); - boolean respectGriefPrevention = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectGriefPrevention"); - boolean respectLWC = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectLWC"); - boolean respectResidence = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.Residence.Respect"); - boolean respectKingdoms = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.Kingdoms"); + public static boolean isRegionProtectedFromBuildPostCache(final Player player, final String ability, final Location loc) { + final boolean allowHarmless = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.AllowHarmlessAbilities"); + final boolean respectWorldGuard = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectWorldGuard"); + final boolean respectPreciousStones = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectPreciousStones"); + final boolean respectFactions = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectFactions"); + final boolean respectTowny = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectTowny"); + final boolean respectGriefPrevention = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectGriefPrevention"); + final boolean respectLWC = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectLWC"); + final boolean respectResidence = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.Residence.Respect"); + final boolean respectKingdoms = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.Kingdoms"); boolean isIgnite = false; boolean isExplosive = false; boolean isHarmless = false; - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (coreAbil != null) { isIgnite = coreAbil.isIgniteAbility(); isExplosive = coreAbil.isExplosiveAbility(); @@ -1361,25 +1385,25 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String return false; } - PluginManager pm = Bukkit.getPluginManager(); + final PluginManager pm = Bukkit.getPluginManager(); - Plugin wgp = pm.getPlugin("WorldGuard"); - Plugin psp = pm.getPlugin("PreciousStones"); - Plugin fcp = pm.getPlugin("Factions"); - Plugin twnp = pm.getPlugin("Towny"); - Plugin gpp = pm.getPlugin("GriefPrevention"); - Plugin massivecore = pm.getPlugin("MassiveCore"); - Plugin lwc = pm.getPlugin("LWC"); - Plugin residence = pm.getPlugin("Residence"); - Plugin kingdoms = pm.getPlugin("Kingdoms"); + final Plugin wgp = pm.getPlugin("WorldGuard"); + final Plugin psp = pm.getPlugin("PreciousStones"); + final Plugin fcp = pm.getPlugin("Factions"); + final Plugin twnp = pm.getPlugin("Towny"); + final Plugin gpp = pm.getPlugin("GriefPrevention"); + final Plugin massivecore = pm.getPlugin("MassiveCore"); + final Plugin lwc = pm.getPlugin("LWC"); + final Plugin residence = pm.getPlugin("Residence"); + final Plugin kingdoms = pm.getPlugin("Kingdoms"); - for (Location location : new Location[] { loc, player.getLocation() }) { - World world = location.getWorld(); + for (final Location location : new Location[] { loc, player.getLocation() }) { + final World world = location.getWorld(); if (lwc != null && respectLWC) { - LWCPlugin lwcp = (LWCPlugin) lwc; - LWC lwc2 = lwcp.getLWC(); - Protection protection = lwc2.getProtectionCache().getProtection(location.getBlock()); + final LWCPlugin lwcp = (LWCPlugin) lwc; + final LWC lwc2 = lwcp.getLWC(); + final Protection protection = lwc2.getProtectionCache().getProtection(location.getBlock()); if (protection != null) { if (!lwc2.canAccessProtection(player, protection)) { return true; @@ -1387,7 +1411,7 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } } if (wgp != null && respectWorldGuard && !player.hasPermission("worldguard.region.bypass." + world.getName())) { - WorldGuardPlugin wg = (WorldGuardPlugin) Bukkit.getPluginManager().getPlugin("WorldGuard"); + final WorldGuardPlugin wg = (WorldGuardPlugin) Bukkit.getPluginManager().getPlugin("WorldGuard"); if (!player.isOnline()) { return true; } @@ -1414,7 +1438,7 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } if (psp != null && respectPreciousStones) { - PreciousStones ps = (PreciousStones) psp; + final PreciousStones ps = (PreciousStones) psp; if (isIgnite) { if (ps.getForceFieldManager().hasSourceField(location, FieldFlag.PREVENT_FIRE)) { @@ -1439,25 +1463,25 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } if (twnp != null && respectTowny) { - Towny twn = (Towny) twnp; + final Towny twn = (Towny) twnp; WorldCoord worldCoord; try { - TownyWorld tWorld = TownyUniverse.getDataSource().getWorld(world.getName()); + final TownyWorld tWorld = TownyUniverse.getDataSource().getWorld(world.getName()); worldCoord = new WorldCoord(tWorld.getName(), Coord.parseCoord(location)); - boolean bBuild = PlayerCacheUtil.getCachePermission(player, location, 3, (byte) 0, TownyPermission.ActionType.BUILD); + final boolean bBuild = PlayerCacheUtil.getCachePermission(player, location, 3, (byte) 0, TownyPermission.ActionType.BUILD); if (!bBuild) { - PlayerCache cache = twn.getCache(player); - TownBlockStatus status = cache.getStatus(); + final PlayerCache cache = twn.getCache(player); + final TownBlockStatus status = cache.getStatus(); if (((status == TownBlockStatus.ENEMY) && TownyWarConfig.isAllowingAttacks())) { try { TownyWar.callAttackCellEvent(twn, player, location.getBlock(), worldCoord); } - catch (Exception e) { + catch (final Exception e) { TownyMessaging.sendErrorMsg(player, e.getMessage()); } return true; @@ -1472,7 +1496,7 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } } } - catch (Exception e1) { + catch (final Exception e1) { TownyMessaging.sendErrorMsg(player, TownySettings.getLangString("msg_err_not_configured")); } } @@ -1482,9 +1506,9 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String if (type == null) { type = Material.AIR; } - String reason = GriefPrevention.instance.allowBuild(player, location); // WORKING with WorldGuard 6.0 BETA 4 + final String reason = GriefPrevention.instance.allowBuild(player, location); // WORKING with WorldGuard 6.0 BETA 4. - Claim claim = GriefPrevention.instance.dataStore.getClaimAt(loc, true, null); + final Claim claim = GriefPrevention.instance.dataStore.getClaimAt(loc, true, null); if (reason != null && claim != null) { return true; @@ -1492,9 +1516,9 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } if (residence != null && respectResidence) { - ClaimedResidence res = Residence.getResidenceManager().getByLoc(loc); + final ClaimedResidence res = Residence.getResidenceManager().getByLoc(loc); if (res != null) { - ResidencePermissions perms = res.getPermissions(); + final ResidencePermissions perms = res.getPermissions(); if (perms.playerHas(player.getName(), ConfigManager.defaultConfig.get().getString("Properities.RegionProtection.Residence.Flag"), true)) { return true; } @@ -1502,27 +1526,27 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String } if (kingdoms != null && respectKingdoms) { - SimpleLocation location_ = new SimpleLocation(loc); - SimpleChunkLocation chunk = location_.toSimpleChunk(); - Land land = GameManagement.getLandManager().getOrLoadLand(chunk); + final SimpleLocation location_ = new SimpleLocation(loc); + final SimpleChunkLocation chunk = location_.toSimpleChunk(); + final Land land = GameManagement.getLandManager().getOrLoadLand(chunk); if (land.getOwner() != null) { - KingdomPlayer kp = GameManagement.getPlayerManager().getSession(player); + final KingdomPlayer kp = GameManagement.getPlayerManager().getSession(player); if (!kp.isAdminMode()) { if (land.getOwner().equals("SafeZone")) { return true; - } else if (kp.getKingdom() == null) { //If the player isn't in a kingdom but it's claimed land + } else if (kp.getKingdom() == null) { // If the player isn't in a kingdom but it's claimed land. return true; } else { - Kingdom kingdom = kp.getKingdom(); - String kingdomName = kingdom.getKingdomName(); - if (!kingdomName.equals(land.getOwner())) //If the player's kingdom doesn't match + final Kingdom kingdom = kp.getKingdom(); + final String kingdomName = kingdom.getKingdomName(); + if (!kingdomName.equals(land.getOwner())) // If the player's kingdom doesn't match. { return true; } - //If it's within the nexus area, test for higher permission + // If it's within the nexus area, test for higher permission. if (land.getStructure() != null && land.getStructure().getType() == StructureType.NEXUS) { if (!kp.getRank().isHigherOrEqualTo(kingdom.getPermissionsInfo().getBuildInNexus())) { return true; @@ -1536,22 +1560,22 @@ public static boolean isRegionProtectedFromBuildPostCache(Player player, String return false; } - public static boolean isSolid(Block block) { + public static boolean isSolid(final Block block) { return !Arrays.asList(NON_OPAQUE).contains(block.getType()); } /** Checks if an entity is Undead **/ - public static boolean isUndead(Entity entity) { + public static boolean isUndead(final Entity entity) { return entity != null && (entity.getType() == EntityType.ZOMBIE || entity.getType() == EntityType.BLAZE || entity.getType() == EntityType.GIANT || entity.getType() == EntityType.IRON_GOLEM || entity.getType() == EntityType.MAGMA_CUBE || entity.getType() == EntityType.PIG_ZOMBIE || entity.getType() == EntityType.SKELETON || entity.getType() == EntityType.SLIME || entity.getType() == EntityType.SNOWMAN || entity.getType() == EntityType.ZOMBIE); } - public static boolean isWeapon(Material mat) { + public static boolean isWeapon(final Material mat) { return mat != null && (mat == Material.WOOD_AXE || mat == Material.WOOD_PICKAXE || mat == Material.WOOD_SPADE || mat == Material.WOOD_SWORD || mat == Material.STONE_AXE || mat == Material.STONE_PICKAXE || mat == Material.STONE_SPADE || mat == Material.STONE_SWORD || mat == Material.IRON_AXE || mat == Material.IRON_PICKAXE || mat == Material.IRON_SWORD || mat == Material.IRON_SPADE || mat == Material.DIAMOND_AXE || mat == Material.DIAMOND_PICKAXE || mat == Material.DIAMOND_SWORD || mat == Material.DIAMOND_SPADE || mat == Material.GOLD_AXE || mat == Material.GOLD_HOE || mat == Material.GOLD_SWORD || mat == Material.GOLD_PICKAXE || mat == Material.GOLD_SPADE); } - public static void loadBendingPlayer(BendingPlayer pl) { - Player player = Bukkit.getPlayer(pl.getUUID()); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void loadBendingPlayer(final BendingPlayer pl) { + final Player player = Bukkit.getPlayer(pl.getUUID()); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; @@ -1566,7 +1590,7 @@ public static void loadBendingPlayer(BendingPlayer pl) { Element element = null; String prefix = ""; - boolean chatEnabled = ConfigManager.languageConfig.get().getBoolean("Chat.Enable"); + final boolean chatEnabled = ConfigManager.languageConfig.get().getBoolean("Chat.Enable"); if (bPlayer.getElements().size() > 1) { prefix = Element.AVATAR.getPrefix(); } else if (bPlayer.getElements().size() == 1) { @@ -1581,10 +1605,10 @@ public static void loadBendingPlayer(BendingPlayer pl) { player.setDisplayName(prefix + ChatColor.RESET + player.getDisplayName()); } - // Handle the AirSpout/WaterSpout login glitches + // Handle the AirSpout/WaterSpout login glitches. if (player.getGameMode() != GameMode.CREATIVE) { - HashMap bound = bPlayer.getAbilities(); - for (String str : bound.values()) { + final HashMap bound = bPlayer.getAbilities(); + for (final String str : bound.values()) { if (str.equalsIgnoreCase("AirSpout") || str.equalsIgnoreCase("WaterSpout") || str.equalsIgnoreCase("SandSpout")) { final Player fplayer = player; new BukkitRunnable() { @@ -1601,15 +1625,15 @@ public void run() { Bukkit.getServer().getPluginManager().callEvent(new BendingPlayerCreationEvent(bPlayer)); } - public static void reloadPlugin(CommandSender sender) { + public static void reloadPlugin(final CommandSender sender) { ProjectKorra.log.info("Reloading ProjectKorra and configuration"); - BendingReloadEvent event = new BendingReloadEvent(sender); + final BendingReloadEvent event = new BendingReloadEvent(sender); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { sender.sendMessage(ChatColor.RED + "Reload event cancelled"); return; } - if (DBConnection.isOpen) { + if (DBConnection.isOpen()) { DBConnection.sql.close(); } GeneralMethods.stopBending(); @@ -1625,21 +1649,16 @@ public static void reloadPlugin(CommandSender sender) { ProjectKorra.collisionInitializer = new CollisionInitializer(ProjectKorra.collisionManager); CoreAbility.registerAbilities(); reloadAddonPlugins(); - ProjectKorra.collisionInitializer.initializeDefaultCollisions(); // must be called after abilities have been registered + ProjectKorra.collisionInitializer.initializeDefaultCollisions(); // must be called after abilities have been registered. ProjectKorra.collisionManager.startCollisionDetection(); - DBConnection.host = ConfigManager.defaultConfig.get().getString("Storage.MySQL.host"); - DBConnection.port = ConfigManager.defaultConfig.get().getInt("Storage.MySQL.port"); - DBConnection.pass = ConfigManager.defaultConfig.get().getString("Storage.MySQL.pass"); - DBConnection.db = ConfigManager.defaultConfig.get().getString("Storage.MySQL.db"); - DBConnection.user = ConfigManager.defaultConfig.get().getString("Storage.MySQL.user"); DBConnection.init(); if (!DBConnection.isOpen()) { ProjectKorra.log.severe("Unable to enable ProjectKorra due to the database not being open"); stopPlugin(); } - for (Player player : Bukkit.getOnlinePlayers()) { + for (final Player player : Bukkit.getOnlinePlayers()) { Preset.unloadPreset(player); GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); PassiveManager.registerPassives(player); @@ -1647,20 +1666,20 @@ public static void reloadPlugin(CommandSender sender) { plugin.updater.checkUpdate(); ProjectKorra.log.info("Reload complete"); } - + public static void reloadAddonPlugins() { - for (int i = CoreAbility.getAddonPlugins().size()-1; i > -1; i--) { - String entry = CoreAbility.getAddonPlugins().get(i); - String[] split = entry.split("::"); + for (int i = CoreAbility.getAddonPlugins().size() - 1; i > -1; i--) { + final String entry = CoreAbility.getAddonPlugins().get(i); + final String[] split = entry.split("::"); if (Bukkit.getServer().getPluginManager().isPluginEnabled(split[0])) { - CoreAbility.registerPluginAbilities((JavaPlugin)Bukkit.getServer().getPluginManager().getPlugin(split[0]), split[1]); + CoreAbility.registerPluginAbilities((JavaPlugin) Bukkit.getServer().getPluginManager().getPlugin(split[0]), split[1]); } else { CoreAbility.getAddonPlugins().remove(i); } } } - public static void removeBlock(Block block) { + public static void removeBlock(final Block block) { if (isAdjacentToThreeOrMoreSources(block)) { block.setType(Material.WATER); block.setData((byte) 0x0); @@ -1669,29 +1688,49 @@ public static void removeBlock(Block block) { } } - public static void removeUnusableAbilities(String player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void removeUnusableAbilities(final String player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } - HashMap slots = bPlayer.getAbilities(); - HashMap finalAbilities = new HashMap(); - for (int i : slots.keySet()) { + // Remove all active instances of abilities that will become unusable. + // We need to do this prior to filtering binds in case the player has a MultiAbility running. + for (final CoreAbility coreAbility : CoreAbility.getAbilities()) { + final CoreAbility playerAbility = CoreAbility.getAbility(bPlayer.getPlayer(), coreAbility.getClass()); + if (playerAbility != null) { + if (playerAbility instanceof PassiveAbility && PassiveManager.hasPassive(bPlayer.getPlayer(), playerAbility)) { + // The player will be able to keep using the given PassiveAbility. + continue; + } else if (bPlayer.canBend(playerAbility)) { + // The player will still be able to use this given Ability, do not end it. + continue; + } + + playerAbility.remove(); + } + } + + // Remove all bound abilities that will become unusable. + final HashMap slots = bPlayer.getAbilities(); + final HashMap finalAbilities = new HashMap(); + for (final int i : slots.keySet()) { if (bPlayer.canBind(CoreAbility.getAbility(slots.get(i)))) { + // The player will still be able to use this given Ability, do not remove it from their binds. finalAbilities.put(i, slots.get(i)); } } + bPlayer.setAbilities(finalAbilities); } - public static Vector rotateVectorAroundVector(Vector axis, Vector rotator, double degrees) { - double angle = Math.toRadians(degrees); + public static Vector rotateVectorAroundVector(final Vector axis, final Vector rotator, final double degrees) { + final double angle = Math.toRadians(degrees); Vector rotation = axis.clone(); - Vector rotate = rotator.clone(); + final Vector rotate = rotator.clone(); rotation = rotation.normalize(); - Vector thirdaxis = rotation.crossProduct(rotate).normalize().multiply(rotate.length()); + final Vector thirdaxis = rotation.crossProduct(rotate).normalize().multiply(rotate.length()); return rotate.multiply(Math.cos(angle)).add(thirdaxis.multiply(Math.sin(angle))); } @@ -1699,17 +1738,17 @@ public static Vector rotateVectorAroundVector(Vector axis, Vector rotator, doubl /** * Rotates a vector around the Y plane. */ - public static Vector rotateXZ(Vector vec, double theta) { - Vector vec2 = vec.clone(); - double x = vec2.getX(); - double z = vec2.getZ(); + public static Vector rotateXZ(final Vector vec, final double theta) { + final Vector vec2 = vec.clone(); + final double x = vec2.getX(); + final double z = vec2.getZ(); vec2.setX(x * Math.cos(Math.toRadians(theta)) - z * Math.sin(Math.toRadians(theta))); vec2.setZ(x * Math.sin(Math.toRadians(theta)) + z * Math.cos(Math.toRadians(theta))); return vec2; } public static void runDebug() { - File debugFile = new File(plugin.getDataFolder(), "debug.txt"); + final File debugFile = new File(plugin.getDataFolder(), "debug.txt"); if (debugFile.exists()) { debugFile.delete(); // We're starting brand new. } @@ -1725,7 +1764,7 @@ public static void runDebug() { writeToDebug("===================="); writeToDebug("Version: " + plugin.getDescription().getVersion()); writeToDebug("Author: " + plugin.getDescription().getAuthors()); - List officialSidePlugins = new ArrayList(); + final List officialSidePlugins = new ArrayList(); if (hasRPG()) { officialSidePlugins.add("ProjectKorra RPG v" + getRPG().getDescription().getVersion()); } @@ -1742,7 +1781,7 @@ public static void runDebug() { writeToDebug(""); writeToDebug("ProjectKorra (Side Plugin) Information"); writeToDebug("===================="); - for (String line : officialSidePlugins) { + for (final String line : officialSidePlugins) { writeToDebug(line); } } @@ -1751,21 +1790,21 @@ public static void runDebug() { writeToDebug("Supported Plugins"); writeToDebug("===================="); - boolean respectWorldGuard = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectWorldGuard"); - boolean respectPreciousStones = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectPreciousStones"); - boolean respectFactions = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectFactions"); - boolean respectTowny = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectTowny"); - boolean respectGriefPrevention = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectGriefPrevention"); - boolean respectLWC = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectLWC"); - PluginManager pm = Bukkit.getPluginManager(); - - Plugin wgp = pm.getPlugin("WorldGuard"); - Plugin psp = pm.getPlugin("PreciousStones"); - Plugin fcp = pm.getPlugin("Factions"); - Plugin twnp = pm.getPlugin("Towny"); - Plugin gpp = pm.getPlugin("GriefPrevention"); - Plugin massivecore = pm.getPlugin("MassiveCore"); - Plugin lwc = pm.getPlugin("LWC"); + final boolean respectWorldGuard = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectWorldGuard"); + final boolean respectPreciousStones = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectPreciousStones"); + final boolean respectFactions = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectFactions"); + final boolean respectTowny = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectTowny"); + final boolean respectGriefPrevention = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectGriefPrevention"); + final boolean respectLWC = ConfigManager.defaultConfig.get().getBoolean("Properties.RegionProtection.RespectLWC"); + final PluginManager pm = Bukkit.getPluginManager(); + + final Plugin wgp = pm.getPlugin("WorldGuard"); + final Plugin psp = pm.getPlugin("PreciousStones"); + final Plugin fcp = pm.getPlugin("Factions"); + final Plugin twnp = pm.getPlugin("Towny"); + final Plugin gpp = pm.getPlugin("GriefPrevention"); + final Plugin massivecore = pm.getPlugin("MassiveCore"); + final Plugin lwc = pm.getPlugin("LWC"); if (wgp != null && respectWorldGuard) { writeToDebug("WorldGuard v" + wgp.getDescription().getVersion()); @@ -1793,8 +1832,8 @@ public static void runDebug() { writeToDebug("Plugins Hooking Into ProjectKorra (Core)"); writeToDebug("===================="); - String[] pkPlugins = new String[] { "projectkorrarpg", "projectkorraitems", "projectkorraspirits", "probending" }; - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + final String[] pkPlugins = new String[] { "projectkorrarpg", "projectkorraitems", "projectkorraspirits", "probending" }; + for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (plugin.getDescription().getDepend() != null && plugin.getDescription().getDepend().contains("ProjectKorra") && !Arrays.asList(pkPlugins).contains(plugin.getName().toLowerCase())) { writeToDebug(plugin.getDescription().getName() + " v" + plugin.getDescription().getVersion()); } @@ -1803,9 +1842,9 @@ public static void runDebug() { writeToDebug(""); writeToDebug("Ability Information"); writeToDebug("===================="); - ArrayList stockAbils = new ArrayList(); - ArrayList unofficialAbils = new ArrayList(); - for (CoreAbility ability : CoreAbility.getAbilities()) { + final ArrayList stockAbils = new ArrayList(); + final ArrayList unofficialAbils = new ArrayList(); + for (final CoreAbility ability : CoreAbility.getAbilities()) { if (ability.getClass().getPackage().getName().startsWith("com.projectkorra")) { stockAbils.add(ability.getName()); } else { @@ -1814,13 +1853,13 @@ public static void runDebug() { } if (!stockAbils.isEmpty()) { Collections.sort(stockAbils); - for (String ability : stockAbils) { + for (final String ability : stockAbils) { writeToDebug(ability + " - STOCK"); } } if (!unofficialAbils.isEmpty()) { Collections.sort(unofficialAbils); - for (String ability : unofficialAbils) { + for (final String ability : unofficialAbils) { writeToDebug(ability + " - UNOFFICAL"); } } @@ -1828,69 +1867,69 @@ public static void runDebug() { writeToDebug(""); writeToDebug("Collection Sizes"); writeToDebug("===================="); - ClassLoader loader = ProjectKorra.class.getClassLoader(); + final ClassLoader loader = ProjectKorra.class.getClassLoader(); try { for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) { if (info.getName().startsWith("com.projectkorra.")) { final Class clazz = info.load(); - for (Field field : clazz.getDeclaredFields()) { - String simpleName = clazz.getSimpleName(); + for (final Field field : clazz.getDeclaredFields()) { + final String simpleName = clazz.getSimpleName(); field.setAccessible(true); try { - Object obj = field.get(null); + final Object obj = field.get(null); if (obj instanceof Collection) { writeToDebug(simpleName + ": " + field.getName() + " size=" + ((Collection) obj).size()); } else if (obj instanceof Map) { writeToDebug(simpleName + ": " + field.getName() + " size=" + ((Map) obj).size()); } } - catch (Exception e) { + catch (final Exception e) { } } } } } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } writeToDebug(""); writeToDebug("CoreAbility Debugger"); writeToDebug("===================="); - for (String line : CoreAbility.getDebugString().split("\\n")) { + for (final String line : CoreAbility.getDebugString().split("\\n")) { writeToDebug(line); } } - public static void saveAbility(BendingPlayer bPlayer, int slot, String ability) { + public static void saveAbility(final BendingPlayer bPlayer, final int slot, final String ability) { if (bPlayer == null) { return; } - String uuid = bPlayer.getUUIDString(); + final String uuid = bPlayer.getUUIDString(); - BindChangeEvent event = new BindChangeEvent(Bukkit.getPlayer(UUID.fromString(uuid)), ability, slot, false); + final BindChangeEvent event = new BindChangeEvent(Bukkit.getPlayer(UUID.fromString(uuid)), ability, slot, false); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { return; } - //Temp code to block modifications of binds, Should be replaced when bind event is added. + // Temp code to block modifications of binds, Should be replaced when bind event is added. if (MultiAbilityManager.playerAbilities.containsKey(Bukkit.getPlayer(bPlayer.getUUID()))) { return; } - HashMap abilities = bPlayer.getAbilities(); + final HashMap abilities = bPlayer.getAbilities(); DBConnection.sql.modifyQuery("UPDATE pk_players SET slot" + slot + " = '" + (abilities.get(slot) == null ? null : abilities.get(slot)) + "' WHERE uuid = '" + uuid + "'"); } - public static void saveElements(BendingPlayer bPlayer) { + public static void saveElements(final BendingPlayer bPlayer) { if (bPlayer == null) { return; } - String uuid = bPlayer.getUUIDString(); + final String uuid = bPlayer.getUUIDString(); - StringBuilder elements = new StringBuilder(); + final StringBuilder elements = new StringBuilder(); if (bPlayer.hasElement(Element.AIR)) { elements.append("a"); } @@ -1907,7 +1946,7 @@ public static void saveElements(BendingPlayer bPlayer) { elements.append("c"); } boolean hasAddon = false; - for (Element element : bPlayer.getElements()) { + for (final Element element : bPlayer.getElements()) { if (Arrays.asList(Element.getAddonElements()).contains(element)) { if (!hasAddon) { hasAddon = true; @@ -1916,7 +1955,7 @@ public static void saveElements(BendingPlayer bPlayer) { elements.append(element.getName() + ","); } } - + if (elements.length() == 0) { elements.append("NULL"); } @@ -1924,13 +1963,13 @@ public static void saveElements(BendingPlayer bPlayer) { DBConnection.sql.modifyQuery("UPDATE pk_players SET element = '" + elements.toString() + "' WHERE uuid = '" + uuid + "'"); } - public static void saveSubElements(BendingPlayer bPlayer) { + public static void saveSubElements(final BendingPlayer bPlayer) { if (bPlayer == null) { return; } - String uuid = bPlayer.getUUIDString(); + final String uuid = bPlayer.getUUIDString(); - StringBuilder subs = new StringBuilder(); + final StringBuilder subs = new StringBuilder(); if (bPlayer.hasSubElement(Element.METAL)) { subs.append("m"); } @@ -1965,7 +2004,7 @@ public static void saveSubElements(BendingPlayer bPlayer) { subs.append("p"); } boolean hasAddon = false; - for (Element element : bPlayer.getSubElements()) { + for (final Element element : bPlayer.getSubElements()) { if (Arrays.asList(Element.getAddonSubElements()).contains(element)) { if (!hasAddon) { hasAddon = true; @@ -1974,24 +2013,24 @@ public static void saveSubElements(BendingPlayer bPlayer) { subs.append(element.getName() + ","); } } - + if (subs.length() == 0) { subs.append("NULL"); } - + DBConnection.sql.modifyQuery("UPDATE pk_players SET subelement = '" + subs.toString() + "' WHERE uuid = '" + uuid + "'"); } - public static void savePermaRemoved(BendingPlayer bPlayer) { + public static void savePermaRemoved(final BendingPlayer bPlayer) { if (bPlayer == null) { return; } - String uuid = bPlayer.getUUIDString(); - boolean permaRemoved = bPlayer.isPermaRemoved(); + final String uuid = bPlayer.getUUIDString(); + final boolean permaRemoved = bPlayer.isPermaRemoved(); DBConnection.sql.modifyQuery("UPDATE pk_players SET permaremoved = '" + (permaRemoved ? "true" : "false") + "' WHERE uuid = '" + uuid + "'"); } - public static void setVelocity(Entity entity, Vector velocity) { + public static void setVelocity(final Entity entity, final Vector velocity) { if (entity instanceof TNTPrimed) { if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingAffectFallingSand.TNT")) { entity.setVelocity(velocity.multiply(ConfigManager.defaultConfig.get().getDouble("Properties.BendingAffectFallingSand.TNTStrengthMultiplier"))); @@ -2027,58 +2066,59 @@ public static void setVelocity(Entity entity, Vector velocity) { entity.setVelocity(velocity); } - public static FallingBlock spawnFallingBlock(Location loc, int type) { + public static FallingBlock spawnFallingBlock(final Location loc, final int type) { return spawnFallingBlock(loc, type, (byte) 0); } - public static FallingBlock spawnFallingBlock(Location loc, int type, byte data) { + public static FallingBlock spawnFallingBlock(final Location loc, final int type, final byte data) { return loc.getWorld().spawnFallingBlock(loc, type, data); } - public static FallingBlock spawnFallingBlock(Location loc, Material type) { + public static FallingBlock spawnFallingBlock(final Location loc, final Material type) { return spawnFallingBlock(loc, type, (byte) 0); } - public static FallingBlock spawnFallingBlock(Location loc, Material type, byte data) { + public static FallingBlock spawnFallingBlock(final Location loc, final Material type, final byte data) { return loc.getWorld().spawnFallingBlock(loc, type, data); } - public static void sendBrandingMessage(CommandSender sender, String message) { + public static void sendBrandingMessage(final CommandSender sender, final String message) { ChatColor color; try { color = ChatColor.valueOf(ConfigManager.languageConfig.get().getString("Chat.Branding.Color").toUpperCase()); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { color = ChatColor.GOLD; } - - String prefix = ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Branding.ChatPrefix.Prefix")) + color + "ProjectKorra" + ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Branding.ChatPrefix.Suffix")); + + final String prefix = ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Branding.ChatPrefix.Prefix")) + color + "ProjectKorra" + ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Branding.ChatPrefix.Suffix")); if (!(sender instanceof Player)) { sender.sendMessage(prefix + message); } else { - TextComponent prefixComponent = new TextComponent(prefix); + final TextComponent prefixComponent = new TextComponent(prefix); prefixComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "http://projectkorra.com/")); prefixComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(color + "Bending brought to you by ProjectKorra!\n" + color + "Click for more info.").create())); /* * The commented code below does not work due to an issue with * Spigot. In the mean time, we'll have to use this incredibly - * 'hacky' method to force the colour on the new line. + * 'hacky' method to force the color on the new line. */ String lastColor = ""; String newMessage = ""; for (int i = 0; i < message.split("").length; i++) { - String c = message.split("")[i]; + final String c = message.split("")[i]; if (c.equalsIgnoreCase("§")) { lastColor = "§" + message.split("")[i + 1]; newMessage = newMessage + c; - } else if (c.equalsIgnoreCase(" ")) { //Add color every word + } else if (c.equalsIgnoreCase(" ")) { // Add color every word newMessage = newMessage + " " + lastColor; } else { newMessage = newMessage + c; } } - TextComponent messageComponent = new TextComponent(newMessage); + final TextComponent messageComponent = new TextComponent(newMessage); ((Player) sender).spigot().sendMessage(new TextComponent(prefixComponent, messageComponent)); /* * boolean prefixSent = false; for (String msg : @@ -2096,10 +2136,9 @@ public static void startCacheCleaner(final double period) { new BukkitRunnable() { @Override public void run() { - for (Map map : BLOCK_CACHE.values()) { - for (Iterator i = map.keySet().iterator(); i.hasNext();) { - Block key = i.next(); - BlockCacheElement value = map.get(key); + for (final Map map : BLOCK_CACHE.values()) { + for (final Block key : map.keySet()) { + final BlockCacheElement value = map.get(key); if (System.currentTimeMillis() - value.getTime() > period) { map.remove(key); @@ -2111,7 +2150,7 @@ public void run() { } public static void stopBending() { - for (CoreAbility ability : CoreAbility.getAbilities()) { + for (final CoreAbility ability : CoreAbility.getAbilities()) { if (ability instanceof AddonAbility) { ((AddonAbility) ability).stop(); } @@ -2122,9 +2161,10 @@ public static void stopBending() { WaterAbility.stopBending(); FireAbility.stopBending(); - Flight.removeAll(); TempBlock.removeAll(); TempArmor.revertAll(); + TempArmorStand.removeAll(); + MovementHandler.resetAll(); MultiAbilityManager.removeAll(); if (!INVINCIBLE.isEmpty()) { INVINCIBLE.clear(); @@ -2135,26 +2175,26 @@ public static void stopPlugin() { plugin.getServer().getPluginManager().disablePlugin(plugin); } - public static void writeToDebug(String message) { + public static void writeToDebug(final String message) { try { - File dataFolder = plugin.getDataFolder(); + final File dataFolder = plugin.getDataFolder(); if (!dataFolder.exists()) { dataFolder.mkdir(); } - File saveTo = new File(plugin.getDataFolder(), "debug.txt"); + final File saveTo = new File(plugin.getDataFolder(), "debug.txt"); if (!saveTo.exists()) { saveTo.createNewFile(); } - FileWriter fw = new FileWriter(saveTo, true); - PrintWriter pw = new PrintWriter(fw); + final FileWriter fw = new FileWriter(saveTo, true); + final PrintWriter pw = new PrintWriter(fw); pw.println(message); pw.flush(); pw.close(); } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/PKListener.java b/src/com/projectkorra/projectkorra/PKListener.java index b22c81739..4f311cb03 100644 --- a/src/com/projectkorra/projectkorra/PKListener.java +++ b/src/com/projectkorra/projectkorra/PKListener.java @@ -13,7 +13,6 @@ import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Sound; import org.bukkit.Statistic; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; @@ -46,17 +45,18 @@ import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.EntityTargetLivingEntityEvent; import org.bukkit.event.entity.EntityTeleportEvent; +import org.bukkit.event.entity.EntityToggleGlideEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.entity.ProjectileLaunchEvent; import org.bukkit.event.entity.SlimeSplitEvent; import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryType.SlotType; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerAnimationEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemDamageEvent; import org.bukkit.event.player.PlayerItemHeldEvent; @@ -64,6 +64,7 @@ import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.event.player.PlayerToggleFlightEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.inventory.EquipmentSlot; @@ -94,7 +95,7 @@ import com.projectkorra.projectkorra.airbending.AirSwipe; import com.projectkorra.projectkorra.airbending.Suffocate; import com.projectkorra.projectkorra.airbending.Tornado; -import com.projectkorra.projectkorra.airbending.flight.AirFlight; +import com.projectkorra.projectkorra.airbending.flight.FlightMultiAbility; import com.projectkorra.projectkorra.airbending.passive.GracefulDescent; import com.projectkorra.projectkorra.avatar.AvatarState; import com.projectkorra.projectkorra.chiblocking.AcrobatStance; @@ -115,12 +116,14 @@ import com.projectkorra.projectkorra.earthbending.EarthArmor; import com.projectkorra.projectkorra.earthbending.EarthBlast; import com.projectkorra.projectkorra.earthbending.EarthGrab; +import com.projectkorra.projectkorra.earthbending.EarthGrab.GrabMode; import com.projectkorra.projectkorra.earthbending.EarthSmash; import com.projectkorra.projectkorra.earthbending.EarthTunnel; import com.projectkorra.projectkorra.earthbending.RaiseEarth; import com.projectkorra.projectkorra.earthbending.RaiseEarthWall; import com.projectkorra.projectkorra.earthbending.Shockwave; import com.projectkorra.projectkorra.earthbending.Tremorsense; +import com.projectkorra.projectkorra.earthbending.combo.EarthPillars; import com.projectkorra.projectkorra.earthbending.lava.LavaFlow; import com.projectkorra.projectkorra.earthbending.lava.LavaFlow.AbilityType; import com.projectkorra.projectkorra.earthbending.lava.LavaSurge; @@ -150,15 +153,17 @@ import com.projectkorra.projectkorra.firebending.WallOfFire; import com.projectkorra.projectkorra.firebending.combustion.Combustion; import com.projectkorra.projectkorra.firebending.lightning.Lightning; +import com.projectkorra.projectkorra.firebending.passive.FirePassive; import com.projectkorra.projectkorra.firebending.util.FireDamageTimer; import com.projectkorra.projectkorra.object.HorizontalVelocityTracker; import com.projectkorra.projectkorra.object.Preset; import com.projectkorra.projectkorra.util.BlockSource; import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.Flight; +import com.projectkorra.projectkorra.util.FlightHandler.Flight; import com.projectkorra.projectkorra.util.MovementHandler; import com.projectkorra.projectkorra.util.PassiveHandler; +import com.projectkorra.projectkorra.util.StatisticsMethods; import com.projectkorra.projectkorra.util.TempArmor; import com.projectkorra.projectkorra.util.TempBlock; import com.projectkorra.projectkorra.waterbending.OctopusForm; @@ -175,12 +180,11 @@ import com.projectkorra.projectkorra.waterbending.ice.PhaseChange; import com.projectkorra.projectkorra.waterbending.ice.PhaseChange.PhaseChangeType; import com.projectkorra.projectkorra.waterbending.multiabilities.WaterArms; -import com.projectkorra.projectkorra.waterbending.passive.Hydrosink; -import com.projectkorra.projectkorra.waterbending.passive.WaterPassive; +import com.projectkorra.projectkorra.waterbending.passive.FastSwim; +import com.projectkorra.projectkorra.waterbending.passive.HydroSink; import com.projectkorra.rpg.RPGMethods; public class PKListener implements Listener { - ProjectKorra plugin; private static final HashMap BENDING_ENTITY_DEATH = new HashMap<>(); // Entities killed by Bending. @@ -189,22 +193,18 @@ public class PKListener implements Listener { private static final ArrayList TOGGLED_OUT = new ArrayList<>(); // Stands for toggled = false while logging out. private static final Map JUMPS = new HashMap<>(); - public PKListener(ProjectKorra plugin) { + public PKListener(final ProjectKorra plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (event.isCancelled()) { - return; - } - - Block block = event.getBlock(); - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - String abil = bPlayer.getBoundAbilityName(); + public void onBlockBreak(final BlockBreakEvent event) { + final Block block = event.getBlock(); + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final String abil = bPlayer.getBoundAbilityName(); CoreAbility ability = null; - + if (bPlayer.isElementToggled(Element.WATER) && bPlayer.isToggled()) { if (abil != null && abil.equalsIgnoreCase("Surge")) { ability = CoreAbility.getAbility(SurgeWall.class); @@ -213,14 +213,14 @@ public void onBlockBreak(BlockBreakEvent event) { } else { ability = CoreAbility.getAbility(abil); } - + if (ability != null && ability instanceof WaterAbility && !((WaterAbility) ability).allowBreakPlants() && WaterAbility.isPlantbendable(player, block.getType(), false)) { event.setCancelled(true); return; } } - EarthBlast blast = EarthBlast.getBlastFromSource(block); + final EarthBlast blast = EarthBlast.getBlastFromSource(block); if (blast != null) { blast.remove(); } @@ -230,39 +230,40 @@ public void onBlockBreak(BlockBreakEvent event) { event.setCancelled(true); } } else if (SurgeWall.getWallBlocks().containsKey(block)) { - SurgeWall.thaw(block); event.setCancelled(true); - } else if (TempBlock.isTempBlock(block) && Illumination.getBlocks().containsKey(TempBlock.get(block))) { + } else if (Illumination.isIlluminationTorch(block)) { event.setCancelled(true); } else if (!SurgeWave.canThaw(block)) { SurgeWave.thaw(block); event.setCancelled(true); + } else if (LavaFlow.isLavaFlowBlock(block)) { + LavaFlow.removeBlock(block); } else if (EarthAbility.getMovedEarth().containsKey(block)) { EarthAbility.removeRevertIndex(block); } else if (TempBlock.isTempBlock(block)) { + event.setCancelled(true); TempBlock.revertBlock(block, Material.AIR); - } else if (EarthPassive.isPassiveSand(block)) { - EarthPassive.revertSand(block); + } else if (DensityShift.isPassiveSand(block)) { + DensityShift.revertSand(block); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockFlowTo(BlockFromToEvent event) { - if (event.isCancelled()) { - return; - } - Block toblock = event.getToBlock(); - Block fromblock = event.getBlock(); + public void onBlockFlowTo(final BlockFromToEvent event) { + final Block toblock = event.getToBlock(); + final Block fromblock = event.getBlock(); if (ElementalAbility.isLava(fromblock)) { event.setCancelled(!EarthPassive.canFlowFromTo(fromblock, toblock)); } + if (ElementalAbility.isWater(fromblock)) { event.setCancelled(!WaterBubble.isAir(toblock)); if (!event.isCancelled()) { event.setCancelled(!WaterManipulation.canFlowFromTo(fromblock, toblock)); } + if (!event.isCancelled()) { - if (TempBlock.isTempBlock(toblock) && Illumination.getBlocks().containsKey(TempBlock.get(toblock))) { + if (Illumination.isIlluminationTorch(toblock)) { toblock.setType(Material.AIR); } } @@ -270,86 +271,81 @@ public void onBlockFlowTo(BlockFromToEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockForm(BlockFormEvent event) { - if (event.isCancelled()) { - return; - } + public void onBlockForm(final BlockFormEvent event) { if (TempBlock.isTempBlock(event.getBlock())) { event.setCancelled(true); } + if (!WaterManipulation.canPhysicsChange(event.getBlock())) { event.setCancelled(true); } + if (!EarthPassive.canPhysicsChange(event.getBlock())) { event.setCancelled(true); } + if (event.getBlock().getType().toString().equals("CONCRETE_POWDER")) { - BlockFace[] faces = new BlockFace[] {BlockFace.UP, BlockFace.DOWN, BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH}; - + final BlockFace[] faces = new BlockFace[] { BlockFace.UP, BlockFace.DOWN, BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH }; + boolean marked = true; - for (BlockFace face : faces) { - Block b = event.getBlock().getRelative(face); + for (final BlockFace face : faces) { + final Block b = event.getBlock().getRelative(face); if (b.getType() == Material.WATER || b.getType() == Material.STATIONARY_WATER) { if (!TempBlock.isTempBlock(b)) { - marked = false; //if there is any normal water around it, prevent it. + marked = false; // if there is any normal water around it, prevent it. break; } } } - + if (marked) { - event.setCancelled(true); + event.setCancelled(true); } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockIgnite(BlockIgniteEvent event) { - if (event.isCancelled()) { - return; - } + public void onBlockIgnite(final BlockIgniteEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockMeltEvent(BlockFadeEvent event) { - if (event.isCancelled()) { - return; - } - - Block block = event.getBlock(); + public void onBlockMeltEvent(final BlockFadeEvent event) { + final Block block = event.getBlock(); if (block.getType() == Material.FIRE) { return; } - event.setCancelled(TempBlock.isTempBlock(block) && Illumination.getBlocks().containsKey(TempBlock.get(block))); + + event.setCancelled(Illumination.isIlluminationTorch(block)); if (!event.isCancelled()) { event.setCancelled(!WaterManipulation.canPhysicsChange(block)); } + if (!event.isCancelled()) { event.setCancelled(!EarthPassive.canPhysicsChange(block)); } + if (!event.isCancelled()) { event.setCancelled(PhaseChange.getFrozenBlocksAsBlock().contains(block)); } + if (!event.isCancelled()) { event.setCancelled(!SurgeWave.canThaw(block)); } + if (!event.isCancelled()) { event.setCancelled(!Torrent.canThaw(block)); } + if (BlazeArc.getIgnitedBlocks().containsKey(block)) { BlazeArc.removeBlock(block); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPhysics(BlockPhysicsEvent event) { - if (event.isCancelled()) { - return; - } - - Block block = event.getBlock(); + public void onBlockPhysics(final BlockPhysicsEvent event) { + final Block block = event.getBlock(); - if (!WaterManipulation.canPhysicsChange(block) || !EarthPassive.canPhysicsChange(block) || (TempBlock.isTempBlock(block) && Illumination.getBlocks().containsKey(TempBlock.get(block))) || EarthAbility.getPreventPhysicsBlocks().contains(block)) { + if (!WaterManipulation.canPhysicsChange(block) || !EarthPassive.canPhysicsChange(block) || Illumination.isIlluminationTorch(block) || EarthAbility.getPreventPhysicsBlocks().contains(block)) { event.setCancelled(true); } @@ -360,24 +356,37 @@ public void onBlockPhysics(BlockPhysicsEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (event.isCancelled()) { - return; - } - Player player = event.getPlayer(); + public void onBlockPlace(final BlockPlaceEvent event) { + final Player player = event.getPlayer(); if (MovementHandler.isStopped(player) || Bloodbending.isBloodbent(player) || Suffocate.isBreathbent(player)) { event.setCancelled(true); + return; + } + + if (TempBlock.isTempBlock(event.getBlock())) { + final TempBlock tb = TempBlock.get(event.getBlock()); + tb.revertBlock(); + event.getBlock().setType(event.getItemInHand().getType()); + if (event.getPlayer().getGameMode() != GameMode.CREATIVE) { + if (event.getItemInHand().getAmount() <= 0) { + event.getItemInHand().setType(Material.AIR); + event.getItemInHand().setAmount(1); + } else { + event.getItemInHand().setAmount(event.getItemInHand().getAmount() - 1); + } + } + return; } } @EventHandler(priority = EventPriority.NORMAL) - public void onElementChange(PlayerChangeElementEvent event) { - Player player = event.getTarget(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onElementChange(final PlayerChangeElementEvent event) { + final Player player = event.getTarget(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); PassiveManager.registerPassives(player); - boolean chatEnabled = ConfigManager.languageConfig.get().getBoolean("Chat.Enable"); + final boolean chatEnabled = ConfigManager.languageConfig.get().getBoolean("Chat.Enable"); if (chatEnabled) { - Element element = event.getElement(); + final Element element = event.getElement(); String prefix = ""; if (bPlayer == null) { @@ -391,6 +400,7 @@ public void onElementChange(PlayerChangeElementEvent event) { } else { prefix = ChatColor.WHITE + ChatColor.translateAlternateColorCodes('&', ConfigManager.languageConfig.get().getString("Chat.Prefixes.Nonbender")) + " "; } + player.setDisplayName(player.getName()); player.setDisplayName(prefix + ChatColor.RESET + player.getDisplayName()); } @@ -403,12 +413,8 @@ public void onElementChange(PlayerChangeElementEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityChangeBlockEvent(final EntityChangeBlockEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); } @@ -422,28 +428,24 @@ public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityCombust(EntityCombustEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); - Block block = entity.getLocation().getBlock(); + public void onEntityCombust(final EntityCombustEvent event) { + final Entity entity = event.getEntity(); + final Block block = entity.getLocation().getBlock(); if (BlazeArc.getIgnitedBlocks().containsKey(block) && entity instanceof LivingEntity) { new FireDamageTimer(entity, BlazeArc.getIgnitedBlocks().get(block)); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDamageBlock(EntityDamageByBlockEvent event) { - + public void onEntityDamageBlock(final EntityDamageByBlockEvent event) { } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onEntityDamageByBlock(EntityDamageByBlockEvent event) { - Block block = event.getDamager(); - if (block == null) + public void onEntityDamageByBlock(final EntityDamageByBlockEvent event) { + final Block block = event.getDamager(); + if (block == null) { return; + } if (TempBlock.isTempBlock(block)) { if (EarthAbility.isEarthbendable(block.getType(), true, true, true) && GeneralMethods.isSolid(block)) { @@ -454,12 +456,8 @@ public void onEntityDamageByBlock(EntityDamageByBlockEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDamageEvent(EntityDamageEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityDamageEvent(final EntityDamageEvent event) { + final Entity entity = event.getEntity(); if (event.getCause() == DamageCause.FIRE && BlazeArc.getIgnitedBlocks().containsKey(entity.getLocation().getBlock())) { new FireDamageTimer(entity, BlazeArc.getIgnitedBlocks().get(entity.getLocation().getBlock())); @@ -469,21 +467,27 @@ public void onEntityDamageEvent(EntityDamageEvent event) { event.setCancelled(true); FireDamageTimer.dealFlameDamage(entity); } - - if (entity instanceof LivingEntity && TempArmor.hasTempArmor((LivingEntity)entity)) { + + if (entity instanceof LivingEntity && TempArmor.hasTempArmor((LivingEntity) entity)) { event.setDamage(DamageModifier.ARMOR, 0); } if (entity instanceof Player) { - Player player = (Player) entity; - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Player player = (Player) entity; + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } + if (CoreAbility.hasAbility(player, EarthGrab.class)) { + final EarthGrab abil = CoreAbility.getAbility(player, EarthGrab.class); + abil.remove(); + } + if (bPlayer.isElementToggled(Element.FIRE)) { return; } + if (bPlayer.getBoundAbilityName().equalsIgnoreCase("HeatControl")) { if (event.getCause() == DamageCause.FIRE || event.getCause() == DamageCause.FIRE_TICK) { player.setFireTicks(0); @@ -494,58 +498,60 @@ public void onEntityDamageEvent(EntityDamageEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { + public void onEntityDeath(final EntityDeathEvent event) { if (TempArmor.hasTempArmor(event.getEntity())) { - TempArmor armor = TempArmor.getTempArmor(event.getEntity()); + final TempArmor armor = TempArmor.getVisibleTempArmor(event.getEntity()); + + final List newDrops = armor.filterArmor(event.getDrops()); - List newDrops = armor.filterArmor(event.getDrops()); - event.getDrops().clear(); event.getDrops().addAll(newDrops); if (MetalClips.isControlled(event.getEntity())) { event.getDrops().add(new ItemStack(Material.IRON_INGOT, MetalClips.getTargetToAbility().get(event.getEntity()).getMetalClipsCount())); } - armor.revert(); + for (final TempArmor tarmor : TempArmor.getTempArmorList(event.getEntity())) { + tarmor.revert(); + } } - CoreAbility[] cookingFireCombos = { CoreAbility.getAbility("JetBlast"), CoreAbility.getAbility("FireWheel"), CoreAbility.getAbility("FireSpin"), CoreAbility.getAbility("FireKick") }; - + final CoreAbility[] cookingFireCombos = { CoreAbility.getAbility("JetBlast"), CoreAbility.getAbility("FireWheel"), CoreAbility.getAbility("FireSpin"), CoreAbility.getAbility("FireKick") }; + if (BENDING_ENTITY_DEATH.containsKey(event.getEntity())) { - CoreAbility coreAbility = (CoreAbility) BENDING_ENTITY_DEATH.get(event.getEntity()); - for (CoreAbility fireCombo : cookingFireCombos) { + final CoreAbility coreAbility = (CoreAbility) BENDING_ENTITY_DEATH.get(event.getEntity()); + for (final CoreAbility fireCombo : cookingFireCombos) { if (coreAbility.getName().equalsIgnoreCase(fireCombo.getName())) { - List drops = event.getDrops(); - List newDrops = new ArrayList<>(); + final List drops = event.getDrops(); + final List newDrops = new ArrayList<>(); for (int i = 0; i < drops.size(); i++) { ItemStack cooked = drops.get(i); - Material material = drops.get(i).getType(); + final Material material = drops.get(i).getType(); switch (material) { - case RAW_BEEF: - cooked = new ItemStack(Material.COOKED_BEEF, 1); - break; - case RAW_FISH: - ItemStack salmon = new ItemStack(Material.RAW_FISH, 1, (short) 1); - if (drops.get(i).getDurability() == salmon.getDurability()) { - cooked = new ItemStack(Material.COOKED_FISH, 1, (short) 1); - } else { - cooked = new ItemStack(Material.COOKED_FISH, 1); - } - break; - case RAW_CHICKEN: - cooked = new ItemStack(Material.COOKED_CHICKEN, 1); - break; - case PORK: - cooked = new ItemStack(Material.GRILLED_PORK, 1); - break; - case MUTTON: - cooked = new ItemStack(Material.COOKED_MUTTON); - break; - case RABBIT: - cooked = new ItemStack(Material.COOKED_RABBIT); - break; - default: - break; + case RAW_BEEF: + cooked = new ItemStack(Material.COOKED_BEEF, 1); + break; + case RAW_FISH: + final ItemStack salmon = new ItemStack(Material.RAW_FISH, 1, (short) 1); + if (drops.get(i).getDurability() == salmon.getDurability()) { + cooked = new ItemStack(Material.COOKED_FISH, 1, (short) 1); + } else { + cooked = new ItemStack(Material.COOKED_FISH, 1); + } + break; + case RAW_CHICKEN: + cooked = new ItemStack(Material.COOKED_CHICKEN, 1); + break; + case PORK: + cooked = new ItemStack(Material.GRILLED_PORK, 1); + break; + case MUTTON: + cooked = new ItemStack(Material.COOKED_MUTTON); + break; + case RABBIT: + cooked = new ItemStack(Material.COOKED_RABBIT); + break; + default: + break; } newDrops.add(cooked); @@ -560,26 +566,26 @@ public void onEntityDeath(EntityDeathEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplode(EntityExplodeEvent event) { - if (event.isCancelled()) { - return; - } - - for (Block block : event.blockList()) { - EarthBlast blast = EarthBlast.getBlastFromSource(block); + public void onEntityExplode(final EntityExplodeEvent event) { + for (final Block block : event.blockList()) { + final EarthBlast blast = EarthBlast.getBlastFromSource(block); if (blast != null) { blast.remove(); } + if (PhaseChange.getFrozenBlocksAsBlock().contains(block)) { PhaseChange.thaw(block); } + if (SurgeWall.getWallBlocks().containsKey(block)) { block.setType(Material.AIR); } + if (!SurgeWave.canThaw(block)) { SurgeWave.thaw(block); } + if (EarthAbility.getMovedEarth().containsKey(block)) { EarthAbility.removeRevertIndex(block); } @@ -587,12 +593,8 @@ public void onEntityExplode(EntityExplodeEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityExplodeEvent(EntityExplodeEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityExplodeEvent(final EntityExplodeEvent event) { + final Entity entity = event.getEntity(); if (entity != null) { if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); @@ -601,59 +603,39 @@ public void onEntityExplodeEvent(EntityExplodeEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityInteractEvent(EntityInteractEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityInteractEvent(final EntityInteractEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityProjectileLaunchEvent(ProjectileLaunchEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityProjectileLaunchEvent(final ProjectileLaunchEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityShootBowEvent(EntityShootBowEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityShootBowEvent(final EntityShootBowEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntitySlimeSplitEvent(SlimeSplitEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntitySlimeSplitEvent(final SlimeSplitEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity)) { event.setCancelled(true); } } - @EventHandler - public void onEntitySuffocatedByTempBlocks(EntityDamageEvent event) { - if (event.isCancelled()) { - return; - } - + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntitySuffocatedByTempBlocks(final EntityDamageEvent event) { if (event.getCause() == DamageCause.SUFFOCATION) { if (TempBlock.isTempBlock(event.getEntity().getLocation().add(0, 1, 0).getBlock())) { event.setCancelled(true); @@ -662,65 +644,55 @@ public void onEntitySuffocatedByTempBlocks(EntityDamageEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityTarget(EntityTargetEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityTarget(final EntityTargetEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityTargetLiving(EntityTargetLivingEntityEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); + public void onEntityTargetLiving(final EntityTargetLivingEntityEvent event) { + final Entity entity = event.getEntity(); if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityTeleportEvent(EntityTeleportEvent event) { - if (event.isCancelled()) { - return; - } - - Entity entity = event.getEntity(); - if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity) || MetalClips.isControlled((LivingEntity)entity)) { + public void onEntityTeleportEvent(final EntityTeleportEvent event) { + final Entity entity = event.getEntity(); + if (MovementHandler.isStopped(entity) || Bloodbending.isBloodbent(entity) || Suffocate.isBreathbent(entity) || MetalClips.isControlled((LivingEntity) entity)) { event.setCancelled(true); } - + if (entity instanceof LivingEntity && TempArmor.hasTempArmor((LivingEntity) entity)) { - TempArmor.getTempArmor((LivingEntity) entity).revert(); + for (final TempArmor armor : TempArmor.getTempArmorList((LivingEntity) entity)) { + armor.revert(); + } } - + if (entity instanceof Player) { - Player player = (Player) entity; + final Player player = (Player) entity; if (CoreAbility.hasAbility(player, EarthArmor.class)) { - EarthArmor abil = CoreAbility.getAbility(player, EarthArmor.class); + final EarthArmor abil = CoreAbility.getAbility(player, EarthArmor.class); abil.remove(); } } } @EventHandler - public void onHorizontalCollision(HorizontalVelocityChangeEvent e) { + public void onHorizontalCollision(final HorizontalVelocityChangeEvent e) { if (e.getEntity() instanceof LivingEntity) { if (e.getEntity().getEntityId() != e.getInstigator().getEntityId()) { - double minimumDistance = plugin.getConfig().getDouble("Properties.HorizontalCollisionPhysics.WallDamageMinimumDistance"); - double maxDamage = plugin.getConfig().getDouble("Properties.HorizontalCollisionPhysics.WallDamageCap"); - double damage = ((e.getDistanceTraveled() - minimumDistance) < 0 ? 0 : e.getDistanceTraveled() - minimumDistance) / (e.getDifference().length()); + final double minimumDistance = this.plugin.getConfig().getDouble("Properties.HorizontalCollisionPhysics.WallDamageMinimumDistance"); + final double maxDamage = this.plugin.getConfig().getDouble("Properties.HorizontalCollisionPhysics.WallDamageCap"); + final double damage = ((e.getDistanceTraveled() - minimumDistance) < 0 ? 0 : e.getDistanceTraveled() - minimumDistance) / (e.getDifference().length()); if (damage > 0) { if (damage <= maxDamage) { - DamageHandler.damageEntity((LivingEntity) e.getEntity(), damage, e.getAbility()); + DamageHandler.damageEntity(e.getEntity(), damage, e.getAbility()); } else { - DamageHandler.damageEntity((LivingEntity) e.getEntity(), maxDamage, e.getAbility()); + DamageHandler.damageEntity(e.getEntity(), maxDamage, e.getAbility()); } } } @@ -728,61 +700,65 @@ public void onHorizontalCollision(HorizontalVelocityChangeEvent e) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onInventoryClick(InventoryClickEvent event) { - if (event.isCancelled()) { - return; - } - - for (MetalClips clips : CoreAbility.getAbilities(MetalClips.class)) { + public void onInventoryClick(final InventoryClickEvent event) { + for (final MetalClips clips : CoreAbility.getAbilities(MetalClips.class)) { if (clips.getTargetEntity() != null && clips.getTargetEntity().getEntityId() == event.getWhoClicked().getEntityId()) { event.setCancelled(true); break; } } - if (event.getSlotType() == SlotType.ARMOR && CoreAbility.hasAbility((Player) event.getWhoClicked(), EarthArmor.class)) { - event.setCancelled(true); - } - - if (event.getSlotType() == SlotType.ARMOR && TempArmor.hasTempArmor((Player) event.getWhoClicked())) { - event.setCancelled(true); + for (int i = 0; i < 4; i++) { + if (event.getSlot() == 36 + i && TempArmor.hasTempArmor(event.getWhoClicked())) { + event.setCancelled(true); + } } } @EventHandler(priority = EventPriority.NORMAL) - public void onEntityBendingDeath(EntityBendingDeathEvent event) { + public void onEntityBendingDeath(final EntityBendingDeathEvent event) { BENDING_ENTITY_DEATH.put(event.getEntity(), event.getAbility()); - - if (ConfigManager.languageConfig.get().getBoolean("DeathMessages.Enabled") && event.getEntity() instanceof Player) { - Ability ability = event.getAbility(); - if (ability == null) { - return; - } + if (event.getEntity() instanceof Player) { + if (ConfigManager.languageConfig.get().getBoolean("DeathMessages.Enabled")) { + final Ability ability = event.getAbility(); + if (ability == null) { + return; + } - BENDING_PLAYER_DEATH.put((Player) event.getEntity(), ability.getElement().getColor() + ability.getName()); - final Player player = (Player) event.getEntity(); + BENDING_PLAYER_DEATH.put((Player) event.getEntity(), ability.getElement().getColor() + ability.getName()); + final Player player = (Player) event.getEntity(); - new BukkitRunnable() { - @Override - public void run() { - BENDING_PLAYER_DEATH.remove(player); - } - }.runTaskLater(ProjectKorra.plugin, 20); + new BukkitRunnable() { + @Override + public void run() { + BENDING_PLAYER_DEATH.remove(player); + } + }.runTaskLater(ProjectKorra.plugin, 20); + } + + StatisticsMethods.addStatisticAbility(event.getAttacker().getUniqueId(), CoreAbility.getAbility(event.getAbility().getName()), com.projectkorra.projectkorra.util.Statistic.PLAYER_KILLS, 1); } + StatisticsMethods.addStatisticAbility(event.getAttacker().getUniqueId(), CoreAbility.getAbility(event.getAbility().getName()), com.projectkorra.projectkorra.util.Statistic.TOTAL_KILLS, 1); } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - if (event.isCancelled()) { - return; + @EventHandler + public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) { + final Block block = event.getBlockClicked().getRelative(event.getBlockFace()); + + if (Illumination.isIlluminationTorch(block)) { + final Player player = Illumination.getBlocks().get(TempBlock.get(block)); + CoreAbility.getAbility(player, Illumination.class).remove(); } + } - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerChat(final AsyncPlayerChatEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - String e = bPlayer == null || bPlayer.getElements().size() == 0 ? "Nonbender" : (bPlayer.getElements().size() > 1 ? "Avatar" : bPlayer.getElements().get(0).getName()); - String element = ConfigManager.languageConfig.get().getString("Chat.Prefixes." + e); - ChatColor c = bPlayer == null || bPlayer.getElements().size() == 0 ? ChatColor.WHITE : (bPlayer.getElements().size() > 1 ? Element.AVATAR.getColor() : bPlayer.getElements().get(0).getColor()); + final String e = bPlayer == null || bPlayer.getElements().size() == 0 ? "Nonbender" : (bPlayer.getElements().size() > 1 ? "Avatar" : bPlayer.getElements().get(0).getName()); + final String element = ConfigManager.languageConfig.get().getString("Chat.Prefixes." + e); + final ChatColor c = bPlayer == null || bPlayer.getElements().size() == 0 ? ChatColor.WHITE : (bPlayer.getElements().size() > 1 ? Element.AVATAR.getColor() : bPlayer.getElements().get(0).getColor()); event.setFormat(event.getFormat().replace("{element}", c + element + ChatColor.RESET).replace("{ELEMENT}", c + element + ChatColor.RESET).replace("{elementcolor}", c + "").replace("{ELEMENTCOLOR}", c + "")); if (!ConfigManager.languageConfig.get().getBoolean("Chat.Enable")) { @@ -798,7 +774,7 @@ public void onPlayerChat(AsyncPlayerChatEvent event) { if (player.hasPermission("bending.avatar") || bPlayer.getElements().size() > 1) { color = ChatColor.valueOf(ConfigManager.languageConfig.get().getString("Chat.Colors.Avatar")); } else { - for (Element element_ : Element.getMainElements()) { + for (final Element element_ : Element.getMainElements()) { if (bPlayer.hasElement(element_)) { color = element_.getColor(); break; @@ -812,63 +788,72 @@ public void onPlayerChat(AsyncPlayerChatEvent event) { event.setFormat(format); } - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerDamage(EntityDamageEvent event) { - + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDamage(final EntityDamageEvent event) { if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Player player = (Player) event.getEntity(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; + } else if (bPlayer.isChiBlocked()) { + return; } - if (bPlayer.hasElement(Element.EARTH) && event.getCause() == DamageCause.FALL) { - new Shockwave(player, true); + if (FlightMultiAbility.getFlyingPlayers().contains(player.getUniqueId())) { + final FlightMultiAbility fma = CoreAbility.getAbility(player, FlightMultiAbility.class); + fma.cancel("taking damage"); } - if (event.isCancelled()) - return; + if (bPlayer.hasElement(Element.EARTH) && event.getCause() == DamageCause.FALL) { + if (bPlayer.getBoundAbilityName().equalsIgnoreCase("Shockwave")) { + new Shockwave(player, true); + } else if (bPlayer.getBoundAbilityName().equalsIgnoreCase("Catapult")) { + new EarthPillars(player, true); + } + } - if (bPlayer.hasElement(Element.AIR) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(Element.AIR) && bPlayer.canUsePassive(Element.AIR)) { - new AirBurst(player, true); - if (CoreAbility.getAbility(GracefulDescent.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(GracefulDescent.class))) { - event.setDamage(0D); - event.setCancelled(true); + if (bPlayer.hasElement(Element.AIR) && event.getCause() == DamageCause.FALL) { + if (bPlayer.getBoundAbilityName().equalsIgnoreCase("AirBurst")) { + new AirBurst(player, true); } } - if (bPlayer.hasElement(Element.WATER) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(Element.WATER) && bPlayer.canUsePassive(Element.WATER) && CoreAbility.getAbility(Hydrosink.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(Hydrosink.class))) { - if (WaterPassive.applyNoFall(player)) { + if (bPlayer.hasElement(Element.AIR) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(CoreAbility.getAbility(GracefulDescent.class)) && bPlayer.canUsePassive(CoreAbility.getAbility(GracefulDescent.class)) && CoreAbility.getAbility(GracefulDescent.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(GracefulDescent.class))) { + event.setDamage(0D); + event.setCancelled(true); + } else if (bPlayer.hasElement(Element.EARTH) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(CoreAbility.getAbility(DensityShift.class)) && bPlayer.canUsePassive(CoreAbility.getAbility(DensityShift.class)) && CoreAbility.getAbility(DensityShift.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(DensityShift.class))) { + if (DensityShift.softenLanding(player)) { event.setDamage(0D); event.setCancelled(true); } - } - - if (bPlayer.hasElement(Element.EARTH) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(Element.EARTH) && bPlayer.canUsePassive(Element.EARTH) && CoreAbility.getAbility(DensityShift.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(DensityShift.class))) { - if (EarthPassive.softenLanding(player)) { + } else if (bPlayer.hasElement(Element.WATER) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(CoreAbility.getAbility(HydroSink.class)) && bPlayer.canUsePassive(CoreAbility.getAbility(HydroSink.class)) && CoreAbility.getAbility(HydroSink.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(HydroSink.class))) { + if (HydroSink.applyNoFall(player)) { event.setDamage(0D); event.setCancelled(true); } } - if (bPlayer.hasElement(Element.CHI) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(Element.CHI) && bPlayer.canUsePassive(Element.CHI) && CoreAbility.getAbility(Acrobatics.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(Acrobatics.class))) { - double initdamage = event.getDamage(); - double newdamage = event.getDamage() * ChiPassive.getFallReductionFactor(); - double finaldamage = initdamage - newdamage; + if (bPlayer.hasElement(Element.CHI) && event.getCause() == DamageCause.FALL && bPlayer.canBendPassive(CoreAbility.getAbility(Acrobatics.class)) && bPlayer.canUsePassive(CoreAbility.getAbility(Acrobatics.class)) && CoreAbility.getAbility(Acrobatics.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(Acrobatics.class))) { + final double initdamage = event.getDamage(); + final double newdamage = event.getDamage() * Acrobatics.getFallReductionFactor(); + final double finaldamage = initdamage - newdamage; event.setDamage(finaldamage); - if (finaldamage <= 0.4) + if (finaldamage <= 0.4) { event.setCancelled(true); + } } if (event.getCause() == DamageCause.FALL) { - Player source = Flight.getLaunchedBy(player); - if (source == player) { - event.setCancelled(true); + final Flight flight = ProjectKorra.flightHandler.getInstance(player); + if (flight != null) { + if (flight.getPlayer() == flight.getSource()) { + event.setCancelled(true); + } } } - if (bPlayer.canBendPassive(Element.FIRE) && bPlayer.hasElement(Element.FIRE) && bPlayer.canUsePassive(Element.FIRE) && (event.getCause() == DamageCause.FIRE || event.getCause() == DamageCause.FIRE_TICK)) { + if (bPlayer.canBendPassive(CoreAbility.getAbility(HeatControl.class)) && bPlayer.hasElement(Element.FIRE) && bPlayer.canUsePassive(CoreAbility.getAbility(HeatControl.class)) && (event.getCause() == DamageCause.FIRE || event.getCause() == DamageCause.FIRE_TICK)) { event.setCancelled(!HeatControl.canBurn(player)); } @@ -878,21 +863,17 @@ public void onPlayerDamage(EntityDamageEvent event) { } if (CoreAbility.getAbility(player, EarthArmor.class) != null) { - EarthArmor eartharmor = CoreAbility.getAbility(player, EarthArmor.class); + final EarthArmor eartharmor = CoreAbility.getAbility(player, EarthArmor.class); eartharmor.updateAbsorbtion(); } } } - @EventHandler - public void onPlayerDamageByPlayer(EntityDamageByEntityEvent e) { - if (e.isCancelled()) { - return; - } - - Entity source = e.getDamager(); - Entity entity = e.getEntity(); - FireBlastCharged fireball = FireBlastCharged.getFireball(source); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDamageByPlayer(final EntityDamageByEntityEvent e) { + final Entity source = e.getDamager(); + final Entity entity = e.getEntity(); + final FireBlastCharged fireball = FireBlastCharged.getFireball(source); if (fireball != null) { e.setCancelled(true); @@ -901,27 +882,30 @@ public void onPlayerDamageByPlayer(EntityDamageByEntityEvent e) { } if (MovementHandler.isStopped(e.getDamager())) { - e.setCancelled(true); - return; + final CoreAbility ability = (CoreAbility) e.getDamager().getMetadata("movement:stop").get(0).value(); + if (!(ability instanceof EarthGrab)) { + e.setCancelled(true); + return; + } } if (entity instanceof Player) { Suffocate.remove((Player) entity); } - + if (source instanceof Player) { // This is the player hitting someone. - Player sourcePlayer = (Player) source; - BendingPlayer sourceBPlayer = BendingPlayer.getBendingPlayer(sourcePlayer); + final Player sourcePlayer = (Player) source; + final BendingPlayer sourceBPlayer = BendingPlayer.getBendingPlayer(sourcePlayer); if (sourceBPlayer == null) { return; } - String boundAbil = sourceBPlayer.getBoundAbilityName(); + final String boundAbil = sourceBPlayer.getBoundAbilityName(); if (sourceBPlayer.getBoundAbility() != null) { if (!sourceBPlayer.isOnCooldown(boundAbil)) { - if (sourceBPlayer.canBendPassive(Element.CHI)) { - if (e.getCause() == DamageCause.ENTITY_ATTACK && e.getDamage() == 1) { + if (sourceBPlayer.canBendPassive(sourceBPlayer.getBoundAbility())) { + if (e.getCause() == DamageCause.ENTITY_ATTACK) { if (sourceBPlayer.getBoundAbility() instanceof ChiAbility) { if (sourceBPlayer.canCurrentlyBendWithWeapons()) { if (sourceBPlayer.isElementToggled(Element.CHI)) { @@ -944,11 +928,11 @@ public void onPlayerDamageByPlayer(EntityDamageByEntityEvent e) { } } } else { - if (e.getCause() == DamageCause.ENTITY_ATTACK && e.getDamage() == 1) { + if (e.getCause() == DamageCause.ENTITY_ATTACK) { if (sourceBPlayer.canCurrentlyBendWithWeapons()) { if (sourceBPlayer.isElementToggled(Element.CHI)) { if (entity instanceof Player) { - Player targetPlayer = (Player) entity; + final Player targetPlayer = (Player) entity; if (ChiPassive.willChiBlock(sourcePlayer, targetPlayer)) { ChiPassive.blockChi(targetPlayer); } @@ -961,14 +945,16 @@ public void onPlayerDamageByPlayer(EntityDamageByEntityEvent e) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(PlayerDeathEvent event) { + public void onPlayerDeath(final PlayerDeathEvent event) { if (!(event.getEntity() instanceof Player)) { return; } if (event.getKeepInventory()) { if (TempArmor.hasTempArmor(event.getEntity())) { - TempArmor.getTempArmor(event.getEntity()).revert(); + for (final TempArmor armor : TempArmor.getTempArmorList(event.getEntity())) { + armor.revert(); + } } } else { // Do nothing. TempArmor drops are handled by the EntityDeath event and not PlayerDeath. @@ -977,15 +963,16 @@ public void onPlayerDeath(PlayerDeathEvent event) { if (event.getEntity().getKiller() != null) { if (BENDING_PLAYER_DEATH.containsKey(event.getEntity())) { String message = ConfigManager.languageConfig.get().getString("DeathMessages.Default"); - String ability = BENDING_PLAYER_DEATH.get(event.getEntity()); - String tempAbility = ChatColor.stripColor(ability).replaceAll(" ", ""); - CoreAbility coreAbil = CoreAbility.getAbility(tempAbility); + final String ability = BENDING_PLAYER_DEATH.get(event.getEntity()); + final String tempAbility = ChatColor.stripColor(ability).replaceAll(" ", ""); + final CoreAbility coreAbil = CoreAbility.getAbility(tempAbility); Element element = null; - boolean isAvatarAbility = false; + final boolean isAvatarAbility = false; if (coreAbil != null) { element = coreAbil.getElement(); } + if (HorizontalVelocityTracker.hasBeenDamagedByHorizontalVelocity(event.getEntity()) && Arrays.asList(HorizontalVelocityTracker.abils).contains(tempAbility)) { if (ConfigManager.languageConfig.get().contains("Abilities." + element.getName() + "." + tempAbility + ".HorizontalVelocityDeath")) { message = ConfigManager.languageConfig.get().getString("Abilities." + element.getName() + "." + tempAbility + ".HorizontalVelocityDeath"); @@ -1016,24 +1003,21 @@ public void onPlayerDeath(PlayerDeathEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteraction(PlayerInteractEvent event) { - if (event.isCancelled()) { - return; - } - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onPlayerInteraction(final PlayerInteractEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (!RIGHT_CLICK_INTERACT.contains(player.getUniqueId())) { final UUID uuid = player.getUniqueId(); RIGHT_CLICK_INTERACT.add(uuid); - + new BukkitRunnable() { @Override public void run() { RIGHT_CLICK_INTERACT.remove(uuid); } - }.runTaskLater(plugin, 5); + }.runTaskLater(this.plugin, 5); } if (event.getHand() == EquipmentSlot.HAND) { @@ -1050,45 +1034,73 @@ public void run() { new EarthSmash(player, ClickType.RIGHT_CLICK); } } + if (MovementHandler.isStopped(player) || Bloodbending.isBloodbent(player) || Suffocate.isBreathbent(player)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { - if (event.isCancelled()) { - return; - } - - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onPlayerInteractEntity(final PlayerInteractAtEntityEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer.canCurrentlyBendWithWeapons()) { ComboManager.addComboAbility(player, ClickType.RIGHT_CLICK_ENTITY); } + if (event.getRightClicked().hasMetadata("earthgrab:trap")) { + final EarthGrab eg = (EarthGrab) event.getRightClicked().getMetadata("earthgrab:trap").get(0).value(); + eg.damageTrap(); + event.setCancelled(true); + return; + } + + if (event.getRightClicked().hasMetadata("temparmorstand")) { + event.setCancelled(true); + return; + } + if (MovementHandler.isStopped(player) || Bloodbending.isBloodbent(player) || Suffocate.isBreathbent(player)) { event.setCancelled(true); + return; } if (bPlayer.getBoundAbilityName().equalsIgnoreCase("HealingWaters") && event.getHand().equals(EquipmentSlot.HAND)) { - HealingWaters instance = CoreAbility.getAbility(player, HealingWaters.class); + final HealingWaters instance = CoreAbility.getAbility(player, HealingWaters.class); if (instance != null && instance.charged) { instance.click(); event.setCancelled(true); + return; } } - } + if (!RIGHT_CLICK_INTERACT.contains(player.getUniqueId())) { + if (event.getRightClicked() instanceof Player) { + final Player target = (Player) event.getRightClicked(); + if (FlightMultiAbility.getFlyingPlayers().contains(player.getUniqueId())) { + final FlightMultiAbility fma = CoreAbility.getAbility(player, FlightMultiAbility.class); + fma.requestCarry(target); + final UUID uuid = player.getUniqueId(); + RIGHT_CLICK_INTERACT.add(uuid); - @EventHandler - public void onPlayerItemDamage(PlayerItemDamageEvent event) { - if (event.isCancelled()) - return; + new BukkitRunnable() { + @Override + public void run() { + RIGHT_CLICK_INTERACT.remove(uuid); + } + }.runTaskLater(this.plugin, 5); + } else if (FlightMultiAbility.getFlyingPlayers().contains(target.getUniqueId())) { + FlightMultiAbility.acceptCarryRequest(player, target); + } + } + } + } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerItemDamage(final PlayerItemDamageEvent event) { if (TempArmor.hasTempArmor(event.getPlayer())) { - TempArmor armor = TempArmor.getTempArmor(event.getPlayer()); - for (ItemStack i : armor.getNewArmor()) { + final TempArmor armor = TempArmor.getVisibleTempArmor(event.getPlayer()); + for (final ItemStack i : armor.getNewArmor()) { if (i != null && event.getItem().isSimilar(i)) { event.setCancelled(true); break; @@ -1098,11 +1110,14 @@ public void onPlayerItemDamage(PlayerItemDamageEvent event) { } @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { + public void onPlayerJoin(final PlayerJoinEvent event) { final Player player = event.getPlayer(); JUMPS.put(player, player.getStatistic(Statistic.JUMP)); GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); + if (ProjectKorra.isStatisticsEnabled()) { + ProjectKorra.statistics.load(player.getUniqueId()); + } Bukkit.getScheduler().runTaskLater(ProjectKorra.plugin, new Runnable() { @Override @@ -1114,11 +1129,12 @@ public void run() { if (ConfigManager.languageConfig.get().getBoolean("Chat.Branding.JoinMessage.Enabled")) { Bukkit.getScheduler().runTaskLater(ProjectKorra.plugin, new Runnable() { + @Override public void run() { ChatColor color = ChatColor.valueOf(ConfigManager.languageConfig.get().getString("Chat.Branding.Color").toUpperCase()); color = color == null ? ChatColor.GOLD : color; - String topBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.TopBorder"); - String bottomBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.BottomBorder"); + final String topBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.TopBorder"); + final String bottomBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.BottomBorder"); if (!topBorder.isEmpty()) { player.sendMessage(ChatColor.translateAlternateColorCodes('&', topBorder)); } @@ -1132,64 +1148,52 @@ public void run() { } @EventHandler - public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { + public void onPlayerChangeWorld(final PlayerChangedWorldEvent event) { PassiveManager.registerPassives(event.getPlayer()); } - @EventHandler - public void onPlayerKick(PlayerKickEvent event) { - if (event.isCancelled()) { - return; - } - - AirFlight.remove(event.getPlayer()); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerKick(final PlayerKickEvent event) { JUMPS.remove(event.getPlayer()); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - if (event.isCancelled()) { - return; - } - - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onPlayerMove(final PlayerMoveEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (MovementHandler.isStopped(player)) { if (event.getTo().getX() != event.getFrom().getX() || event.getTo().getZ() != event.getFrom().getZ() || event.getTo().getY() > event.getFrom().getY()) { event.setCancelled(true); return; } - } - - else if (CoreAbility.hasAbility(player, WaterSpout.class) || CoreAbility.hasAbility(player, AirSpout.class) ) { + } else if (CoreAbility.hasAbility(player, WaterSpout.class) || CoreAbility.hasAbility(player, AirSpout.class)) { Vector vel = new Vector(); vel.setX(event.getTo().getX() - event.getFrom().getX()); vel.setZ(event.getTo().getZ() - event.getFrom().getZ()); - double currspeed = vel.length(); - double maxspeed = .2; + final double currspeed = vel.length(); + final double maxspeed = .2; if (currspeed > maxspeed) { // apply only if moving set a factor vel = vel.normalize().multiply(maxspeed); // apply the new velocity event.getPlayer().setVelocity(vel); } - } - - else if (Bloodbending.isBloodbent(player)) { - BendingPlayer bender = Bloodbending.getBloodbender(player); + } else if (Bloodbending.isBloodbent(player)) { + final BendingPlayer bender = Bloodbending.getBloodbender(player); if (bender.isAvatarState()) { event.setCancelled(true); return; } + double distance1 = 0; double distance2 = 0; - Location loc = Bloodbending.getBloodbendingLocation(player); + final Location loc = Bloodbending.getBloodbendingLocation(player); if (player.getWorld().equals(loc.getWorld())) { distance1 = event.getFrom().distanceSquared(loc); distance2 = event.getTo().distanceSquared(loc); } - + if (distance1 == 0 && distance2 == 0) { return; } else if (distance1 > distance2 || distance1 < distance2) { @@ -1198,37 +1202,29 @@ else if (Bloodbending.isBloodbent(player)) { return; } } - } - - else if (AirFlight.isFlying(player)) { - if (AirFlight.isHovering(player)) { - Location loc = event.getFrom(); - Location toLoc = event.getTo(); - - if (loc.getX() != toLoc.getX() || loc.getY() != toLoc.getY() || loc.getZ() != toLoc.getZ()) { - event.setCancelled(true); - return; + } else { + if (bPlayer != null) { + if (event.getTo().getX() != event.getFrom().getX() || event.getTo().getY() != event.getFrom().getY() || event.getTo().getZ() != event.getFrom().getZ()) { + if (bPlayer.hasElement(Element.AIR) || bPlayer.hasElement(Element.CHI)) { + PassiveHandler.checkExhaustionPassives(player); + } } - } - } - else { - if (bPlayer != null) { - if (bPlayer.hasElement(Element.AIR) || bPlayer.hasElement(Element.CHI)) { - PassiveHandler.checkExhaustionPassives(player); + if (event.getTo().getBlock() != event.getFrom().getBlock()) { + FirePassive.handle(player); } } } if (event.getTo().getY() > event.getFrom().getY()) { if (!(player.getLocation().getBlock().getType() == Material.VINE) && !(player.getLocation().getBlock().getType() == Material.LADDER)) { - int current = player.getStatistic(Statistic.JUMP); - int last = JUMPS.get(player); + final int current = player.getStatistic(Statistic.JUMP); + final int last = JUMPS.get(player); if (last != current) { JUMPS.put(player, current); - double yDif = event.getTo().getY() - event.getFrom().getY(); + final double yDif = event.getTo().getY() - event.getFrom().getY(); if ((yDif < 0.035 || yDif > 0.037) && (yDif < 0.116 || yDif > 0.118)) { Bukkit.getServer().getPluginManager().callEvent(new PlayerJumpEvent(player, yDif)); @@ -1239,8 +1235,8 @@ else if (AirFlight.isFlying(player)) { } @EventHandler - public void onPlayerGamemodeChange(PlayerGameModeChangeEvent event) { - Player player = event.getPlayer(); + public void onPlayerGamemodeChange(final PlayerGameModeChangeEvent event) { + final Player player = event.getPlayer(); if (event.getNewGameMode() == GameMode.SPECTATOR) { if (!Commands.invincible.contains(player.getName())) { Commands.invincible.add(player.getName()); @@ -1252,14 +1248,20 @@ public void onPlayerGamemodeChange(PlayerGameModeChangeEvent event) { } @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onPlayerQuit(final PlayerQuitEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (ProjectKorra.isStatisticsEnabled()) { + ProjectKorra.statistics.store(player.getUniqueId()); + } if (bPlayer != null) { + bPlayer.saveCooldowns(); + if (TOGGLED_OUT.contains(player.getUniqueId()) && bPlayer.isToggled()) { TOGGLED_OUT.remove(player.getUniqueId()); } + if (!bPlayer.isToggled()) { TOGGLED_OUT.add(player.getUniqueId()); } @@ -1268,10 +1270,13 @@ public void onPlayerQuit(PlayerQuitEvent event) { if (Commands.invincible.contains(player.getName())) { Commands.invincible.remove(player.getName()); } + Preset.unloadPreset(player); if (TempArmor.hasTempArmor(player)) { - TempArmor.getTempArmor(player).revert(); + for (final TempArmor armor : TempArmor.getTempArmorList(player)) { + armor.revert(); + } } if (MetalClips.isControlled(event.getPlayer())) { @@ -1279,17 +1284,21 @@ public void onPlayerQuit(PlayerQuitEvent event) { } MultiAbilityManager.remove(player); - AirFlight.remove(player); JUMPS.remove(player); + + for (final CoreAbility ca : CoreAbility.getAbilities()) { + if (CoreAbility.getAbility(event.getPlayer(), ca.getClass()) != null) { + CoreAbility.getAbility(event.getPlayer(), ca.getClass()).remove(); + } + } } - @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerSneak(PlayerToggleSneakEvent event) { - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public void onPlayerSneak(final PlayerToggleSneakEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (event.isCancelled() || bPlayer == null) { + if (bPlayer == null) { return; } @@ -1301,7 +1310,7 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { } } - String abilName = bPlayer.getBoundAbilityName(); + final String abilName = bPlayer.getBoundAbilityName(); if (Suffocate.isBreathbent(player)) { if (!abilName.equalsIgnoreCase("AirSwipe") || !abilName.equalsIgnoreCase("FireBlast") || !abilName.equalsIgnoreCase("EarthBlast") || !abilName.equalsIgnoreCase("WaterManipulation")) { if (!player.isSneaking()) { @@ -1311,6 +1320,13 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { } if (MovementHandler.isStopped(player) || Bloodbending.isBloodbent(player)) { + if (!player.isSneaking()) { + event.setCancelled(true); + return; + } + } + + if (bPlayer.isChiBlocked()) { event.setCancelled(true); return; } @@ -1319,38 +1335,18 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { BlockSource.update(player, ClickType.SHIFT_DOWN); } - if (CoreAbility.getAbility(FerroControl.class).isEnabled() && PassiveManager.hasPassive(player, CoreAbility.getAbility(FerroControl.class)) && !bPlayer.isOnCooldown("FerroControl")) { - if (event.isSneaking()) { - Block block = player.getTargetBlock((HashSet) null, 5); - if (block != null) { - if (block.getType() == Material.IRON_DOOR_BLOCK && !GeneralMethods.isRegionProtectedFromBuild(player, block.getLocation())) { - if (block.getData() >= 8) { - block = block.getRelative(BlockFace.DOWN); - } - if (block.getData() < 4) { - block.setData((byte) (block.getData() + 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_IRON_DOOR_CLOSE, 10, 1); - } else { - block.setData((byte) (block.getData() - 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_IRON_DOOR_OPEN, 10, 1); - } - bPlayer.addCooldown("FerroControl", 200); - } - } - - } + if (PassiveManager.hasPassive(player, CoreAbility.getAbility(FerroControl.class))) { + new FerroControl(player); + } else if (PassiveManager.hasPassive(player, CoreAbility.getAbility(FastSwim.class))) { + new FastSwim(player); } AirScooter.check(player); - CoreAbility coreAbil = bPlayer.getBoundAbility(); - String abil = bPlayer.getBoundAbilityName(); + final CoreAbility coreAbil = bPlayer.getBoundAbility(); + final String abil = bPlayer.getBoundAbilityName(); if (coreAbil == null) { - return; - } - if (bPlayer.isChiBlocked()) { - event.setCancelled(true); return; } @@ -1358,6 +1354,7 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { if (coreAbil instanceof AddonAbility) { return; } + if (coreAbil instanceof AirAbility && bPlayer.isElementToggled(Element.AIR) == true) { if (bPlayer.canCurrentlyBendWithWeapons()) { if (abil.equalsIgnoreCase("Tornado")) { @@ -1374,11 +1371,6 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { new AirShield(player); } else if (abil.equalsIgnoreCase("Suffocate")) { new Suffocate(player); - } else if (abil.equalsIgnoreCase("Flight")) { - if (player.isSneaking() || !bPlayer.canUseFlight()) { - return; - } - new AirFlight(player); } } } @@ -1397,7 +1389,7 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { if (!CoreAbility.hasAbility(player, PhaseChange.class)) { new PhaseChange(player, PhaseChangeType.MELT); } else { - PhaseChange pc = CoreAbility.getAbility(player, PhaseChange.class); + final PhaseChange pc = CoreAbility.getAbility(player, PhaseChange.class); pc.startNewType(PhaseChangeType.MELT); } } else if (abil.equalsIgnoreCase("WaterManipulation")) { @@ -1411,6 +1403,7 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { } else if (abil.equalsIgnoreCase("WaterArms")) { new WaterArms(player); } + if (abil.equalsIgnoreCase("HealingWaters")) { new HealingWaters(player); } @@ -1442,7 +1435,7 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { } else if (abil.equalsIgnoreCase("EarthSmash")) { new EarthSmash(player, ClickType.SHIFT_DOWN); } else if (abil.equalsIgnoreCase("MetalClips")) { - MetalClips clips = CoreAbility.getAbility(player, MetalClips.class); + final MetalClips clips = CoreAbility.getAbility(player, MetalClips.class); if (clips != null) { if (clips.getTargetEntity() == null) { clips.setMagnetized(true); @@ -1452,7 +1445,9 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { } else { new MetalClips(player, 1); } - } + } else if (abil.equalsIgnoreCase("EarthGrab")) { + new EarthGrab(player, GrabMode.DRAG); + } } } @@ -1475,24 +1470,20 @@ public void onPlayerSneak(PlayerToggleSneakEvent event) { new Combustion(player); } else if (abil.equalsIgnoreCase("FireManipulation")) { new FireManipulation(player, FireManipulationType.SHIFT); - } + } } } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerSlotChange(PlayerItemHeldEvent event) { - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - int slot = event.getNewSlot() + 1; + public void onPlayerSlotChange(final PlayerItemHeldEvent event) { + final Player player = event.getPlayer(); + final int slot = event.getNewSlot() + 1; + GeneralMethods.displayMovePreview(player, slot); - if (ConfigManager.defaultConfig.get().getBoolean("Properties.BendingPreview")) { - if (bPlayer != null && bPlayer.getAbilities() != null) { - GeneralMethods.displayMovePreview(player, slot); - } - } else { - WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); + if (!ConfigManager.defaultConfig.get().getBoolean("Properties.BendingPreview")) { + final WaterArms waterArms = CoreAbility.getAbility(player, WaterArms.class); if (waterArms != null) { waterArms.displayBoundMsg(event.getNewSlot() + 1); return; @@ -1501,25 +1492,35 @@ public void onPlayerSlotChange(PlayerItemHeldEvent event) { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerSwing(PlayerAnimationEvent event) { - if (event.isCancelled()) { + public void onPlayerSwapItems(final PlayerSwapHandItemsEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (bPlayer == null) { return; } - Player player = event.getPlayer(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final ItemStack main = event.getMainHandItem(); + final ItemStack off = event.getOffHandItem(); + if (main.getType() == Material.AIR && (off == null || off.getType() == Material.AIR)) { + ComboManager.addComboAbility(player, ClickType.OFFHAND_TRIGGER); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerSwing(final PlayerAnimationEvent event) { + final Player player = event.getPlayer(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } else if (RIGHT_CLICK_INTERACT.contains(player.getUniqueId())) { return; } - Entity target = GeneralMethods.getTargetedEntity(player, 3); + final Entity target = GeneralMethods.getTargetedEntity(player, 3); if (bPlayer.canCurrentlyBendWithWeapons()) { if (target != null && !(target.equals(player)) && target instanceof LivingEntity) { ComboManager.addComboAbility(player, ClickType.LEFT_CLICK_ENTITY); - } else { ComboManager.addComboAbility(player, ClickType.LEFT_CLICK); } @@ -1528,9 +1529,17 @@ public void onPlayerSwing(PlayerAnimationEvent event) { if (Suffocate.isBreathbent(player)) { event.setCancelled(true); return; - } else if ((Bloodbending.isBloodbent(player) && !bPlayer.getBoundAbilityName().equalsIgnoreCase("AvatarState")) || MovementHandler.isStopped(player)) { + } else if ((Bloodbending.isBloodbent(player) && !bPlayer.getBoundAbilityName().equalsIgnoreCase("AvatarState"))) { event.setCancelled(true); return; + } else if (MovementHandler.isStopped(player)) { + if (player.hasMetadata("movement:stop")) { + final CoreAbility abil = (CoreAbility) player.getMetadata("movement:stop").get(0).value(); + if (!(abil instanceof EarthGrab)) { + event.setCancelled(true); + return; + } + } } else if (bPlayer.isChiBlocked()) { event.setCancelled(true); return; @@ -1545,7 +1554,7 @@ public void onPlayerSwing(PlayerAnimationEvent event) { AirScooter.check(player); String abil = bPlayer.getBoundAbilityName(); - CoreAbility coreAbil = bPlayer.getBoundAbility(); + final CoreAbility coreAbil = bPlayer.getBoundAbility(); if (coreAbil == null && !MultiAbilityManager.hasMultiAbilityBound(player)) { return; @@ -1569,17 +1578,8 @@ public void onPlayerSwing(PlayerAnimationEvent event) { } else if (abil.equalsIgnoreCase("AirSwipe")) { new AirSwipe(player); } else if (abil.equalsIgnoreCase("Flight")) { - if (!ProjectKorra.plugin.getConfig().getBoolean("Abilities.Air.Flight.HoverEnabled") || !bPlayer.canUseFlight()) { - return; - } - - if (AirFlight.isFlying(event.getPlayer())) { - if (AirFlight.isHovering(event.getPlayer())) { - AirFlight.setHovering(event.getPlayer(), false); - } else { - AirFlight.setHovering(event.getPlayer(), true); - } - } + new FlightMultiAbility(player); + return; } } } @@ -1598,7 +1598,7 @@ public void onPlayerSwing(PlayerAnimationEvent event) { if (!CoreAbility.hasAbility(player, PhaseChange.class)) { new PhaseChange(player, PhaseChangeType.FREEZE); } else { - PhaseChange pc = CoreAbility.getAbility(player, PhaseChange.class); + final PhaseChange pc = CoreAbility.getAbility(player, PhaseChange.class); pc.startNewType(PhaseChangeType.FREEZE); } } else if (abil.equalsIgnoreCase("WaterBubble")) { @@ -1628,16 +1628,14 @@ public void onPlayerSwing(PlayerAnimationEvent event) { } else if (abil.equalsIgnoreCase("Shockwave")) { Shockwave.coneShockwave(player); } else if (abil.equalsIgnoreCase("EarthArmor")) { - EarthArmor armor = CoreAbility.getAbility(player, EarthArmor.class); + final EarthArmor armor = CoreAbility.getAbility(player, EarthArmor.class); if (armor != null && armor.isFormed()) { armor.click(); } - } else if (abil.equalsIgnoreCase("EarthGrab")) { - new EarthGrab(player); } else if (abil.equalsIgnoreCase("Tremorsense")) { new Tremorsense(player, true); } else if (abil.equalsIgnoreCase("MetalClips")) { - MetalClips clips = CoreAbility.getAbility(player, MetalClips.class); + final MetalClips clips = CoreAbility.getAbility(player, MetalClips.class); if (clips == null) { new MetalClips(player, 0); } else if (clips.getMetalClipsCount() < (player.hasPermission("bending.ability.MetalClips.4clips") ? 4 : 3)) { @@ -1646,7 +1644,7 @@ public void onPlayerSwing(PlayerAnimationEvent event) { clips.crush(); } } else if (abil.equalsIgnoreCase("LavaSurge")) { - LavaSurge surge = CoreAbility.getAbility(player, LavaSurge.class); + final LavaSurge surge = CoreAbility.getAbility(player, LavaSurge.class); if (surge != null) { surge.launch(); } @@ -1654,6 +1652,8 @@ public void onPlayerSwing(PlayerAnimationEvent event) { new LavaFlow(player, AbilityType.CLICK); } else if (abil.equalsIgnoreCase("EarthSmash")) { new EarthSmash(player, ClickType.LEFT_CLICK); + } else if (abil.equalsIgnoreCase("EarthGrab")) { + new EarthGrab(player, GrabMode.PROJECTING); } } } @@ -1684,7 +1684,7 @@ public void onPlayerSwing(PlayerAnimationEvent event) { Combustion.explode(player); } else if (abil.equalsIgnoreCase("FireManipulation")) { if (CoreAbility.hasAbility(player, FireManipulation.class)) { - FireManipulation fireManip = CoreAbility.getAbility(player, FireManipulation.class); + final FireManipulation fireManip = CoreAbility.getAbility(player, FireManipulation.class); if (fireManip.getFireManipulationType() == FireManipulationType.SHIFT) { fireManip.click(); } @@ -1719,32 +1719,54 @@ public void onPlayerSwing(PlayerAnimationEvent event) { abil = MultiAbilityManager.getBoundMultiAbility(player); if (abil.equalsIgnoreCase("WaterArms")) { new WaterArms(player); + } else if (abil.equalsIgnoreCase("Flight")) { + new FlightMultiAbility(player); + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerToggleFlight(final PlayerToggleFlightEvent event) { + final Player player = event.getPlayer(); + if (CoreAbility.hasAbility(player, Tornado.class) || Bloodbending.isBloodbent(player) || Suffocate.isBreathbent(player) || CoreAbility.hasAbility(player, FireJet.class) || CoreAbility.hasAbility(player, AvatarState.class)) { + event.setCancelled(player.getGameMode() != GameMode.CREATIVE); + return; + } + + if (FlightMultiAbility.getFlyingPlayers().contains(player.getUniqueId())) { + if (player.isFlying()) { + event.setCancelled(true); + return; } } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { - if (event.isCancelled()) { + public void onPlayerToggleGlide(final EntityToggleGlideEvent event) { + if (!(event.getEntity() instanceof Player)) { return; } + final Player player = (Player) event.getEntity(); - Player player = event.getPlayer(); - if (CoreAbility.hasAbility(player, Tornado.class) || Bloodbending.isBloodbent(player) || Suffocate.isBreathbent(player) || CoreAbility.hasAbility(player, FireJet.class) || CoreAbility.hasAbility(player, AvatarState.class)) { - event.setCancelled(player.getGameMode() != GameMode.CREATIVE); + if (FlightMultiAbility.getFlyingPlayers().contains(player.getUniqueId())) { + if (player.isGliding()) { + event.setCancelled(true); + return; + } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProjectileHit(ProjectileHitEvent event) { - Integer id = event.getEntity().getEntityId(); - Smokescreen smokescreen = Smokescreen.getSnowballs().get(id); + public void onProjectileHit(final ProjectileHitEvent event) { + final Integer id = event.getEntity().getEntityId(); + final Smokescreen smokescreen = Smokescreen.getSnowballs().get(id); if (smokescreen != null) { - Location loc = event.getEntity().getLocation(); + final Location loc = event.getEntity().getLocation(); Smokescreen.playEffect(loc); - for (Entity en : GeneralMethods.getEntitiesAroundPoint(loc, smokescreen.getRadius())) { + for (final Entity en : GeneralMethods.getEntitiesAroundPoint(loc, smokescreen.getRadius())) { smokescreen.applyBlindness(en); } + Smokescreen.getSnowballs().remove(id); } } @@ -1764,4 +1786,4 @@ public static ArrayList getToggledOut() { public static Map getJumpStatistics() { return JUMPS; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ProjectKorra.java b/src/com/projectkorra/projectkorra/ProjectKorra.java index eaaadea69..72f695b3f 100644 --- a/src/com/projectkorra/projectkorra/ProjectKorra.java +++ b/src/com/projectkorra/projectkorra/ProjectKorra.java @@ -24,8 +24,11 @@ import com.projectkorra.projectkorra.firebending.util.FirebendingManager; import com.projectkorra.projectkorra.object.Preset; import com.projectkorra.projectkorra.storage.DBConnection; +import com.projectkorra.projectkorra.util.DBCooldownManager; +import com.projectkorra.projectkorra.util.FlightHandler; import com.projectkorra.projectkorra.util.Metrics; import com.projectkorra.projectkorra.util.RevertChecker; +import com.projectkorra.projectkorra.util.StatisticsManager; import com.projectkorra.projectkorra.util.TempBlock; import com.projectkorra.projectkorra.util.Updater; import com.projectkorra.projectkorra.waterbending.util.WaterbendingManager; @@ -34,9 +37,11 @@ public class ProjectKorra extends JavaPlugin { public static ProjectKorra plugin; public static Logger log; - //public static PKLogHandler handler; public static CollisionManager collisionManager; public static CollisionInitializer collisionInitializer; + public static StatisticsManager statistics; + public static DBCooldownManager cooldowns; + public static FlightHandler flightHandler; public static long time_step = 1; public Updater updater; @@ -44,76 +49,56 @@ public class ProjectKorra extends JavaPlugin { public void onEnable() { plugin = this; ProjectKorra.log = this.getLogger(); - - /* - * try { File logFolder = new File(getDataFolder(), "Logs"); if - * (!logFolder.exists()) { logFolder.mkdirs(); } handler = new - * PKLogHandler(logFolder + File.separator + "ERROR.%g.log"); - * log.getParent().addHandler(handler); } catch (SecurityException | - * IOException e) { e.printStackTrace(); } - */ new ConfigManager(); new GeneralMethods(this); - updater = new Updater(this, "http://projectkorra.com/forum/forums/dev-builds.16/index.rss"); + final boolean checkUpdateOnStartup = ConfigManager.getConfig().getBoolean("Properties.UpdateChecker"); + this.updater = new Updater(this, "https://projectkorra.com/forum/resources/projectkorra-core.1/", checkUpdateOnStartup); new Commands(this); new MultiAbilityManager(); new ComboManager(); collisionManager = new CollisionManager(); collisionInitializer = new CollisionInitializer(collisionManager); CoreAbility.registerAbilities(); - collisionInitializer.initializeDefaultCollisions(); // must be called - // after abilities - // have been - // registered + collisionInitializer.initializeDefaultCollisions(); collisionManager.startCollisionDetection(); Preset.loadExternalPresets(); - DBConnection.host = getConfig().getString("Storage.MySQL.host"); - DBConnection.port = getConfig().getInt("Storage.MySQL.port"); - DBConnection.pass = getConfig().getString("Storage.MySQL.pass"); - DBConnection.db = getConfig().getString("Storage.MySQL.db"); - DBConnection.user = getConfig().getString("Storage.MySQL.user"); DBConnection.init(); - if (DBConnection.isOpen() == false) { - // Message is logged by DBConnection + if (!DBConnection.isOpen()) { return; } - getServer().getPluginManager().registerEvents(new PKListener(this), this); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new BendingManager(), 0, 1); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new AirbendingManager(this), 0, 1); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new WaterbendingManager(this), 0, 1); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new EarthbendingManager(this), 0, 1); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new FirebendingManager(this), 0, 1); - getServer().getScheduler().scheduleSyncRepeatingTask(this, new ChiblockingManager(this), 0, 1); - // getServer().getScheduler().scheduleSyncRepeatingTask(this, new - // PassiveHandler(), 0, 1); - getServer().getScheduler().runTaskTimerAsynchronously(this, new RevertChecker(this), 0, 200); + statistics = new StatisticsManager(); + cooldowns = new DBCooldownManager(); + flightHandler = new FlightHandler(); + + this.getServer().getPluginManager().registerEvents(new PKListener(this), this); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new BendingManager(), 0, 1); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new AirbendingManager(this), 0, 1); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new WaterbendingManager(this), 0, 1); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new EarthbendingManager(this), 0, 1); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new FirebendingManager(this), 0, 1); + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new ChiblockingManager(this), 0, 1); + this.getServer().getScheduler().runTaskTimerAsynchronously(this, new RevertChecker(this), 0, 200); if (ConfigManager.languageConfig.get().getBoolean("Chat.Branding.AutoAnnouncer.Enabled")) { - getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { + this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { @Override public void run() { - ChatColor color = ChatColor - .valueOf(ConfigManager.languageConfig.get().getString("Chat.Branding.Color").toUpperCase()); + ChatColor color = ChatColor.valueOf(ConfigManager.languageConfig.get().getString("Chat.Branding" + ".Color").toUpperCase()); color = color == null ? ChatColor.GOLD : color; - String topBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.TopBorder"); - String bottomBorder = ConfigManager.languageConfig.get() - .getString("Chat.Branding.Borders.BottomBorder"); + final String topBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders.TopBorder"); + final String bottomBorder = ConfigManager.languageConfig.get().getString("Chat.Branding.Borders" + ".BottomBorder"); if (!topBorder.isEmpty()) { Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', topBorder)); } - Bukkit.broadcastMessage(color + "This server is running ProjectKorra version " - + ProjectKorra.plugin.getDescription().getVersion() - + " for bending! Find out more at http://www.projectkorra.com!"); + Bukkit.broadcastMessage(color + "This server is running ProjectKorra version " + ProjectKorra.plugin.getDescription().getVersion() + " for bending! Find out more at http://www" + ".projectkorra.com!"); if (!bottomBorder.isEmpty()) { Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', bottomBorder)); } } - }, (long) (ConfigManager.languageConfig.get().getDouble("Chat.Branding.AutoAnnouncer.Interval") * 60 * 20), - (long) (ConfigManager.languageConfig.get().getDouble("Chat.Branding.AutoAnnouncer.Interval") * 60 - * 20)); + }, (long) (ConfigManager.languageConfig.get().getDouble("Chat.Branding.AutoAnnouncer.Interval") * 60 * 20), (long) (ConfigManager.languageConfig.get().getDouble("Chat.Branding.AutoAnnouncer.Interval") * 60 * 20)); } TempBlock.startReversion(); @@ -122,6 +107,7 @@ public void run() { GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); GeneralMethods.removeUnusableAbilities(player.getName()); + statistics.load(player.getUniqueId()); Bukkit.getScheduler().runTaskLater(ProjectKorra.plugin, new Runnable() { @Override public void run() { @@ -131,22 +117,22 @@ public void run() { }, 5); } - Metrics metrics = new Metrics(this); + final Metrics metrics = new Metrics(this); metrics.addCustomChart(new Metrics.AdvancedPie("Elements") { @Override - public HashMap getValues(HashMap valueMap) { - for (Element element : Element.getMainElements()) { - valueMap.put(element.getName(), getPlayersWithElement(element)); + public HashMap getValues(final HashMap valueMap) { + for (final Element element : Element.getMainElements()) { + valueMap.put(element.getName(), this.getPlayersWithElement(element)); } return valueMap; } - private int getPlayersWithElement(Element element) { + private int getPlayersWithElement(final Element element) { int counter = 0; - for (Player player : Bukkit.getOnlinePlayers()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + for (final Player player : Bukkit.getOnlinePlayers()) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer != null && bPlayer.hasElement(element)) { counter++; } @@ -156,20 +142,28 @@ private int getPlayersWithElement(Element element) { } }); - double cacheTime = ConfigManager.getConfig().getDouble("Properties.RegionProtection.CacheBlockTime"); + final double cacheTime = ConfigManager.getConfig().getDouble("Properties.RegionProtection.CacheBlockTime"); if (Bukkit.getPluginManager().getPlugin("Residence") != null) { FlagPermissions.addFlag(ConfigManager.defaultConfig.get().getString("Properties.RegionProtection.Residence.Flag")); } - + GeneralMethods.deserializeFile(); GeneralMethods.startCacheCleaner(cacheTime); - updater.checkUpdate(); } @Override public void onDisable() { GeneralMethods.stopBending(); - if (DBConnection.isOpen != false) { + for (final Player player : this.getServer().getOnlinePlayers()) { + if (isStatisticsEnabled()) { + statistics.save(player.getUniqueId(), false); + } + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (bPlayer != null) { + bPlayer.saveCooldowns(); + } + } + if (DBConnection.isOpen()) { DBConnection.sql.close(); } } @@ -178,7 +172,7 @@ public static CollisionManager getCollisionManager() { return collisionManager; } - public static void setCollisionManager(CollisionManager collisionManager) { + public static void setCollisionManager(final CollisionManager collisionManager) { ProjectKorra.collisionManager = collisionManager; } @@ -186,8 +180,12 @@ public static CollisionInitializer getCollisionInitializer() { return collisionInitializer; } - public static void setCollisionInitializer(CollisionInitializer collisionInitializer) { + public static void setCollisionInitializer(final CollisionInitializer collisionInitializer) { ProjectKorra.collisionInitializer = collisionInitializer; } + public static boolean isStatisticsEnabled() { + return ConfigManager.getConfig().getBoolean("Properties.Statistics"); + } + } diff --git a/src/com/projectkorra/projectkorra/ability/Ability.java b/src/com/projectkorra/projectkorra/ability/Ability.java index 4936e6ed1..7e70fbd9a 100644 --- a/src/com/projectkorra/projectkorra/ability/Ability.java +++ b/src/com/projectkorra/projectkorra/ability/Ability.java @@ -14,7 +14,6 @@ import com.projectkorra.projectkorra.firebending.FireBlastCharged; import com.projectkorra.projectkorra.firebending.FireBurst; import com.projectkorra.projectkorra.waterbending.TorrentWave; -import com.projectkorra.projectkorra.waterbending.passive.WaterPassive; /** * The Ability interface defines the set of methods that any CoreAbility, @@ -23,7 +22,6 @@ * methods, but most will need to be specified by each Ability individually. */ public interface Ability { - /** * Causes the ability to be updated. */ @@ -38,7 +36,7 @@ public interface Ability { * Determines if this ability uses the {@link PlayerToggleSneakEvent} as a * controlling mechanism. Currently {@link WaterPassive} will not work while * the player has a sneak ability bound. - * + * * @return true if the ability uses sneak as a controlling mechanism */ public boolean isSneakAbility(); @@ -47,7 +45,7 @@ public interface Ability { * Determines if this ability is considered harmless against other players. * A harmless ability cannot manipulate another player. For example: * AirPassive, WaterSpout, AirSpout, and FireJet. - * + * * @return true if the ability is harmless and should be allowed in both PvP * and non-PvP zones */ @@ -69,7 +67,7 @@ public interface Ability { * A hidden ability is an ability that should not be shown by commands such * as /bending display and /bending help. For example: Combos, * MultiAbility sub abilities, and helper abilities. - * + * * @return true if the ability should not be displayed to the players */ public boolean isHiddenAbility(); @@ -91,7 +89,7 @@ public interface Ability { * can be null in certain circumstances, for example when calling * {@link CoreAbility#getAbility(String)}, or if an ability decided to set * player to null. - * + * * @return the player that this ability belongs to */ public Player getPlayer(); @@ -105,7 +103,7 @@ public interface Ability { * the same name (SurgeWall/SurgeWave) but need to have independent * cooldowns, then {@link BendingPlayer#addCooldown(String, long)} should be * called explicitly. - * + * * @return Returns the name of the ability */ public String getName(); @@ -126,7 +124,7 @@ public interface Ability { * player can fully utilize the ability. In most cases the description will * be specified in the config.yml file and will be retrieved by accessing * the FileConfiguration via {@link CoreAbility#getConfig}. - * + * * @return the description for this ability * @see HelpCommand * @see CoreAbility#getDescription() @@ -137,7 +135,7 @@ public interface Ability { * Specifies the Element used to represent this type of ability, favoring * SubElements over Elements. For example, a LightningAbility would return * {@link Element#LIGHTNING} instead of {@link Element#FIRE}. - * + * * @return the most accurate Element that this ability belongs to * @see SubElement#getParentElement */ @@ -150,10 +148,9 @@ public interface Ability { * while it is possible for an {@link EarthBlast}. The location is useful * for making sure that the player is currently in the same world as the * ability. - * + * * @return the location of the Ability * @see BendingPlayer#canBend(CoreAbility) */ public Location getLocation(); - } diff --git a/src/com/projectkorra/projectkorra/ability/AirAbility.java b/src/com/projectkorra/projectkorra/ability/AirAbility.java index 7b9e23d90..3e0ec60e9 100644 --- a/src/com/projectkorra/projectkorra/ability/AirAbility.java +++ b/src/com/projectkorra/projectkorra/ability/AirAbility.java @@ -1,5 +1,14 @@ package com.projectkorra.projectkorra.ability; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; @@ -9,18 +18,9 @@ import com.projectkorra.projectkorra.util.ParticleEffect; import com.projectkorra.projectkorra.util.ParticleEffect.ParticleData; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - public abstract class AirAbility extends ElementalAbility { - public AirAbility(Player player) { + public AirAbility(final Player player) { super(player); } @@ -40,10 +40,10 @@ public Element getElement() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { super.handleCollision(collision); if (collision.isRemovingFirst()) { - ParticleData particleData = (ParticleEffect.ParticleData) new ParticleEffect.BlockData(Material.WOOL, (byte) 0); + final ParticleData particleData = new ParticleEffect.BlockData(Material.WOOL, (byte) 0); ParticleEffect.BLOCK_CRACK.display(particleData, 1F, 1F, 1F, 0.1F, 10, collision.getLocationFirst(), 50); } } @@ -51,17 +51,17 @@ public void handleCollision(Collision collision) { /** * Breaks a breathbendng hold on an entity or one a player is inflicting on * an entity. - * + * * @param entity The entity to be acted upon */ - public static void breakBreathbendingHold(Entity entity) { + public static void breakBreathbendingHold(final Entity entity) { if (Suffocate.isBreathbent(entity)) { Suffocate.breakSuffocate(entity); return; } if (entity instanceof Player) { - Player player = (Player) entity; + final Player player = (Player) entity; if (Suffocate.isChannelingSphere(player)) { Suffocate.remove(player); } @@ -70,11 +70,11 @@ public static void breakBreathbendingHold(Entity entity) { /** * Gets the Air Particles from the config. - * + * * @return Config specified ParticleEffect */ public static ParticleEffect getAirbendingParticles() { - String particle = getConfig().getString("Properties.Air.Particles"); + final String particle = getConfig().getString("Properties.Air.Particles"); if (particle == null) { return ParticleEffect.CLOUD; } else if (particle.equalsIgnoreCase("spell")) { @@ -95,59 +95,61 @@ public static ParticleEffect getAirbendingParticles() { * {@link Collision} for the new system. *

* Checks whether a location is within an AirShield. - * + * * @param loc The location to check * @return true If the location is inside an AirShield. */ @Deprecated - public static boolean isWithinAirShield(Location loc) { - List list = new ArrayList(); + public static boolean isWithinAirShield(final Location loc) { + final List list = new ArrayList(); list.add("AirShield"); return GeneralMethods.blockAbilities(null, list, loc, 0); } /** * Plays an integer amount of air particles in a location. - * + * * @param loc The location to use * @param amount The amount of particles */ - public static void playAirbendingParticles(Location loc, int amount) { + public static void playAirbendingParticles(final Location loc, final int amount) { playAirbendingParticles(loc, amount, (float) Math.random(), (float) Math.random(), (float) Math.random()); } /** * Plays an integer amount of air particles in a location with a given * xOffset, yOffset, and zOffset. - * + * * @param loc The location to use * @param amount The amount of particles * @param xOffset The xOffset to use * @param yOffset The yOffset to use * @param zOffset The zOffset to use */ - public static void playAirbendingParticles(Location loc, int amount, float xOffset, float yOffset, float zOffset) { + public static void playAirbendingParticles(final Location loc, final int amount, final float xOffset, final float yOffset, final float zOffset) { getAirbendingParticles().display(loc, xOffset, yOffset, zOffset, 0, amount); } /** * Plays the Airbending Sound at a location if enabled in the config. - * + * * @param loc The location to play the sound at */ - public static void playAirbendingSound(Location loc) { + public static void playAirbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Air.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Air.Sound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Air.Sound.Pitch"); + final float volume = (float) getConfig().getDouble("Properties.Air.Sound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Air.Sound.Pitch"); Sound sound = Sound.ENTITY_CREEPER_HURT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Air.Sound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Air.Sound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } @@ -157,13 +159,13 @@ public static void playAirbendingSound(Location loc) { * {@link Collision} for the new system. *

* Removes all air spouts in a location within a certain radius. - * + * * @param loc The location to use * @param radius The radius around the location to remove spouts in * @param source The player causing the removal */ @Deprecated - public static void removeAirSpouts(Location loc, double radius, Player source) { + public static void removeAirSpouts(final Location loc, final double radius, final Player source) { AirSpout.removeSpouts(loc, radius, source); } @@ -172,13 +174,13 @@ public static void removeAirSpouts(Location loc, double radius, Player source) { * {@link Collision} for the new system. *

* Removes all air spouts in a location with a radius of 1.5. - * + * * @param loc The location to use * @param source The player causing the removal */ @Deprecated - public static void removeAirSpouts(Location loc, Player source) { + public static void removeAirSpouts(final Location loc, final Player source) { removeAirSpouts(loc, 1.5, source); } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/AvatarAbility.java b/src/com/projectkorra/projectkorra/ability/AvatarAbility.java index 441a19534..112180c27 100644 --- a/src/com/projectkorra/projectkorra/ability/AvatarAbility.java +++ b/src/com/projectkorra/projectkorra/ability/AvatarAbility.java @@ -1,15 +1,15 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; -import com.projectkorra.projectkorra.ProjectKorra; - import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.ProjectKorra; + public abstract class AvatarAbility extends ElementalAbility { - public AvatarAbility(Player player) { + public AvatarAbility(final Player player) { super(player); } @@ -28,19 +28,21 @@ public final Element getElement() { return Element.AVATAR; } - public static void playAvatarSound(Location loc) { + public static void playAvatarSound(final Location loc) { if (getConfig().getBoolean("Abilities.Avatar.AvatarState.PlaySound")) { - float volume = (float) getConfig().getDouble("Abilities.Avatar.AvatarState.Sound.Volume"); - float pitch = (float) getConfig().getDouble("Abilities.Avatar.AvatarState.Sound.Pitch"); - + final float volume = (float) getConfig().getDouble("Abilities.Avatar.AvatarState.Sound.Volume"); + final float pitch = (float) getConfig().getDouble("Abilities.Avatar.AvatarState.Sound.Pitch"); + Sound sound = Sound.BLOCK_ANVIL_LAND; - + try { - sound = Sound.valueOf(getConfig().getString("Properties.Avatar.AvatarState.Sound.Sound")); - } catch (IllegalArgumentException exception) { - ProjectKorra.log.warning("Your current value for 'Properties.Avatar.AvatarState.Sound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + sound = Sound.valueOf(getConfig().getString("Abilities.Avatar.AvatarState.Sound.Sound")); + } + catch (final IllegalArgumentException exception) { + ProjectKorra.log.warning("Your current value for 'Abilities.Avatar.AvatarState.Sound.Sound' is not valid."); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } @@ -54,4 +56,4 @@ public boolean requireAvatar() { return true; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/BloodAbility.java b/src/com/projectkorra/projectkorra/ability/BloodAbility.java index 36609ff30..7c7d48ffc 100644 --- a/src/com/projectkorra/projectkorra/ability/BloodAbility.java +++ b/src/com/projectkorra/projectkorra/ability/BloodAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class BloodAbility extends WaterAbility implements SubAbility { - public BloodAbility(Player player) { + public BloodAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/ChiAbility.java b/src/com/projectkorra/projectkorra/ability/ChiAbility.java index 8c975a9a5..49a582664 100644 --- a/src/com/projectkorra/projectkorra/ability/ChiAbility.java +++ b/src/com/projectkorra/projectkorra/ability/ChiAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class ChiAbility extends ElementalAbility { - public ChiAbility(Player player) { + public ChiAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/ComboAbility.java b/src/com/projectkorra/projectkorra/ability/ComboAbility.java index 151933910..1c6c98eba 100644 --- a/src/com/projectkorra/projectkorra/ability/ComboAbility.java +++ b/src/com/projectkorra/projectkorra/ability/ComboAbility.java @@ -1,10 +1,10 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import java.util.ArrayList; import org.bukkit.entity.Player; -import java.util.ArrayList; +import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; public interface ComboAbility { @@ -22,5 +22,4 @@ public interface ComboAbility { * @return An ArrayList containing the combo's steps. */ public abstract ArrayList getCombination(); - } diff --git a/src/com/projectkorra/projectkorra/ability/CombustionAbility.java b/src/com/projectkorra/projectkorra/ability/CombustionAbility.java index 80bac3dbf..786385ce0 100644 --- a/src/com/projectkorra/projectkorra/ability/CombustionAbility.java +++ b/src/com/projectkorra/projectkorra/ability/CombustionAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class CombustionAbility extends FireAbility implements SubAbility { - public CombustionAbility(Player player) { + public CombustionAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/CoreAbility.java b/src/com/projectkorra/projectkorra/ability/CoreAbility.java index 5b43cc7b6..dc41014f1 100644 --- a/src/com/projectkorra/projectkorra/ability/CoreAbility.java +++ b/src/com/projectkorra/projectkorra/ability/CoreAbility.java @@ -53,7 +53,7 @@ * For {@link CollisionManager} and {@link Collision}, a CoreAbility may need to * override {@link #isCollidable()}, {@link #getCollisionRadius()}, * {@link #handleCollision(Collision)}, and {@link #getLocations()}. - * + * * @see #start() * @see #progress() * @see #remove() @@ -65,7 +65,7 @@ public abstract class CoreAbility implements Ability { private static final Set INSTANCES = Collections.newSetFromMap(new ConcurrentHashMap()); private static final Map, Map>> INSTANCES_BY_PLAYER = new ConcurrentHashMap<>(); private static final Map, Set> INSTANCES_BY_CLASS = new ConcurrentHashMap<>(); - private static final Map ABILITIES_BY_NAME = new ConcurrentSkipListMap<>(); // preserves ordering + private static final Map ABILITIES_BY_NAME = new ConcurrentSkipListMap<>(); // preserves ordering. private static final Map, CoreAbility> ABILITIES_BY_CLASS = new ConcurrentHashMap<>(); private static final double DEFAULT_COLLISION_RADIUS = 0.3; private static final List ADDON_PLUGINS = new ArrayList<>(); @@ -93,7 +93,7 @@ public abstract class CoreAbility implements Ability { * getDeclaredConstructor which is only usable with a public default * constructor. Reflection lets us create a list of all of the plugin's * abilities when the plugin first loads. - * + * * @see #ABILITIES_BY_NAME * @see #getAbility(String) */ @@ -102,12 +102,12 @@ public CoreAbility() { /** * Creates a new CoreAbility instance but does not start it. - * + * * @param player the non-null player that created this instance * @see #start() */ - public CoreAbility(Player player) { - if (player == null) { + public CoreAbility(final Player player) { + if (player == null || !this.isEnabled()) { return; } @@ -116,7 +116,7 @@ public CoreAbility(Player player) { this.startTime = System.currentTimeMillis(); this.started = false; this.id = CoreAbility.idCounter; - this.startTick = getCurrentTick(); + this.startTick = this.getCurrentTick(); if (idCounter == Integer.MAX_VALUE) { idCounter = Integer.MIN_VALUE; @@ -130,25 +130,25 @@ public CoreAbility(Player player) { * {@link #progress()} until {@link #remove()} is called. This method cannot * be overridden, and any code that needs to be performed before start * should be handled in the constructor. - * + * * @see #getStartTime() * @see #isStarted() * @see #isRemoved() */ - public final void start() { - if (player == null) { + public void start() { + if (this.player == null || !this.isEnabled()) { return; } - AbilityStartEvent event = new AbilityStartEvent(this); + final AbilityStartEvent event = new AbilityStartEvent(this); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { - remove(); + this.remove(); return; } this.started = true; this.startTime = System.currentTimeMillis(); - Class clazz = getClass(); - UUID uuid = player.getUniqueId(); + final Class clazz = this.getClass(); + final UUID uuid = this.player.getUniqueId(); if (!INSTANCES_BY_PLAYER.containsKey(clazz)) { INSTANCES_BY_PLAYER.put(clazz, new ConcurrentHashMap>()); @@ -169,37 +169,37 @@ public final void start() { * Causes this CoreAbility instance to be removed, and {@link #progress} * will no longer be called every tick. If this method is overridden then * the new method must call super.remove(). - * + * * {@inheritDoc} - * + * * @see #isRemoved() */ @Override public void remove() { - if (player == null) { + if (this.player == null) { return; } Bukkit.getServer().getPluginManager().callEvent(new AbilityEndEvent(this)); - removed = true; + this.removed = true; - Map> classMap = INSTANCES_BY_PLAYER.get(getClass()); + final Map> classMap = INSTANCES_BY_PLAYER.get(this.getClass()); if (classMap != null) { - Map playerMap = classMap.get(player.getUniqueId()); + final Map playerMap = classMap.get(this.player.getUniqueId()); if (playerMap != null) { playerMap.remove(this.id); if (playerMap.size() == 0) { - classMap.remove(player.getUniqueId()); + classMap.remove(this.player.getUniqueId()); } } if (classMap.size() == 0) { - INSTANCES_BY_PLAYER.remove(getClass()); + INSTANCES_BY_PLAYER.remove(this.getClass()); } } - if (INSTANCES_BY_CLASS.containsKey(getClass())) { - INSTANCES_BY_CLASS.get(getClass()).remove(this); + if (INSTANCES_BY_CLASS.containsKey(this.getClass())) { + INSTANCES_BY_CLASS.get(this.getClass()).remove(this); } INSTANCES.remove(this); } @@ -209,28 +209,37 @@ public void remove() { * that has been started and has not been removed. */ public static void progressAll() { - for (Set setAbils : INSTANCES_BY_CLASS.values()) { - for (CoreAbility abil : setAbils) { + for (final Set setAbils : INSTANCES_BY_CLASS.values()) { + for (final CoreAbility abil : setAbils) { if (abil instanceof PassiveAbility) { - BendingPlayer bPlayer = abil.getBendingPlayer(); - if (bPlayer == null || !abil.getPlayer().isOnline()) { - abil.remove(); + if (!((PassiveAbility) abil).isProgressable()) { continue; - } else if (!bPlayer.canBendPassive(abil.getElement())) { // Check for if the passive should be removed - abil.remove(); + } + + if (!abil.getPlayer().isOnline()) { // This has to be before isDead as isDead. + abil.remove(); // will return true if they are offline. continue; - } else if (!bPlayer.canUsePassive(abil.getElement())) { // Check for if the passive should be prevented from happening, but not remove it + } else if (abil.getPlayer().isDead()) { continue; } + } else if (abil.getPlayer().isDead()) { + abil.remove(); + continue; + } else if (!abil.getPlayer().isOnline()) { + abil.remove(); + continue; } + try { abil.progress(); Bukkit.getServer().getPluginManager().callEvent(new AbilityProgressEvent(abil)); - } catch (Exception e) { + } + catch (final Exception e) { e.printStackTrace(); try { abil.remove(); - } catch (Exception re) { + } + catch (final Exception re) { re.printStackTrace(); } } @@ -243,15 +252,15 @@ public static void progressAll() { * removed. */ public static void removeAll() { - for (Set setAbils : INSTANCES_BY_CLASS.values()) { - for (CoreAbility abil : setAbils) { + for (final Set setAbils : INSTANCES_BY_CLASS.values()) { + for (final CoreAbility abil : setAbils) { abil.remove(); } } - for (CoreAbility coreAbility : ABILITIES_BY_NAME.values()) { + for (final CoreAbility coreAbility : ABILITIES_BY_NAME.values()) { if (coreAbility instanceof AddonAbility) { - AddonAbility addon = (AddonAbility) coreAbility; + final AddonAbility addon = (AddonAbility) coreAbility; addon.stop(); } } @@ -260,13 +269,13 @@ public static void removeAll() { /** * Returns any T CoreAbility that has been started and not yet removed. May * return null if no such ability exists. - * + * * @param player the player that created the CoreAbility instance * @param clazz the class of the type of CoreAbility * @return a CoreAbility instance or null */ - public static T getAbility(Player player, Class clazz) { - Collection abils = getAbilities(player, clazz); + public static T getAbility(final Player player, final Class clazz) { + final Collection abils = getAbilities(player, clazz); if (abils.iterator().hasNext()) { return abils.iterator().next(); } @@ -279,30 +288,30 @@ public static T getAbility(Player player, Class clazz * Players, instead this method looks at the CoreAbilities that were created * via Reflection by {@link #registerAbilities()} when the plugin was first * loaded. - * + * *

* These "fake" instances have a null player, but methods such as * {@link Ability#getName()}, and {@link Ability#getElement()} will still * work, as will checking the type of the ability with instanceof. - * + * *

* CoreAbility coreAbil = getAbility(someString);
* if (coreAbil instanceof FireAbility && coreAbil.isSneakAbility()) - * + * * @param abilityName the name of a loaded CoreAbility * @return a "fake" CoreAbility instance, or null if no such ability exists */ - public static CoreAbility getAbility(String abilityName) { + public static CoreAbility getAbility(final String abilityName) { return abilityName != null ? ABILITIES_BY_NAME.get(abilityName.toLowerCase()) : null; } /** * Returns a "fake" instance for a CoreAbility with the specific class. - * + * * @param clazz the class for the type of CoreAbility to be returned * @return a "fake" CoreAbility instance or null */ - public static CoreAbility getAbility(Class clazz) { + public static CoreAbility getAbility(final Class clazz) { return clazz != null ? ABILITIES_BY_CLASS.get(clazz) : null; } @@ -314,15 +323,22 @@ public static ArrayList getAbilities() { return new ArrayList(ABILITIES_BY_CLASS.values()); } + /** + * @return a list of "fake" instances for each ability that was loaded by + * {@link #registerAbilities()} + */ + public static ArrayList getAbilitiesByName() { + return new ArrayList(ABILITIES_BY_NAME.values()); + } + /** * Returns a Collection of all of the player created instances for a * specific type of CoreAbility. - * + * * @param clazz the class for the type of CoreAbilities * @return a Collection of real instances */ - @SuppressWarnings("unchecked") - public static Collection getAbilities(Class clazz) { + public static Collection getAbilities(final Class clazz) { if (clazz == null || INSTANCES_BY_CLASS.get(clazz) == null || INSTANCES_BY_CLASS.get(clazz).size() == 0) { return Collections.emptySet(); } @@ -332,13 +348,12 @@ public static Collection getAbilities(Class clazz) /** * Returns a Collection of specific CoreAbility instances that were created * by the specified player. - * + * * @param player the player that created the instances * @param clazz the class for the type of CoreAbilities * @return a Collection of real instances */ - @SuppressWarnings("unchecked") - public static Collection getAbilities(Player player, Class clazz) { + public static Collection getAbilities(final Player player, final Class clazz) { if (player == null || clazz == null || INSTANCES_BY_PLAYER.get(clazz) == null || INSTANCES_BY_PLAYER.get(clazz).get(player.getUniqueId()) == null) { return Collections.emptySet(); } @@ -356,18 +371,18 @@ public static Collection getAbilitiesByInstances() { /** * Returns an List of fake instances that were loaded by * {@link #registerAbilities()} filtered by Element. - * + * * @param element the Element of the loaded abilities * @return a list of fake CoreAbility instances */ - public static List getAbilitiesByElement(Element element) { - ArrayList abilities = new ArrayList(); + public static List getAbilitiesByElement(final Element element) { + final ArrayList abilities = new ArrayList(); if (element != null) { - for (CoreAbility ability : getAbilities()) { + for (final CoreAbility ability : getAbilities()) { if (ability.getElement() == element) { abilities.add(ability); } else if (ability.getElement() instanceof SubElement) { - Element parentElement = ((SubElement) ability.getElement()).getParentElement(); + final Element parentElement = ((SubElement) ability.getElement()).getParentElement(); if (parentElement == element) { abilities.add(ability); } @@ -376,12 +391,14 @@ public static List getAbilitiesByElement(Element element) { } return abilities; } - + /** - * CoreAbility keeps track of plugins that have registered abilities - * to use for bending reload purposes - *
This isn't a simple list, external use isn't recommended - * @return a list of entrys with the plugin name and path abilities can be found at + * CoreAbility keeps track of plugins that have registered abilities to use + * for bending reload purposes
+ * This isn't a simple list, external use isn't recommended + * + * @return a list of entrys with the plugin name and path abilities can be + * found at */ public static List getAddonPlugins() { return ADDON_PLUGINS; @@ -389,24 +406,25 @@ public static List getAddonPlugins() { /** * Returns true if the player has an active CoreAbility instance of type T. - * + * * @param player the player that created the T instance * @param clazz the class for the type of CoreAbility */ - public static boolean hasAbility(Player player, Class clazz) { + public static boolean hasAbility(final Player player, final Class clazz) { return getAbility(player, clazz) != null; } - + /** * Unloads the ability + * * @param clazz Ability class to unload */ - public static void unloadAbility(Class clazz) { + public static void unloadAbility(final Class clazz) { if (!ABILITIES_BY_CLASS.containsKey(clazz)) { return; } - String name = ABILITIES_BY_CLASS.get(clazz).getName(); - for (CoreAbility abil : INSTANCES) { + final String name = ABILITIES_BY_CLASS.get(clazz).getName(); + for (final CoreAbility abil : INSTANCES) { if (abil.getName() == name) { abil.remove(); } @@ -419,16 +437,16 @@ public static void unloadAbility(Class clazz) { /** * Returns a Set of all of the players that currently have an active * instance of clazz. - * + * * @param clazz the clazz for the type of CoreAbility */ - public static Set getPlayers(Class clazz) { - HashSet players = new HashSet<>(); + public static Set getPlayers(final Class clazz) { + final HashSet players = new HashSet<>(); if (clazz != null) { - Map> uuidMap = INSTANCES_BY_PLAYER.get(clazz); + final Map> uuidMap = INSTANCES_BY_PLAYER.get(clazz); if (uuidMap != null) { - for (UUID uuid : uuidMap.keySet()) { - Player uuidPlayer = Bukkit.getPlayer(uuid); + for (final UUID uuid : uuidMap.keySet()) { + final Player uuidPlayer = Bukkit.getPlayer(uuid); if (uuidPlayer != null) { players.add(uuidPlayer); } @@ -450,10 +468,9 @@ public static void registerAbilities() { } /** - * Scans a JavaPlugin and registers CoreAbility class files. - * Does not work. Use {@link CoreAbility.registerPluginAbilities} - * instead! - * + * Scans a JavaPlugin and registers CoreAbility class files. Does not work. + * Use {@link CoreAbility.registerPluginAbilities} instead! + * * @param plugin a JavaPlugin containing CoreAbility class files * @param packagePrefix a prefix of the package name, used to increase * performance @@ -461,16 +478,16 @@ public static void registerAbilities() { * @see #getAbility(String) */ @Deprecated - public static void legacyRegisterPluginAbilities(JavaPlugin plugin, String packagePrefix) { - List disabled = new ArrayList(); //this way multiple classes with the same name only show once + public static void legacyRegisterPluginAbilities(final JavaPlugin plugin, final String packagePrefix) { + final List disabled = new ArrayList(); // this way multiple classes with the same name only show once. if (plugin == null) { return; } - Class pluginClass = plugin.getClass(); - ClassLoader loader = pluginClass.getClassLoader(); - - ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); + final Class pluginClass = plugin.getClass(); + final ClassLoader loader = pluginClass.getClassLoader(); + + final ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); try { for (final ClassInfo info : ClassPath.from(loader).getAllClasses()) { @@ -485,9 +502,9 @@ public static void legacyRegisterPluginAbilities(JavaPlugin plugin, String packa continue; } - Constructor objDef = CoreAbility.class.getDeclaredConstructor(); - Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); - CoreAbility ability = (CoreAbility) clazz.cast(intConstr.newInstance()); + final Constructor objDef = CoreAbility.class.getDeclaredConstructor(); + final Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); + final CoreAbility ability = (CoreAbility) clazz.cast(intConstr.newInstance()); if (ability == null || ability.getName() == null) { continue; @@ -497,12 +514,12 @@ public static void legacyRegisterPluginAbilities(JavaPlugin plugin, String packa continue; } - String name = ability.getName(); + final String name = ability.getName(); ABILITIES_BY_NAME.put(ability.getName().toLowerCase(), ability); ABILITIES_BY_CLASS.put(ability.getClass(), ability); if (ability instanceof ComboAbility) { - ComboAbility combo = (ComboAbility) ability; + final ComboAbility combo = (ComboAbility) ability; if (combo.getCombination() != null) { ComboManager.getComboAbilities().put(name, new ComboManager.ComboAbilityInfo(name, combo.getCombination(), combo)); ComboManager.getDescriptions().put(name, ability.getDescription()); @@ -516,7 +533,7 @@ public static void legacyRegisterPluginAbilities(JavaPlugin plugin, String packa } if (ability instanceof MultiAbility) { - MultiAbility multiAbil = (MultiAbility) ability; + final MultiAbility multiAbil = (MultiAbility) ability; MultiAbilityManager.multiAbilityList.add(new MultiAbilityInfo(name, multiAbil.getMultiAbilities())); } @@ -526,45 +543,48 @@ public static void legacyRegisterPluginAbilities(JavaPlugin plugin, String packa } if (ability instanceof AddonAbility) { - AddonAbility addon = (AddonAbility) ability; + final AddonAbility addon = (AddonAbility) ability; addon.load(); } } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } - catch (Error e) { + catch (final Error e) { e.printStackTrace(); } } } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } } - + /** * Scans a JavaPlugin and registers CoreAbility class files. - * + * * @param plugin a JavaPlugin containing CoreAbility class files * @param packageBase a prefix of the package name, used to increase * performance * @see #getAbilities() * @see #getAbility(String) */ - public static void registerPluginAbilities(JavaPlugin plugin, String packageBase) { - AbilityLoader abilityLoader = new AbilityLoader(plugin, packageBase); - List loadedAbilities = abilityLoader.load(CoreAbility.class, CoreAbility.class); - ADDON_PLUGINS.add(plugin.getName() + "::" + packageBase); - - for (CoreAbility coreAbil : loadedAbilities) { + public static void registerPluginAbilities(final JavaPlugin plugin, final String packageBase) { + final AbilityLoader abilityLoader = new AbilityLoader(plugin, packageBase); + final List loadedAbilities = abilityLoader.load(CoreAbility.class, CoreAbility.class); + final String entry = plugin.getName() + "::" + packageBase; + if (!ADDON_PLUGINS.contains(entry)) { + ADDON_PLUGINS.add(entry); + } + + for (final CoreAbility coreAbil : loadedAbilities) { if (!coreAbil.isEnabled()) { plugin.getLogger().info(coreAbil.getName() + " is disabled"); continue; } - String name = coreAbil.getName(); - + final String name = coreAbil.getName(); + if (name == null) { plugin.getLogger().warning("Ability " + coreAbil.getClass().getName() + " has no name?"); continue; @@ -575,7 +595,7 @@ public static void registerPluginAbilities(JavaPlugin plugin, String packageBase ABILITIES_BY_CLASS.put(coreAbil.getClass(), coreAbil); if (coreAbil instanceof ComboAbility) { - ComboAbility combo = (ComboAbility) coreAbil; + final ComboAbility combo = (ComboAbility) coreAbil; if (combo.getCombination() != null) { ComboManager.getComboAbilities().put(name, new ComboManager.ComboAbilityInfo(name, combo.getCombination(), combo)); ComboManager.getDescriptions().put(name, coreAbil.getDescription()); @@ -584,14 +604,14 @@ public static void registerPluginAbilities(JavaPlugin plugin, String packageBase } if (coreAbil instanceof MultiAbility) { - MultiAbility multiAbil = (MultiAbility) coreAbil; + final MultiAbility multiAbil = (MultiAbility) coreAbil; MultiAbilityManager.multiAbilityList.add(new MultiAbilityInfo(name, multiAbil.getMultiAbilities())); } if (coreAbil instanceof PassiveAbility) { coreAbil.setHiddenAbility(true); PassiveManager.getPassives().put(name, coreAbil); - if (!PassiveManager.getPassiveClasses().containsKey((PassiveAbility)coreAbil)) { + if (!PassiveManager.getPassiveClasses().containsKey(coreAbil)) { PassiveManager.getPassiveClasses().put((PassiveAbility) coreAbil, coreAbil.getClass()); } PassiveManager.getPassiveClasses().put((PassiveAbility) coreAbil, coreAbil.getClass()); @@ -609,23 +629,23 @@ public static void registerPluginAbilities(JavaPlugin plugin, String packageBase /** * Scans all of the Jar files inside of /ProjectKorra/folder and registers * all of the CoreAbility class files that were found. - * + * * @param folder the name of the folder to scan * @see #getAbilities() * @see #getAbility(String) */ - public static void registerAddonAbilities(String folder) { - ProjectKorra plugin = ProjectKorra.plugin; - File path = new File(plugin.getDataFolder().toString() + folder); + public static void registerAddonAbilities(final String folder) { + final ProjectKorra plugin = ProjectKorra.plugin; + final File path = new File(plugin.getDataFolder().toString() + folder); if (!path.exists()) { path.mkdir(); return; } - AddonAbilityLoader abilityLoader = new AddonAbilityLoader(plugin, path); - List loadedAbilities = abilityLoader.load(CoreAbility.class, CoreAbility.class); + final AddonAbilityLoader abilityLoader = new AddonAbilityLoader(plugin, path); + final List loadedAbilities = abilityLoader.load(CoreAbility.class, CoreAbility.class); - for (CoreAbility coreAbil : loadedAbilities) { + for (final CoreAbility coreAbil : loadedAbilities) { if (!(coreAbil instanceof AddonAbility)) { plugin.getLogger().warning(coreAbil.getName() + " is an addon ability and must implement the AddonAbility interface"); continue; @@ -634,8 +654,8 @@ public static void registerAddonAbilities(String folder) { continue; } - AddonAbility addon = (AddonAbility) coreAbil; - String name = coreAbil.getName(); + final AddonAbility addon = (AddonAbility) coreAbil; + final String name = coreAbil.getName(); try { addon.load(); @@ -643,7 +663,7 @@ public static void registerAddonAbilities(String folder) { ABILITIES_BY_CLASS.put(coreAbil.getClass(), coreAbil); if (coreAbil instanceof ComboAbility) { - ComboAbility combo = (ComboAbility) coreAbil; + final ComboAbility combo = (ComboAbility) coreAbil; if (combo.getCombination() != null) { ComboManager.getComboAbilities().put(name, new ComboManager.ComboAbilityInfo(name, combo.getCombination(), combo)); ComboManager.getDescriptions().put(name, coreAbil.getDescription()); @@ -653,14 +673,14 @@ public static void registerAddonAbilities(String folder) { } if (coreAbil instanceof MultiAbility) { - MultiAbility multiAbil = (MultiAbility) coreAbil; + final MultiAbility multiAbil = (MultiAbility) coreAbil; MultiAbilityManager.multiAbilityList.add(new MultiAbilityInfo(name, multiAbil.getMultiAbilities())); } if (coreAbil instanceof PassiveAbility) { coreAbil.setHiddenAbility(true); PassiveManager.getPassives().put(name, coreAbil); - if (!PassiveManager.getPassiveClasses().containsKey((PassiveAbility)coreAbil)) { + if (!PassiveManager.getPassiveClasses().containsKey(coreAbil)) { PassiveManager.getPassiveClasses().put((PassiveAbility) coreAbil, coreAbil.getClass()); } } @@ -676,39 +696,39 @@ public static void registerAddonAbilities(String folder) { } public long getStartTime() { - return startTime; + return this.startTime; } public long getStartTick() { - return startTick; + return this.startTick; } public long getCurrentTick() { - return player.getWorld().getFullTime(); + return this.player.getWorld().getFullTime(); } public boolean isStarted() { - return started; + return this.started; } public boolean isRemoved() { - return removed; + return this.removed; } public BendingPlayer getBendingPlayer() { - return bPlayer; + return this.bPlayer; } public int getId() { - return id; + return this.id; } @Override public boolean isHiddenAbility() { - return hidden; + return this.hidden; } - public void setHiddenAbility(boolean hidden) { + public void setHiddenAbility(final boolean hidden) { this.hidden = hidden; } @@ -718,18 +738,18 @@ public boolean isEnabled() { return true; } - String elementName = getElement().getName(); - if (getElement() instanceof SubElement) { - elementName = ((SubElement) getElement()).getParentElement().getName(); + String elementName = this.getElement().getName(); + if (this.getElement() instanceof SubElement) { + elementName = ((SubElement) this.getElement()).getParentElement().getName(); } String tag = null; if (this instanceof ComboAbility) { - tag = "Abilities." + elementName + "." + elementName + "Combo." + getName() + ".Enabled"; + tag = "Abilities." + elementName + "." + elementName + "Combo." + this.getName() + ".Enabled"; } else if (this instanceof PassiveAbility) { - tag = "Abilities." + elementName + ".Passive." + getName() + ".Enabled"; + tag = "Abilities." + elementName + ".Passive." + this.getName() + ".Enabled"; } else { - tag = "Abilities." + elementName + "." + getName() + ".Enabled"; + tag = "Abilities." + elementName + "." + this.getName() + ".Enabled"; } if (getConfig().isBoolean(tag)) { @@ -742,63 +762,88 @@ public boolean isEnabled() { @Override public String getInstructions() { - String elementName = getElement().getName(); - if (getElement() instanceof SubElement) { - elementName = ((SubElement) getElement()).getParentElement().getName(); + String elementName = this.getElement().getName(); + if (this.getElement() instanceof SubElement) { + elementName = ((SubElement) this.getElement()).getParentElement().getName(); } - return ConfigManager.languageConfig.get().contains("Abilities." + elementName + "." + getName() + ".Instructions") ? ConfigManager.languageConfig.get().getString("Abilities." + elementName + "." + getName() + ".Instructions") : ""; + return ConfigManager.languageConfig.get().contains("Abilities." + elementName + "." + this.getName() + ".Instructions") ? ConfigManager.languageConfig.get().getString("Abilities." + elementName + "." + this.getName() + ".Instructions") : ""; } @Override public String getDescription() { - String elementName = getElement().getName(); - if (getElement() instanceof SubElement) { - elementName = ((SubElement) getElement()).getParentElement().getName(); + String elementName = this.getElement().getName(); + if (this.getElement() instanceof SubElement) { + elementName = ((SubElement) this.getElement()).getParentElement().getName(); } if (this instanceof PassiveAbility) { - return ConfigManager.languageConfig.get().getString("Abilities." + elementName + ".Passive." + getName() + ".Description"); + return ConfigManager.languageConfig.get().getString("Abilities." + elementName + ".Passive." + this.getName() + ".Description"); + } else if (this instanceof ComboAbility) { + return ConfigManager.languageConfig.get().getString("Abilities." + elementName + ".Combo." + this.getName() + ".Description"); } - return ConfigManager.languageConfig.get().getString("Abilities." + elementName + "." + getName() + ".Description"); + return ConfigManager.languageConfig.get().getString("Abilities." + elementName + "." + this.getName() + ".Description"); } @Override public Player getPlayer() { - return player; + return this.player; } /** * Changes the player that owns this ability instance. Used for redirection * and other abilities that change the player object. - * - * @param player The player who now controls the ability + * + * @param target The player who now controls the ability */ - public void setPlayer(Player player) { - Map> classMap = INSTANCES_BY_PLAYER.get(getClass()); + public void setPlayer(final Player target) { + if (target == this.player) { + return; + } + + final Class clazz = this.getClass(); + + // The mapping from player UUID to a map of the player's instances. + Map> classMap = INSTANCES_BY_PLAYER.get(clazz); + if (classMap != null) { - Map playerMap = classMap.get(player.getUniqueId()); + // The map of AbilityId to Ability for the current player. + final Map playerMap = classMap.get(this.player.getUniqueId()); + if (playerMap != null) { + // Remove the ability from the current player's map. playerMap.remove(this.id); - if (playerMap.size() == 0) { - classMap.remove(player.getUniqueId()); + + if (playerMap.isEmpty()) { + // Remove the player's empty ability map from global instances map. + classMap.remove(this.player.getUniqueId()); } } - if (classMap.size() == 0) { - INSTANCES_BY_PLAYER.remove(getClass()); + if (classMap.isEmpty()) { + INSTANCES_BY_PLAYER.remove(this.getClass()); } } - if (!INSTANCES_BY_PLAYER.containsKey(this.getClass())) { - INSTANCES_BY_PLAYER.put(this.getClass(), new ConcurrentHashMap>()); + // Add a new map for the current ability if it doesn't exist in the global map. + if (!INSTANCES_BY_PLAYER.containsKey(clazz)) { + INSTANCES_BY_PLAYER.put(clazz, new ConcurrentHashMap<>()); } - if (!INSTANCES_BY_PLAYER.get(this.getClass()).containsKey(player.getUniqueId())) { - INSTANCES_BY_PLAYER.get(this.getClass()).put(player.getUniqueId(), new ConcurrentHashMap()); + classMap = INSTANCES_BY_PLAYER.get(clazz); + + // Create an AbilityId to Ability map for the target player if it doesn't exist. + if (!classMap.containsKey(target.getUniqueId())) { + classMap.put(target.getUniqueId(), new ConcurrentHashMap<>()); } - INSTANCES_BY_PLAYER.get(this.getClass()).get(player.getUniqueId()).put(this.getId(), this); + // Add the current instance to the target player's ability map. + classMap.get(target.getUniqueId()).put(this.getId(), this); - this.player = player; + this.player = target; + + final BendingPlayer newBendingPlayer = BendingPlayer.getBendingPlayer(target); + if (newBendingPlayer != null) { + this.bPlayer = newBendingPlayer; + } } /** @@ -806,7 +851,7 @@ public void setPlayer(Player player) { * each other. For example, an EarthBlast is not collidable right when the * person selects a source block, but it is collidable once the block begins * traveling. - * + * * @return true if the instance is currently collidable * @see CollisionManager */ @@ -821,7 +866,7 @@ public boolean isCollidable() { * EarthBlast, etc. Some abilities consist of multiple Locations with small * radiuses, such as AirSpout, WaterSpout, Torrent, RaiseEarth, AirSwipe, * FireKick, etc. - * + * * @return the radius for a location returned by {@link #getLocations()} * @see CollisionManager */ @@ -839,13 +884,13 @@ public double getCollisionRadius() { *

* This ability should only worry about itself because handleCollision will * be called for the other ability instance as well. - * + * * @param collision with data about the other ability instance * @see CollisionManager */ - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { if (collision.isRemovingFirst()) { - remove(); + this.remove(); } } @@ -853,13 +898,13 @@ public void handleCollision(Collision collision) { * A List of Locations used to represent the ability. Some abilities might * just be 1 Location with a radius, while some might be multiple Locations * with small radiuses. - * + * * @return a List of the ability's locations * @see CollisionManager */ public List getLocations() { - ArrayList locations = new ArrayList<>(); - locations.add(getLocation()); + final ArrayList locations = new ArrayList<>(); + locations.add(this.getLocation()); return locations; } @@ -882,15 +927,15 @@ public static FileConfiguration getLanguageConfig() { * caused by a developer forgetting to call {@link #remove()} */ public static String getDebugString() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); int playerCounter = 0; - HashMap classCounter = new HashMap<>(); + final HashMap classCounter = new HashMap<>(); - for (Map> map1 : INSTANCES_BY_PLAYER.values()) { + for (final Map> map1 : INSTANCES_BY_PLAYER.values()) { playerCounter++; - for (Map map2 : map1.values()) { - for (CoreAbility coreAbil : map2.values()) { - String simpleName = coreAbil.getClass().getSimpleName(); + for (final Map map2 : map1.values()) { + for (final CoreAbility coreAbil : map2.values()) { + final String simpleName = coreAbil.getClass().getSimpleName(); if (classCounter.containsKey(simpleName)) { classCounter.put(simpleName, classCounter.get(simpleName) + 1); @@ -901,9 +946,9 @@ public static String getDebugString() { } } - for (Set set : INSTANCES_BY_CLASS.values()) { - for (CoreAbility coreAbil : set) { - String simpleName = coreAbil.getClass().getSimpleName(); + for (final Set set : INSTANCES_BY_CLASS.values()) { + for (final CoreAbility coreAbil : set) { + final String simpleName = coreAbil.getClass().getSimpleName(); if (classCounter.containsKey(simpleName)) { classCounter.put(simpleName, classCounter.get(simpleName) + 1); } else { @@ -914,7 +959,7 @@ public static String getDebugString() { sb.append("Class->UUID's in memory: " + playerCounter + "\n"); sb.append("Abilities in memory:\n"); - for (String className : classCounter.keySet()) { + for (final String className : classCounter.keySet()) { sb.append(className + ": " + classCounter.get(className) + "\n"); } return sb.toString(); @@ -924,4 +969,4 @@ public static double getDefaultCollisionRadius() { return DEFAULT_COLLISION_RADIUS; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/EarthAbility.java b/src/com/projectkorra/projectkorra/ability/EarthAbility.java index bfe555acd..484b9b26a 100644 --- a/src/com/projectkorra/projectkorra/ability/EarthAbility.java +++ b/src/com/projectkorra/projectkorra/ability/EarthAbility.java @@ -25,7 +25,7 @@ import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.earthbending.RaiseEarth; import com.projectkorra.projectkorra.earthbending.lava.LavaFlow; -import com.projectkorra.projectkorra.earthbending.passive.EarthPassive; +import com.projectkorra.projectkorra.earthbending.passive.DensityShift; import com.projectkorra.projectkorra.firebending.Illumination; import com.projectkorra.projectkorra.util.BlockSource; import com.projectkorra.projectkorra.util.Information; @@ -40,24 +40,24 @@ public abstract class EarthAbility extends ElementalAbility { private static final Map TEMP_AIR_LOCATIONS = new ConcurrentHashMap(); private static final ArrayList PREVENT_PHYSICS = new ArrayList(); - public EarthAbility(Player player) { + public EarthAbility(final Player player) { super(player); } - public int getEarthbendableBlocksLength(Block block, Vector direction, int maxlength) { - Location location = block.getLocation(); + public int getEarthbendableBlocksLength(final Block block, Vector direction, final int maxlength) { + final Location location = block.getLocation(); direction = direction.normalize(); for (int i = 0; i <= maxlength; i++) { - double j = i; - if (!isEarthbendable(location.clone().add(direction.clone().multiply(j)).getBlock())) { + final double j = i; + if (!this.isEarthbendable(location.clone().add(direction.clone().multiply(j)).getBlock())) { return i; } } return maxlength; } - public Block getEarthSourceBlock(double range) { - return getEarthSourceBlock(player, getName(), range); + public Block getEarthSourceBlock(final double range) { + return getEarthSourceBlock(this.player, this.getName(), range); } @Override @@ -65,12 +65,12 @@ public Element getElement() { return Element.EARTH; } - public Block getLavaSourceBlock(double range) { - return getLavaSourceBlock(player, getName(), range); + public Block getLavaSourceBlock(final double range) { + return getLavaSourceBlock(this.player, this.getName(), range); } - public Block getTargetEarthBlock(int range) { - return getTargetEarthBlock(player, range); + public Block getTargetEarthBlock(final int range) { + return getTargetEarthBlock(this.player, range); } @Override @@ -84,67 +84,67 @@ public boolean isIgniteAbility() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { super.handleCollision(collision); if (collision.isRemovingFirst()) { - ParticleData particleData = (ParticleEffect.ParticleData) new ParticleEffect.BlockData(Material.DIRT, (byte) 0); + final ParticleData particleData = new ParticleEffect.BlockData(Material.DIRT, (byte) 0); ParticleEffect.BLOCK_CRACK.display(particleData, 1F, 1F, 1F, 0.1F, 10, collision.getLocationFirst(), 50); } } - public static boolean isEarthbendable(Material material, boolean metal, boolean sand, boolean lava) { + public static boolean isEarthbendable(final Material material, final boolean metal, final boolean sand, final boolean lava) { return isEarth(material) || (metal && isMetal(material)) || (sand && isSand(material)) || (lava && isLava(material)); } - public boolean isEarthbendable(Block block) { - return isEarthbendable(player, getName(), block); + public boolean isEarthbendable(final Block block) { + return isEarthbendable(this.player, this.getName(), block); } - public static boolean isEarthbendable(Player player, Block block) { + public static boolean isEarthbendable(final Player player, final Block block) { return isEarthbendable(player, null, block); } - public boolean isLavabendable(Block block) { - return isLavabendable(player, block); + public boolean isLavabendable(final Block block) { + return isLavabendable(this.player, block); } - public boolean isMetalbendable(Block block) { - return isMetalbendable(block.getType()); + public boolean isMetalbendable(final Block block) { + return this.isMetalbendable(block.getType()); } - public boolean isMetalbendable(Material material) { - return isMetalbendable(player, material); + public boolean isMetalbendable(final Material material) { + return isMetalbendable(this.player, material); } - public boolean isSandbendable(Block block) { - return isSandbendable(block.getType()); + public boolean isSandbendable(final Block block) { + return this.isSandbendable(block.getType()); } - public boolean isSandbendable(Material material) { - return isSandbendable(player, material); + public boolean isSandbendable(final Material material) { + return isSandbendable(this.player, material); } - public void moveEarth(Block block, Vector direction, int chainlength) { - moveEarth(block, direction, chainlength, true); + public void moveEarth(final Block block, final Vector direction, final int chainlength) { + this.moveEarth(block, direction, chainlength, true); } - public boolean moveEarth(Block block, Vector direction, int chainlength, boolean throwplayer) { - if (isEarthbendable(block) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { + public boolean moveEarth(Block block, final Vector direction, final int chainlength, final boolean throwplayer) { + if (this.isEarthbendable(block) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { boolean up = false; boolean down = false; - Vector norm = direction.clone().normalize(); + final Vector norm = direction.clone().normalize(); if (norm.dot(new Vector(0, 1, 0)) == 1) { up = true; } else if (norm.dot(new Vector(0, -1, 0)) == 1) { down = true; } - Vector negnorm = norm.clone().multiply(-1); - Location location = block.getLocation(); - ArrayList blocks = new ArrayList(); + final Vector negnorm = norm.clone().multiply(-1); + final Location location = block.getLocation(); + final ArrayList blocks = new ArrayList(); for (double j = -2; j <= chainlength; j++) { - Block checkblock = location.clone().add(negnorm.clone().multiply(j)).getBlock(); + final Block checkblock = location.clone().add(negnorm.clone().multiply(j)).getBlock(); if (!PREVENT_PHYSICS.contains(checkblock)) { blocks.add(checkblock); PREVENT_PHYSICS.add(checkblock); @@ -152,8 +152,8 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean } Block affectedblock = location.clone().add(norm).getBlock(); - if (EarthPassive.isPassiveSand(block)) { - EarthPassive.revertSand(block); + if (DensityShift.isPassiveSand(block)) { + DensityShift.revertSand(block); } if (Illumination.isIlluminationTorch(affectedblock) && TempBlock.isTempBlock(affectedblock)) { TempBlock.get(affectedblock).revertBlock(); @@ -161,11 +161,11 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean if (affectedblock == null) { return false; - } else if (isTransparent(affectedblock)) { + } else if (this.isTransparent(affectedblock)) { if (throwplayer) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(affectedblock.getLocation(), 1.75)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(affectedblock.getLocation(), 1.75)) { if (entity instanceof LivingEntity) { - LivingEntity lentity = (LivingEntity) entity; + final LivingEntity lentity = (LivingEntity) entity; if (lentity.getEyeLocation().getBlockX() == affectedblock.getX() && lentity.getEyeLocation().getBlockZ() == affectedblock.getZ()) { if (!(entity instanceof FallingBlock)) { entity.setVelocity(norm.clone().multiply(.75)); @@ -181,7 +181,7 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean } } if (up) { - Block topblock = affectedblock.getRelative(BlockFace.UP); + final Block topblock = affectedblock.getRelative(BlockFace.UP); if (topblock.getType() != Material.AIR) { GeneralMethods.breakBlock(affectedblock); } else if (!affectedblock.isLiquid() && affectedblock.getType() != Material.AIR) { @@ -196,19 +196,19 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean for (double i = 1; i < chainlength; i++) { affectedblock = location.clone().add(negnorm.getX() * i, negnorm.getY() * i, negnorm.getZ() * i).getBlock(); - if (!isEarthbendable(affectedblock)) { + if (!this.isEarthbendable(affectedblock)) { if (down) { - if (isTransparent(affectedblock) && !affectedblock.isLiquid() && affectedblock.getType() != Material.AIR) { + if (this.isTransparent(affectedblock) && !affectedblock.isLiquid() && affectedblock.getType() != Material.AIR) { moveEarthBlock(affectedblock, block); } } break; } - if (EarthPassive.isPassiveSand(affectedblock)) { - EarthPassive.revertSand(affectedblock); + if (DensityShift.isPassiveSand(affectedblock)) { + DensityShift.revertSand(affectedblock); } if (block == null) { - for (Block checkblock : blocks) { + for (final Block checkblock : blocks) { PREVENT_PHYSICS.remove(checkblock); } return false; @@ -217,22 +217,22 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean block = affectedblock; } - int i = chainlength; + final int i = chainlength; affectedblock = location.clone().add(negnorm.getX() * i, negnorm.getY() * i, negnorm.getZ() * i).getBlock(); - if (!isEarthbendable(affectedblock)) { + if (!this.isEarthbendable(affectedblock)) { if (down) { - if (isTransparent(affectedblock) && !affectedblock.isLiquid()) { + if (this.isTransparent(affectedblock) && !affectedblock.isLiquid()) { moveEarthBlock(affectedblock, block); } } } } else { - for (Block checkblock : blocks) { + for (final Block checkblock : blocks) { PREVENT_PHYSICS.remove(checkblock); } return false; } - for (Block checkblock : blocks) { + for (final Block checkblock : blocks) { PREVENT_PHYSICS.remove(checkblock); } return true; @@ -240,21 +240,20 @@ public boolean moveEarth(Block block, Vector direction, int chainlength, boolean return false; } - public void moveEarth(Location location, Vector direction, int chainlength) { - moveEarth(location, direction, chainlength, true); + public void moveEarth(final Location location, final Vector direction, final int chainlength) { + this.moveEarth(location, direction, chainlength, true); } - public void moveEarth(Location location, Vector direction, int chainlength, boolean throwplayer) { - moveEarth(location.getBlock(), direction, chainlength, throwplayer); + public void moveEarth(final Location location, final Vector direction, final int chainlength, final boolean throwplayer) { + this.moveEarth(location.getBlock(), direction, chainlength, throwplayer); } /** * Creates a temporary air block. - * + * * @param block The block to use as a base */ - @SuppressWarnings("deprecation") - public static void addTempAirBlock(Block block) { + public static void addTempAirBlock(final Block block) { Information info; if (MOVED_EARTH.containsKey(block)) { @@ -273,9 +272,10 @@ public static void addTempAirBlock(Block block) { TEMP_AIR_LOCATIONS.put(info.getID(), info); } - public static void displaySandParticle(Location loc, float xOffset, float yOffset, float zOffset, float amount, float speed, boolean red) { - if (amount <= 0) + public static void displaySandParticle(final Location loc, final float xOffset, final float yOffset, final float zOffset, final float amount, final float speed, final boolean red) { + if (amount <= 0) { return; + } for (int x = 0; x < amount; x++) { if (!red) { @@ -294,14 +294,13 @@ public static void displaySandParticle(Location loc, float xOffset, float yOffse * use BlockSource.getEarthSourceBlock() instead of this method. Dynamic * source selection saves the user's previous source for future use. * {@link BlockSource#getEarthSourceBlock(Player, double, com.projectkorra.projectkorra.util.ClickType)} - * + * * @param range the maximum block selection range. * @return a valid Earth source block, or null if one could not be found. */ - @SuppressWarnings("deprecation") - public static Block getEarthSourceBlock(Player player, String abilityName, double range) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - Block testBlock = player.getTargetBlock(getTransparentMaterialSet(), (int) range); + public static Block getEarthSourceBlock(final Player player, final String abilityName, final double range) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Block testBlock = player.getTargetBlock(getTransparentMaterialSet(), (int) range); if (bPlayer == null) { return null; } else if (isEarthbendable(testBlock.getType(), true, true, true)) { @@ -310,11 +309,11 @@ public static Block getEarthSourceBlock(Player player, String abilityName, doubl return null; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(player, abilityName, location)) { continue; } else if (isEarthbendable(player, block)) { @@ -324,7 +323,7 @@ public static Block getEarthSourceBlock(Player player, String abilityName, doubl return null; } - public static Block getLavaSourceBlock(Player player, double range) { + public static Block getLavaSourceBlock(final Player player, final double range) { return getLavaSourceBlock(player, null, range); } @@ -333,24 +332,23 @@ public static Block getLavaSourceBlock(Player player, double range) { * use BlockSource.getLavaSourceBlock() instead of this method. Dynamic * source selection saves the user's previous source for future use. * {@link BlockSource#getLavaSourceBlock(Player, double, com.projectkorra.projectkorra.util.ClickType)} - * + * * @param range the maximum block selection range. * @return a valid Lava source block, or null if one could not be found. */ - @SuppressWarnings("deprecation") - public static Block getLavaSourceBlock(Player player, String abilityName, double range) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + public static Block getLavaSourceBlock(final Player player, final String abilityName, final double range) { + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(player, abilityName, location)) { continue; } if (isLavabendable(player, block)) { if (TempBlock.isTempBlock(block)) { - TempBlock tb = TempBlock.get(block); - byte full = 0x0; + final TempBlock tb = TempBlock.get(block); + final byte full = 0x0; if (tb.getState().getRawData() != full && !isLava(tb.getState().getType())) { continue; } @@ -361,7 +359,7 @@ public static Block getLavaSourceBlock(Player player, String abilityName, double return null; } - public static double getMetalAugment(double value) { + public static double getMetalAugment(final double value) { return value * getConfig().getDouble("Properties.Earth.MetalPowerFactor"); } @@ -371,24 +369,24 @@ public static Map getMovedEarth() { /** * Attempts to find the closest earth block near a given location. - * + * * @param loc the initial location to search from. * @param radius the maximum radius to search for the earth block. * @param maxVertical the maximum block height difference between the * starting location and the earth bendable block. * @return an earth bendable block, or null. */ - public static Block getNearbyEarthBlock(Location loc, double radius, int maxVertical) { + public static Block getNearbyEarthBlock(final Location loc, final double radius, final int maxVertical) { if (loc == null) { return null; } - int rotation = 30; + final int rotation = 30; for (int i = 0; i < radius; i++) { Vector tracer = new Vector(i, 1, 0); for (int deg = 0; deg < 360; deg += rotation) { - Location searchLoc = loc.clone().add(tracer); - Block block = GeneralMethods.getTopBlock(searchLoc, maxVertical); + final Location searchLoc = loc.clone().add(tracer); + final Block block = GeneralMethods.getTopBlock(searchLoc, maxVertical); if (block != null && isEarthbendable(block.getType(), true, true, true)) { return block; @@ -411,8 +409,7 @@ public static ChatColor getSubChatColor() { return ChatColor.valueOf(ConfigManager.getConfig().getString("Properties.Chat.Colors.EarthSub")); } - @SuppressWarnings("deprecation") - public static Block getTargetEarthBlock(Player player, int range) { + public static Block getTargetEarthBlock(final Player player, final int range) { return player.getTargetBlock(getTransparentMaterialSet(), range); } @@ -420,8 +417,8 @@ public static Map getTempAirLocations() { return TEMP_AIR_LOCATIONS; } - public static boolean isEarthbendable(Player player, String abilityName, Block block) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isEarthbendable(final Player player, final String abilityName, final Block block) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null || !isEarthbendable(block.getType(), true, true, true) || PREVENT_EARTHBENDING.contains(block) || GeneralMethods.isRegionProtectedFromBuild(player, abilityName, block.getLocation())) { return false; } else if (isMetal(block) && !bPlayer.canMetalbend()) { @@ -438,11 +435,10 @@ public static boolean isEarthRevertOn() { return getConfig().getBoolean("Properties.Earth.RevertEarthbending"); } - @SuppressWarnings("deprecation") - public static boolean isLavabendable(Player player, Block block) { - byte full = 0x0; + public static boolean isLavabendable(final Player player, final Block block) { + final byte full = 0x0; if (TempBlock.isTempBlock(block)) { - TempBlock tblock = TempBlock.instances.get(block); + final TempBlock tblock = TempBlock.instances.get(block); if (tblock == null || !LavaFlow.getTempLavaBlocks().values().contains(tblock)) { return false; } @@ -453,18 +449,17 @@ public static boolean isLavabendable(Player player, Block block) { return false; } - public static boolean isMetalbendable(Player player, Material material) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isMetalbendable(final Player player, final Material material) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); return bPlayer == null ? null : isMetal(material) && bPlayer.canMetalbend(); } - public static boolean isSandbendable(Player player, Material material) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isSandbendable(final Player player, final Material material) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); return bPlayer == null ? null : isSand(material) && bPlayer.canSandbend(); } - @SuppressWarnings("deprecation") - public static void moveEarthBlock(Block source, Block target) { + public static void moveEarthBlock(final Block source, final Block target) { Information info; if (MOVED_EARTH.containsKey(source)) { @@ -491,89 +486,98 @@ public static void moveEarthBlock(Block source, Block target) { target.setType(info.getState().getType()); target.setData(info.getState().getRawData()); } - + source.setType(Material.AIR); } - public static void playEarthbendingSound(Location loc) { + public static void playEarthbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Earth.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Earth.EarthSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Earth.EarthSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Earth.EarthSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Earth.EarthSound.Pitch"); + Sound sound = Sound.ENTITY_GHAST_SHOOT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Earth.EarthSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Earth.EarthSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playMetalbendingSound(Location loc) { + public static void playMetalbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Earth.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Earth.MetalSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Earth.MetalSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Earth.MetalSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Earth.MetalSound.Pitch"); + Sound sound = Sound.ENTITY_IRONGOLEM_HURT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Earth.MetalSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Earth.MetalSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playSandbendingSound(Location loc) { + public static void playSandbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Earth.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Earth.SandSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Earth.SandSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Earth.SandSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Earth.SandSound.Pitch"); + Sound sound = Sound.BLOCK_SAND_BREAK; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Earth.SandSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Earth.SandSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playLavabendingSound(Location loc) { + + public static void playLavabendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Earth.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Earth.LavaSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Earth.LavaSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Earth.LavaSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Earth.LavaSound.Pitch"); + Sound sound = Sound.BLOCK_LAVA_AMBIENT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Earth.LavaSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Earth.LavaSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } public static void removeAllEarthbendedBlocks() { - for (Block block : MOVED_EARTH.keySet()) { + for (final Block block : MOVED_EARTH.keySet()) { revertBlock(block); } - for (Integer i : TEMP_AIR_LOCATIONS.keySet()) { + for (final Integer i : TEMP_AIR_LOCATIONS.keySet()) { revertAirBlock(i, true); } } - public static void removeRevertIndex(Block block) { + public static void removeRevertIndex(final Block block) { if (MOVED_EARTH.containsKey(block)) { - Information info = MOVED_EARTH.get(block); + final Information info = MOVED_EARTH.get(block); if (block.getType() == Material.SANDSTONE && info.getType() == Material.SAND) { block.setType(Material.SAND); } @@ -585,17 +589,17 @@ public static void removeRevertIndex(Block block) { } } - public static void revertAirBlock(int i) { + public static void revertAirBlock(final int i) { revertAirBlock(i, false); } - public static void revertAirBlock(int i, boolean force) { + public static void revertAirBlock(final int i, final boolean force) { if (!TEMP_AIR_LOCATIONS.containsKey(i)) { return; } - Information info = TEMP_AIR_LOCATIONS.get(i); - Block block = info.getState().getBlock(); + final Information info = TEMP_AIR_LOCATIONS.get(i); + final Block block = info.getState().getBlock(); if (block.getType() != Material.AIR && !block.isLiquid()) { if (force || !MOVED_EARTH.containsKey(block)) { @@ -610,16 +614,15 @@ public static void revertAirBlock(int i, boolean force) { } } - @SuppressWarnings("deprecation") - public static boolean revertBlock(Block block) { - byte full = 0x0; + public static boolean revertBlock(final Block block) { + final byte full = 0x0; if (!isEarthRevertOn()) { MOVED_EARTH.remove(block); return false; } if (MOVED_EARTH.containsKey(block)) { - Information info = MOVED_EARTH.get(block); - Block sourceblock = info.getState().getBlock(); + final Information info = MOVED_EARTH.get(block); + final Block sourceblock = info.getState().getBlock(); if (info.getState().getType() == Material.AIR) { MOVED_EARTH.remove(block); @@ -647,8 +650,7 @@ public static boolean revertBlock(Block block) { if (sourceblock.getType() == Material.AIR || sourceblock.isLiquid()) { info.getState().update(true); } else { - //GeneralMethods.dropItems(block, - // GeneralMethods.getDrops(block, info.getState().getType(), info.getState().getRawData(), DIAMOND_PICKAXE)); + } if (GeneralMethods.isAdjacentToThreeOrMoreSources(block)) { @@ -670,10 +672,10 @@ public static boolean revertBlock(Block block) { } public static void stopBending() { - EarthPassive.removeAll(); + DensityShift.removeAll(); if (isEarthRevertOn()) { removeAllEarthbendedBlocks(); } } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/ElementalAbility.java b/src/com/projectkorra/projectkorra/ability/ElementalAbility.java index b896aa766..165662330 100644 --- a/src/com/projectkorra/projectkorra/ability/ElementalAbility.java +++ b/src/com/projectkorra/projectkorra/ability/ElementalAbility.java @@ -2,6 +2,7 @@ import java.util.Arrays; import java.util.HashSet; +import java.util.List; import org.bukkit.Material; import org.bukkit.World; @@ -25,12 +26,16 @@ public abstract class ElementalAbility extends CoreAbility { private static final PotionEffectType[] NEUTRAL_EFFECTS = { PotionEffectType.INVISIBILITY }; private static final PotionEffectType[] NEGATIVE_EFFECTS = { PotionEffectType.POISON, PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER }; - public ElementalAbility(Player player) { + public ElementalAbility(final Player player) { super(player); } - public boolean isTransparent(Block block) { - return isTransparent(player, getName(), block); + public boolean isTransparent(final Block block) { + return isTransparent(this.player, this.getName(), block); + } + + public List getEarthbendableBlocks() { + return getConfig().getStringList("Properties.Earth.EarthBlocks"); } public static Material[] getTransparentMaterials() { @@ -38,205 +43,209 @@ public static Material[] getTransparentMaterials() { } public static HashSet getTransparentMaterialSet() { - HashSet set = new HashSet(); - for (Material material : getTransparentMaterials()) { + final HashSet set = new HashSet(); + for (final Material material : getTransparentMaterials()) { set.add(material); } - + return set; } - public static boolean isDay(World world) { - long time = world.getTime(); + public static boolean isDay(final World world) { + final long time = world.getTime(); if (world.getEnvironment() == Environment.NETHER || world.getEnvironment() == Environment.THE_END) { return true; } - + if (time >= 23500 || time <= 12500) { return true; } - + return false; } - public static boolean isEarth(Block block) { + public static boolean isEarth(final Block block) { return block != null ? isEarth(block.getType()) : false; } - public static boolean isEarth(Material material) { + public static boolean isEarth(final Material material) { return getConfig().getStringList("Properties.Earth.EarthBlocks").contains(material.toString()); } - public static boolean isFullMoon(World world) { + public static boolean isFullMoon(final World world) { if (GeneralMethods.hasRPG()) { - return EventManager.marker.get(world).equalsIgnoreCase("FullMoon"); + final String event = EventManager.marker.get(world); + return event != null && event.equalsIgnoreCase("FullMoon"); } else { - long days = world.getFullTime() / 24000; - long phase = days % 8; - + final long days = world.getFullTime() / 24000; + final long phase = days % 8; + if (phase == 0) { return true; } - + return false; } } - public static boolean isIce(Block block) { + public static boolean isIce(final Block block) { return block != null ? isIce(block.getType()) : false; } - public static boolean isIce(Material material) { + public static boolean isIce(final Material material) { return getConfig().getStringList("Properties.Water.IceBlocks").contains(material.toString()); } - public static boolean isLava(Block block) { + public static boolean isLava(final Block block) { return block != null ? isLava(block.getType()) : false; } - public static boolean isLava(Material material) { + public static boolean isLava(final Material material) { return material == Material.LAVA || material == Material.STATIONARY_LAVA; } - public static boolean isSnow(Block block) { + public static boolean isSnow(final Block block) { return block != null ? isSnow(block.getType()) : false; } - public static boolean isSnow(Material material) { + public static boolean isSnow(final Material material) { return getConfig().getStringList("Properties.Water.SnowBlocks").contains(material.toString()); } - public static boolean isLunarEclipse(World world) { + public static boolean isLunarEclipse(final World world) { if (world == null || !GeneralMethods.hasRPG()) { return false; } - - return EventManager.marker.get(world).equalsIgnoreCase("LunarEclipse"); + + final String event = EventManager.marker.get(world); + return event != null && event.equalsIgnoreCase("LunarEclipse"); } - public static boolean isSolarEclipse(World world) { + public static boolean isSolarEclipse(final World world) { if (world == null || !GeneralMethods.hasRPG() || !EventManager.marker.containsKey(world)) { return false; } - - return EventManager.marker.get(world).equalsIgnoreCase("SolarEclipse"); + + final String event = EventManager.marker.get(world); + return event != null && event.equalsIgnoreCase("SolarEclipse"); } - public static boolean isMeltable(Block block) { + public static boolean isMeltable(final Block block) { if (block.getType() == Material.ICE || block.getType() == Material.SNOW) { return true; } - + return false; } - public static boolean isMetal(Block block) { + public static boolean isMetal(final Block block) { return block != null ? isMetal(block.getType()) : false; } - public static boolean isMetal(Material material) { + public static boolean isMetal(final Material material) { return getConfig().getStringList("Properties.Earth.MetalBlocks").contains(material.toString()); } - public static boolean isMetalBlock(Block block) { + public static boolean isMetalBlock(final Block block) { if (block.getType() == Material.GOLD_BLOCK || block.getType() == Material.IRON_BLOCK || block.getType() == Material.IRON_ORE || block.getType() == Material.GOLD_ORE || block.getType() == Material.QUARTZ_BLOCK || block.getType() == Material.QUARTZ_ORE) { return true; } - + return false; } - public static boolean isNegativeEffect(PotionEffectType effect) { - for (PotionEffectType effect2 : NEGATIVE_EFFECTS) { + public static boolean isNegativeEffect(final PotionEffectType effect) { + for (final PotionEffectType effect2 : NEGATIVE_EFFECTS) { if (effect2.equals(effect)) { return true; } } - + return false; } - public static boolean isNeutralEffect(PotionEffectType effect) { - for (PotionEffectType effect2 : NEUTRAL_EFFECTS) { + public static boolean isNeutralEffect(final PotionEffectType effect) { + for (final PotionEffectType effect2 : NEUTRAL_EFFECTS) { if (effect2.equals(effect)) { return true; } } - + return false; } - public static boolean isNight(World world) { + public static boolean isNight(final World world) { if (world.getEnvironment() == Environment.NETHER || world.getEnvironment() == Environment.THE_END) { return false; } - long time = world.getTime(); - + final long time = world.getTime(); + if (time >= 12950 && time <= 23050) { return true; } - + return false; } - public static boolean isPlant(Block block) { + public static boolean isPlant(final Block block) { return block != null ? isPlant(block.getType()) : false; } - public static boolean isPlant(Material material) { + public static boolean isPlant(final Material material) { return getConfig().getStringList("Properties.Water.PlantBlocks").contains(material.toString()); } - public static boolean isPositiveEffect(PotionEffectType effect) { - for (PotionEffectType effect2 : POSITIVE_EFFECTS) { + public static boolean isPositiveEffect(final PotionEffectType effect) { + for (final PotionEffectType effect2 : POSITIVE_EFFECTS) { if (effect2.equals(effect)) { return true; } } - + return false; } - public static boolean isSand(Block block) { + public static boolean isSand(final Block block) { return block != null ? isSand(block.getType()) : false; } - public static boolean isSand(Material material) { + public static boolean isSand(final Material material) { return getConfig().getStringList("Properties.Earth.SandBlocks").contains(material.toString()); } - public static boolean isSozinsComet(World world) { + public static boolean isSozinsComet(final World world) { if (world == null || !GeneralMethods.hasRPG()) { return false; } - - return EventManager.marker.get(world).equalsIgnoreCase("SozinsComet"); + + final String event = EventManager.marker.get(world); + return event != null && event.equalsIgnoreCase("SozinsComet"); } - public static boolean isTransparent(Player player, Block block) { + public static boolean isTransparent(final Player player, final Block block) { return isTransparent(player, null, block); } - public static boolean isTransparent(Player player, String abilityName, Block block) { + public static boolean isTransparent(final Player player, final String abilityName, final Block block) { return Arrays.asList(getTransparentMaterials()).contains(block.getType()) && !GeneralMethods.isRegionProtectedFromBuild(player, abilityName, block.getLocation()); } - public static boolean isUndead(Entity entity) { + public static boolean isUndead(final Entity entity) { if (entity == null) { return false; } else if (entity.getType() == EntityType.ZOMBIE || entity.getType() == EntityType.BLAZE || entity.getType() == EntityType.GIANT || entity.getType() == EntityType.IRON_GOLEM || entity.getType() == EntityType.MAGMA_CUBE || entity.getType() == EntityType.PIG_ZOMBIE || entity.getType() == EntityType.SKELETON || entity.getType() == EntityType.SLIME || entity.getType() == EntityType.SNOWMAN || entity.getType() == EntityType.ZOMBIE) { return true; } - + return false; } - public static boolean isWater(Block block) { + public static boolean isWater(final Block block) { return block != null ? isWater(block.getType()) : null; } - public static boolean isWater(Material material) { + public static boolean isWater(final Material material) { return material == Material.WATER || material == Material.STATIONARY_WATER; } diff --git a/src/com/projectkorra/projectkorra/ability/FireAbility.java b/src/com/projectkorra/projectkorra/ability/FireAbility.java index 315270924..3ce6708c3 100644 --- a/src/com/projectkorra/projectkorra/ability/FireAbility.java +++ b/src/com/projectkorra/projectkorra/ability/FireAbility.java @@ -33,7 +33,7 @@ public abstract class FireAbility extends ElementalAbility { private static final Map TEMP_FIRE = new ConcurrentHashMap(); private static final Material[] IGNITABLE_MATERIALS = { Material.BEDROCK, Material.BOOKSHELF, Material.BRICK, Material.CLAY, Material.CLAY_BRICK, Material.COAL_ORE, Material.COBBLESTONE, Material.DIAMOND_ORE, Material.DIAMOND_BLOCK, Material.DIRT, Material.ENDER_STONE, Material.GLOWING_REDSTONE_ORE, Material.GOLD_BLOCK, Material.GRAVEL, Material.GRASS, Material.HUGE_MUSHROOM_1, Material.HUGE_MUSHROOM_2, Material.LAPIS_BLOCK, Material.LAPIS_ORE, Material.LOG, Material.MOSSY_COBBLESTONE, Material.MYCEL, Material.NETHER_BRICK, Material.NETHERRACK, Material.OBSIDIAN, Material.REDSTONE_ORE, Material.SAND, Material.SANDSTONE, Material.SMOOTH_BRICK, Material.STONE, Material.SOUL_SAND, Material.WOOD, Material.WOOL, Material.LEAVES, Material.LEAVES_2, Material.MELON_BLOCK, Material.PUMPKIN, Material.JACK_O_LANTERN, Material.NOTE_BLOCK, Material.GLOWSTONE, Material.IRON_BLOCK, Material.DISPENSER, Material.SPONGE, Material.IRON_ORE, Material.GOLD_ORE, Material.COAL_BLOCK, Material.WORKBENCH, Material.HAY_BLOCK, Material.REDSTONE_LAMP_OFF, Material.REDSTONE_LAMP_ON, Material.EMERALD_ORE, Material.EMERALD_BLOCK, Material.REDSTONE_BLOCK, Material.QUARTZ_BLOCK, Material.QUARTZ_ORE, Material.STAINED_CLAY, Material.HARD_CLAY }; - public FireAbility(Player player) { + public FireAbility(final Player player) { super(player); } @@ -53,16 +53,16 @@ public Element getElement() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { super.handleCollision(collision); if (collision.isRemovingFirst()) { - ParticleData particleData = (ParticleEffect.ParticleData) new ParticleEffect.BlockData(Material.FIRE, (byte) 0); + final ParticleData particleData = new ParticleEffect.BlockData(Material.FIRE, (byte) 0); ParticleEffect.BLOCK_CRACK.display(particleData, 1F, 1F, 1F, 0.1F, 10, collision.getLocationFirst(), 50); } } - public double getDayFactor(double value) { - return player != null ? getDayFactor(value, player.getWorld()) : 1; + public double getDayFactor(final double value) { + return this.player != null ? getDayFactor(value, this.player.getWorld()) : 1; } /** @@ -77,13 +77,13 @@ public static boolean canFireGrief() { * Creates a fire block meant to replace other blocks but reverts when the * fire dissipates or is destroyed. */ - public static void createTempFire(Location loc) { + public static void createTempFire(final Location loc) { if (loc.getBlock().getType() == Material.AIR) { loc.getBlock().setType(Material.FIRE); return; } Information info = new Information(); - long time = getConfig().getLong("Properties.Fire.RevertTicks") + (long) ((new Random()).nextDouble() * getConfig().getLong("Properties.Fire.RevertTicks")); + final long time = getConfig().getLong("Properties.Fire.RevertTicks") + (long) ((new Random()).nextDouble() * getConfig().getLong("Properties.Fire.RevertTicks")); if (TEMP_FIRE.containsKey(loc)) { info = TEMP_FIRE.get(loc); } else { @@ -103,7 +103,7 @@ public static double getDayFactor() { /** * Gets the firebending dayfactor from the config multiplied by a specific * value if it is day. - * + * * @param value The value * @param world The world to pass into {@link #isDay(World)} * @return value DayFactor multiplied by specified value when @@ -111,7 +111,7 @@ public static double getDayFactor() { * else
* value The specified value in the parameters */ - public static double getDayFactor(double value, World world) { + public static double getDayFactor(final double value, final World world) { if (isDay(world)) { if (GeneralMethods.hasRPG()) { if (isSozinsComet(world)) { @@ -132,11 +132,11 @@ public static ChatColor getSubChatColor() { return ChatColor.valueOf(ConfigManager.getConfig().getString("Properties.Chat.Colors.FireSub")); } - public static boolean isIgnitable(Block block) { + public static boolean isIgnitable(final Block block) { return block != null ? isIgnitable(block.getType()) : false; } - public static boolean isIgnitable(Material material) { + public static boolean isIgnitable(final Material material) { return Arrays.asList(IGNITABLE_MATERIALS).contains(material); } @@ -145,89 +145,95 @@ public static boolean isIgnitable(Material material) { * {@link Collision} for the new system. *

* Checks whether a location is within a FireShield. - * + * * @param loc The location to check * @return true If the location is inside a FireShield. */ @Deprecated - public static boolean isWithinFireShield(Location loc) { - List list = new ArrayList(); + public static boolean isWithinFireShield(final Location loc) { + final List list = new ArrayList(); list.add("FireShield"); return GeneralMethods.blockAbilities(null, list, loc, 0); } - public static void playCombustionSound(Location loc) { + public static void playCombustionSound(final Location loc) { if (getConfig().getBoolean("Properties.Fire.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Fire.CombustionSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Fire.CombustionSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Fire.CombustionSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Fire.CombustionSound.Pitch"); + Sound sound = Sound.ENTITY_FIREWORK_BLAST; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Fire.CombustionSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Fire.CombustionSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playFirebendingParticles(Location loc, int amount, float xOffset, float yOffset, float zOffset) { + public static void playFirebendingParticles(final Location loc, final int amount, final float xOffset, final float yOffset, final float zOffset) { ParticleEffect.FLAME.display(loc, xOffset, yOffset, zOffset, 0, amount); } - public static void playFirebendingSound(Location loc) { + public static void playFirebendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Fire.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Fire.FireSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Fire.FireSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Fire.FireSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Fire.FireSound.Pitch"); + Sound sound = Sound.BLOCK_FIRE_AMBIENT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Fire.FireSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Fire.FireSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playLightningbendingParticle(Location loc) { + public static void playLightningbendingParticle(final Location loc) { playLightningbendingParticle(loc, (float) Math.random(), (float) Math.random(), (float) Math.random()); } - public static void playLightningbendingParticle(Location loc, float xOffset, float yOffset, float zOffset) { + public static void playLightningbendingParticle(final Location loc, final float xOffset, final float yOffset, final float zOffset) { loc.setX(loc.getX() + Math.random() * (xOffset / 2 - -(xOffset / 2))); loc.setY(loc.getY() + Math.random() * (yOffset / 2 - -(yOffset / 2))); loc.setZ(loc.getZ() + Math.random() * (zOffset / 2 - -(zOffset / 2))); GeneralMethods.displayColoredParticle(loc, "#01E1FF"); } - - public static void playLightningbendingSound(Location loc) { + + public static void playLightningbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Fire.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Fire.LightningSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Fire.LightningSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Fire.LightningSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Fire.LightningSound.Pitch"); + Sound sound = Sound.ENTITY_CREEPER_HURT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Fire.LightningSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Fire.LightningSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } /** Removes all temp fire that no longer needs to be there */ public static void removeFire() { - Iterator it = TEMP_FIRE.keySet().iterator(); + final Iterator it = TEMP_FIRE.keySet().iterator(); while (it.hasNext()) { - Location loc = it.next(); - Information info = TEMP_FIRE.get(loc); + final Location loc = it.next(); + final Information info = TEMP_FIRE.get(loc); if (info.getLocation().getBlock().getType() != Material.FIRE && info.getLocation().getBlock().getType() != Material.AIR) { revertTempFire(loc); } else if (info.getBlock().getType() == Material.AIR || System.currentTimeMillis() > info.getTime()) { @@ -238,17 +244,17 @@ public static void removeFire() { /** * Revert the temp fire at the location if any is there. - * + * * @param location The Location */ - public static void revertTempFire(Location location) { + public static void revertTempFire(final Location location) { if (!TEMP_FIRE.containsKey(location)) { return; } - Information info = TEMP_FIRE.get(location); + final Information info = TEMP_FIRE.get(location); if (info.getLocation().getBlock().getType() != Material.FIRE && info.getLocation().getBlock().getType() != Material.AIR) { if (info.getState().getType() == Material.RED_ROSE || info.getState().getType() == Material.YELLOW_FLOWER) { - ItemStack itemStack = new ItemStack(info.getState().getData().getItemType(), 1, info.getState().getRawData()); + final ItemStack itemStack = new ItemStack(info.getState().getData().getItemType(), 1, info.getState().getRawData()); info.getState().getBlock().getWorld().dropItemNaturally(info.getLocation(), itemStack); } } else { @@ -260,9 +266,9 @@ public static void revertTempFire(Location location) { public static void stopBending() { BlazeArc.removeAllCleanup(); - for (Location loc : TEMP_FIRE.keySet()) { + for (final Location loc : TEMP_FIRE.keySet()) { revertTempFire(loc); } } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/FlightAbility.java b/src/com/projectkorra/projectkorra/ability/FlightAbility.java index 4199fdfcb..23efab2e5 100644 --- a/src/com/projectkorra/projectkorra/ability/FlightAbility.java +++ b/src/com/projectkorra/projectkorra/ability/FlightAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class FlightAbility extends AirAbility implements SubAbility { - public FlightAbility(Player player) { + public FlightAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/HealingAbility.java b/src/com/projectkorra/projectkorra/ability/HealingAbility.java index db4d352f1..533d8ed71 100644 --- a/src/com/projectkorra/projectkorra/ability/HealingAbility.java +++ b/src/com/projectkorra/projectkorra/ability/HealingAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class HealingAbility extends WaterAbility implements SubAbility { - public HealingAbility(Player player) { + public HealingAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/IceAbility.java b/src/com/projectkorra/projectkorra/ability/IceAbility.java index ee7654f34..71c796fd7 100644 --- a/src/com/projectkorra/projectkorra/ability/IceAbility.java +++ b/src/com/projectkorra/projectkorra/ability/IceAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class IceAbility extends WaterAbility implements SubAbility { - public IceAbility(Player player) { + public IceAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/LavaAbility.java b/src/com/projectkorra/projectkorra/ability/LavaAbility.java index 2e6e1036b..b1fbf7ea3 100644 --- a/src/com/projectkorra/projectkorra/ability/LavaAbility.java +++ b/src/com/projectkorra/projectkorra/ability/LavaAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class LavaAbility extends EarthAbility implements SubAbility { - public LavaAbility(Player player) { + public LavaAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/LightningAbility.java b/src/com/projectkorra/projectkorra/ability/LightningAbility.java index cfc70f584..2f7df496e 100644 --- a/src/com/projectkorra/projectkorra/ability/LightningAbility.java +++ b/src/com/projectkorra/projectkorra/ability/LightningAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class LightningAbility extends FireAbility implements SubAbility { - public LightningAbility(Player player) { + public LightningAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/MetalAbility.java b/src/com/projectkorra/projectkorra/ability/MetalAbility.java index 202dabe69..eb1759197 100644 --- a/src/com/projectkorra/projectkorra/ability/MetalAbility.java +++ b/src/com/projectkorra/projectkorra/ability/MetalAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class MetalAbility extends EarthAbility implements SubAbility { - public MetalAbility(Player player) { + public MetalAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/MultiAbility.java b/src/com/projectkorra/projectkorra/ability/MultiAbility.java index 0099cba77..a73e6bf2b 100644 --- a/src/com/projectkorra/projectkorra/ability/MultiAbility.java +++ b/src/com/projectkorra/projectkorra/ability/MultiAbility.java @@ -1,9 +1,9 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.ability.util.MultiAbilityManager.MultiAbilityInfoSub; - import java.util.ArrayList; +import com.projectkorra.projectkorra.ability.util.MultiAbilityManager.MultiAbilityInfoSub; + public interface MultiAbility { /** @@ -11,7 +11,7 @@ public interface MultiAbility { *

* {@code new * MultiAbilitySub("SubAbility", Element.LIGHTNING);} - * + * * @return a list of sub MultiAbilities */ public abstract ArrayList getMultiAbilities(); diff --git a/src/com/projectkorra/projectkorra/ability/PassiveAbility.java b/src/com/projectkorra/projectkorra/ability/PassiveAbility.java index 8999de299..93ee299d4 100644 --- a/src/com/projectkorra/projectkorra/ability/PassiveAbility.java +++ b/src/com/projectkorra/projectkorra/ability/PassiveAbility.java @@ -3,10 +3,19 @@ public interface PassiveAbility { /** + * This is a check to see if the passive requires some form of activation, + * such as sneaking, clicking, etc.
+ * If false, the passive should not call start! * - * @return false if the passive does not actually do anything, but so it - * still registers in /b d [element]passive + * @return false if this passive should always be on */ public boolean isInstantiable(); + /** + * This is used if the passive should progress + * + * @return false if progress() shouldn't be called; + */ + public boolean isProgressable(); + } diff --git a/src/com/projectkorra/projectkorra/ability/PlantAbility.java b/src/com/projectkorra/projectkorra/ability/PlantAbility.java index 36b50e2c1..ce283f2ee 100644 --- a/src/com/projectkorra/projectkorra/ability/PlantAbility.java +++ b/src/com/projectkorra/projectkorra/ability/PlantAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class PlantAbility extends WaterAbility implements SubAbility { - public PlantAbility(Player player) { + public PlantAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/SandAbility.java b/src/com/projectkorra/projectkorra/ability/SandAbility.java index e59a9a911..5390f1dad 100644 --- a/src/com/projectkorra/projectkorra/ability/SandAbility.java +++ b/src/com/projectkorra/projectkorra/ability/SandAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class SandAbility extends EarthAbility implements SubAbility { - public SandAbility(Player player) { + public SandAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/SpiritualAbility.java b/src/com/projectkorra/projectkorra/ability/SpiritualAbility.java index 0c31f610d..d30c5f204 100644 --- a/src/com/projectkorra/projectkorra/ability/SpiritualAbility.java +++ b/src/com/projectkorra/projectkorra/ability/SpiritualAbility.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.ability; -import com.projectkorra.projectkorra.Element; - import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.Element; + public abstract class SpiritualAbility extends AirAbility implements SubAbility { - public SpiritualAbility(Player player) { + public SpiritualAbility(final Player player) { super(player); } diff --git a/src/com/projectkorra/projectkorra/ability/SubAbility.java b/src/com/projectkorra/projectkorra/ability/SubAbility.java index e0efb9871..b52cc099a 100644 --- a/src/com/projectkorra/projectkorra/ability/SubAbility.java +++ b/src/com/projectkorra/projectkorra/ability/SubAbility.java @@ -5,7 +5,7 @@ public interface SubAbility { /** * Specifies the Class of this Ability's parent. For example, a * LightningAbility would return FireAbility.class. - * + * * @return the Class of the parent */ public Class getParentAbility(); diff --git a/src/com/projectkorra/projectkorra/ability/WaterAbility.java b/src/com/projectkorra/projectkorra/ability/WaterAbility.java index 9d979879a..6ab180bd4 100644 --- a/src/com/projectkorra/projectkorra/ability/WaterAbility.java +++ b/src/com/projectkorra/projectkorra/ability/WaterAbility.java @@ -29,16 +29,16 @@ public abstract class WaterAbility extends ElementalAbility { - public WaterAbility(Player player) { + public WaterAbility(final Player player) { super(player); } public boolean canAutoSource() { - return getConfig().getBoolean("Abilities." + getElement() + "." + getName() + ".CanAutoSource"); + return getConfig().getBoolean("Abilities." + this.getElement() + "." + this.getName() + ".CanAutoSource"); } public boolean canDynamicSource() { - return getConfig().getBoolean("Abilities." + getElement() + "." + getName() + ".CanDynamicSource"); + return getConfig().getBoolean("Abilities." + this.getElement() + "." + this.getName() + ".CanDynamicSource"); } @Override @@ -46,27 +46,27 @@ public Element getElement() { return Element.WATER; } - public Block getIceSourceBlock(double range) { - return getIceSourceBlock(player, range); + public Block getIceSourceBlock(final double range) { + return getIceSourceBlock(this.player, range); } public double getNightFactor() { - if (getLocation() != null) { - return getNightFactor(getLocation().getWorld()); + if (this.getLocation() != null) { + return getNightFactor(this.getLocation().getWorld()); } - return player != null ? getNightFactor(player.getLocation().getWorld()) : 1; + return this.player != null ? getNightFactor(this.player.getLocation().getWorld()) : 1; } - public double getNightFactor(double value) { - return player != null ? getNightFactor(value, player.getWorld()) : value; + public double getNightFactor(final double value) { + return this.player != null ? getNightFactor(value, this.player.getWorld()) : value; } - public Block getPlantSourceBlock(double range) { - return getPlantSourceBlock(range, false); + public Block getPlantSourceBlock(final double range) { + return this.getPlantSourceBlock(range, false); } - public Block getPlantSourceBlock(double range, boolean onlyLeaves) { - return getPlantSourceBlock(player, range, onlyLeaves); + public Block getPlantSourceBlock(final double range, final boolean onlyLeaves) { + return getPlantSourceBlock(this.player, range, onlyLeaves); } @Override @@ -80,67 +80,67 @@ public boolean isIgniteAbility() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { super.handleCollision(collision); if (collision.isRemovingFirst()) { - ParticleData particleData = (ParticleEffect.ParticleData) new ParticleEffect.BlockData(Material.WATER, (byte) 0); + final ParticleData particleData = new ParticleEffect.BlockData(Material.WATER, (byte) 0); ParticleEffect.BLOCK_CRACK.display(particleData, 1F, 1F, 1F, 0.1F, 10, collision.getLocationFirst(), 50); } } - - public static boolean isBendableWaterTempBlock(Block block) { // Will need to be done for earth as well. + + public static boolean isBendableWaterTempBlock(final Block block) { // TODO: Will need to be done for earth as well. return isBendableWaterTempBlock(TempBlock.get(block)); } - - public static boolean isBendableWaterTempBlock(TempBlock tempBlock) { - return PhaseChange.getFrozenBlocksAsTempBlock().contains(tempBlock) || HeatControl.getMeltedBlocks().contains(tempBlock); + + public static boolean isBendableWaterTempBlock(final TempBlock tempBlock) { + return PhaseChange.getFrozenBlocksAsTempBlock().contains(tempBlock) || HeatControl.getMeltedBlocks().contains(tempBlock) || SurgeWall.SOURCE_BLOCKS.contains(tempBlock); } - public boolean isIcebendable(Block block) { - return isIcebendable(block.getType()); + public boolean isIcebendable(final Block block) { + return this.isIcebendable(block.getType()); } - public boolean isIcebendable(Material material) { - return isIcebendable(player, material); + public boolean isIcebendable(final Material material) { + return this.isIcebendable(this.player, material); } - public boolean isIcebendable(Player player, Material material) { + public boolean isIcebendable(final Player player, final Material material) { return isIcebendable(player, material, false); } - public boolean isPlantbendable(Block block) { - return isPlantbendable(block.getType()); + public boolean isPlantbendable(final Block block) { + return this.isPlantbendable(block.getType()); } - public boolean isPlantbendable(Material material) { - return isPlantbendable(player, material); + public boolean isPlantbendable(final Material material) { + return this.isPlantbendable(this.player, material); } - public boolean isPlantbendable(Player player, Material material) { + public boolean isPlantbendable(final Player player, final Material material) { return isPlantbendable(player, material, false); } - public boolean isWaterbendable(Block block) { - return isWaterbendable(player, block); + public boolean isWaterbendable(final Block block) { + return this.isWaterbendable(this.player, block); } - public boolean isWaterbendable(Player player, Block block) { + public boolean isWaterbendable(final Player player, final Block block) { return isWaterbendable(player, null, block); } - + public boolean allowBreakPlants() { return true; } - public static boolean isWaterbendable(Material material) { + public static boolean isWaterbendable(final Material material) { return isWater(material) || isIce(material) || isPlant(material) || isSnow(material); } - public static Block getIceSourceBlock(Player player, double range) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + public static Block getIceSourceBlock(final Player player, final double range) { + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(player, "IceBlast", location)) { continue; } @@ -154,7 +154,7 @@ public static Block getIceSourceBlock(Player player, double range) { return null; } - public static double getNightFactor(double value, World world) { + public static double getNightFactor(final double value, final World world) { if (isNight(world)) { if (GeneralMethods.hasRPG()) { if (isLunarEclipse(world)) { @@ -176,16 +176,16 @@ public static double getNightFactor(double value, World world) { } } - public static double getNightFactor(World world) { + public static double getNightFactor(final World world) { return getNightFactor(1, world); } - public static Block getPlantSourceBlock(Player player, double range, boolean onlyLeaves) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + public static Block getPlantSourceBlock(final Player player, final double range, final boolean onlyLeaves) { + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(player, "PlantDisc", location)) { continue; } else if (isPlantbendable(player, block.getType(), onlyLeaves)) { @@ -203,19 +203,18 @@ public static Block getPlantSourceBlock(Player player, double range, boolean onl * use BlockSource.getWaterSourceBlock() instead of this method. Dynamic * source selection saves the user's previous source for future use. * {@link BlockSource#getWaterSourceBlock(Player, double)} - * + * * @param player the player that is attempting to Waterbend. * @param range the maximum block selection range. * @param plantbending true if the player can bend plants. * @return a valid Water source block, or null if one could not be found. */ - @SuppressWarnings("deprecation") - public static Block getWaterSourceBlock(Player player, double range, boolean plantbending) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + public static Block getWaterSourceBlock(final Player player, final double range, final boolean plantbending) { + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - Block testBlock = player.getTargetBlock(getTransparentMaterialSet(), range > 3 ? 3 : (int) range); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Block testBlock = player.getTargetBlock(getTransparentMaterialSet(), range > 3 ? 3 : (int) range); if (bPlayer == null) { return null; } else if (isWaterbendable(player, null, testBlock) && (!isPlant(testBlock) || plantbending)) { @@ -223,7 +222,7 @@ public static Block getWaterSourceBlock(Player player, double range, boolean pla } for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if ((!isTransparent(player, block) && !isIce(block) && !isPlant(block) && !isSnow(block)) || GeneralMethods.isRegionProtectedFromBuild(player, "WaterManipulation", location)) { continue; } else if (isWaterbendable(player, null, block) && (!isPlant(block) || plantbending)) { @@ -236,10 +235,10 @@ public static Block getWaterSourceBlock(Player player, double range, boolean pla return null; } - public static boolean isAdjacentToFrozenBlock(Block block) { - BlockFace[] faces = { BlockFace.DOWN, BlockFace.UP, BlockFace.NORTH, BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH }; + public static boolean isAdjacentToFrozenBlock(final Block block) { + final BlockFace[] faces = { BlockFace.DOWN, BlockFace.UP, BlockFace.NORTH, BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH }; boolean adjacent = false; - for (BlockFace face : faces) { + for (final BlockFace face : faces) { if (PhaseChange.getFrozenBlocksAsBlock().contains((block.getRelative(face)))) { adjacent = true; } @@ -247,13 +246,13 @@ public static boolean isAdjacentToFrozenBlock(Block block) { return adjacent; } - public static boolean isIcebendable(Player player, Material material, boolean onlyIce) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isIcebendable(final Player player, final Material material, final boolean onlyIce) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); return bPlayer == null ? null : isIce(material) && bPlayer.canIcebend() && (!onlyIce || material == Material.ICE); } - public static boolean isPlantbendable(Player player, Material material, boolean onlyLeaves) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isPlantbendable(final Player player, final Material material, final boolean onlyLeaves) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (onlyLeaves) { return bPlayer == null ? null : isPlant(material) && bPlayer.canPlantbend() && isLeaves(material); } else { @@ -261,26 +260,25 @@ public static boolean isPlantbendable(Player player, Material material, boolean } } - public static boolean isLeaves(Block block) { + public static boolean isLeaves(final Block block) { return block != null ? isLeaves(block.getType()) : false; } - public static boolean isLeaves(Material material) { + public static boolean isLeaves(final Material material) { return material == Material.LEAVES || material == Material.LEAVES_2; } - public static boolean isSnow(Block block) { + public static boolean isSnow(final Block block) { return block != null ? isSnow(block.getType()) : false; } - public static boolean isSnow(Material material) { + public static boolean isSnow(final Material material) { return material == Material.SNOW || material == Material.SNOW_BLOCK; } - @SuppressWarnings("deprecation") - public static boolean isWaterbendable(Player player, String abilityName, Block block) { - byte full = 0x0; - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean isWaterbendable(final Player player, final String abilityName, final Block block) { + final byte full = 0x0; + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null || !isWaterbendable(block.getType()) || GeneralMethods.isRegionProtectedFromBuild(player, abilityName, block.getLocation())) { return false; } @@ -296,57 +294,63 @@ public static boolean isWaterbendable(Player player, String abilityName, Block b return true; } - public static void playFocusWaterEffect(Block block) { + public static void playFocusWaterEffect(final Block block) { block.getWorld().playEffect(block.getLocation(), Effect.SMOKE, 4, 20); } - public static void playIcebendingSound(Location loc) { + public static void playIcebendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Water.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Water.IceSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Water.IceSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Water.IceSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Water.IceSound.Pitch"); + Sound sound = Sound.ITEM_FLINTANDSTEEL_USE; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Water.IceSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Water.IceSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playPlantbendingSound(Location loc) { + public static void playPlantbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Water.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Water.PlantSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Water.PlantSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Water.PlantSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Water.PlantSound.Pitch"); + Sound sound = Sound.BLOCK_GRASS_STEP; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Water.PlantSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Water.PlantSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } - public static void playWaterbendingSound(Location loc) { + public static void playWaterbendingSound(final Location loc) { if (getConfig().getBoolean("Properties.Water.PlaySound")) { - float volume = (float) getConfig().getDouble("Properties.Water.WaterSound.Volume"); - float pitch = (float) getConfig().getDouble("Properties.Water.WaterSound.Pitch"); - + final float volume = (float) getConfig().getDouble("Properties.Water.WaterSound.Volume"); + final float pitch = (float) getConfig().getDouble("Properties.Water.WaterSound.Pitch"); + Sound sound = Sound.BLOCK_WATER_AMBIENT; - + try { sound = Sound.valueOf(getConfig().getString("Properties.Water.WaterSound.Sound")); - } catch (IllegalArgumentException exception) { + } + catch (final IllegalArgumentException exception) { ProjectKorra.log.warning("Your current value for 'Properties.Water.WaterSound.Sound' is not valid."); - } finally { - loc.getWorld().playSound(loc, sound, volume, pitch); + } + finally { + loc.getWorld().playSound(loc, sound, volume, pitch); } } } @@ -356,13 +360,13 @@ public static void playWaterbendingSound(Location loc) { * {@link Collision} for the new system. *

* Removes all water spouts in a location within a certain radius. - * + * * @param loc The location to use * @param radius The radius around the location to remove spouts in * @param source The player causing the removal */ @Deprecated - public static void removeWaterSpouts(Location loc, double radius, Player source) { + public static void removeWaterSpouts(final Location loc, final double radius, final Player source) { WaterSpout.removeSpouts(loc, radius, source); } @@ -371,12 +375,12 @@ public static void removeWaterSpouts(Location loc, double radius, Player source) * {@link Collision} for the new system. *

* Removes all water spouts in a location with a radius of 1.5. - * + * * @param loc The location to use * @param source The player causing the removal */ @Deprecated - public static void removeWaterSpouts(Location loc, Player source) { + public static void removeWaterSpouts(final Location loc, final Player source) { removeWaterSpouts(loc, 1.5, source); } @@ -385,4 +389,4 @@ public static void stopBending() { SurgeWave.removeAllCleanup(); WaterArms.removeAllCleanup(); } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/util/AbilityLoader.java b/src/com/projectkorra/projectkorra/ability/util/AbilityLoader.java index f76838310..cea08e7d9 100644 --- a/src/com/projectkorra/projectkorra/ability/util/AbilityLoader.java +++ b/src/com/projectkorra/projectkorra/ability/util/AbilityLoader.java @@ -11,106 +11,103 @@ import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; + import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import com.projectkorra.projectkorra.ProjectKorra; - import com.projectkorra.projectkorra.event.AbilityLoadEvent; import sun.reflect.ReflectionFactory; public class AbilityLoader { - + private final Plugin plugin; private ClassLoader loader; private JarFile jar; private String path; - - public AbilityLoader(JavaPlugin plugin, String packageBase) { + + public AbilityLoader(final JavaPlugin plugin, final String packageBase) { this.plugin = plugin; this.loader = plugin.getClass().getClassLoader(); this.path = packageBase.replace('.', '/'); - - if (plugin == null || loader == null) { + + if (plugin == null || this.loader == null) { ProjectKorra.log.severe("Could not find classloader! Will not load abilities from " + packageBase); return; } - - + try { - Enumeration resources = this.loader.getResources(path); - + final Enumeration resources = this.loader.getResources(this.path); + String jarloc = resources.nextElement().getPath(); - jarloc = jarloc.substring(5, jarloc.length() - path.length() - 2); + jarloc = jarloc.substring(5, jarloc.length() - this.path.length() - 2); + + final String s = URLDecoder.decode(jarloc, "UTF-8"); + + this.jar = new JarFile(new File(s)); - String s = URLDecoder.decode(jarloc, "UTF-8"); - - jar = new JarFile(new File(s)); - - } catch (IOException e) { + } + catch (final IOException e) { e.printStackTrace(); } } - + /** * Returns a list of loaded objects of the provided classType. - * + * * @param classType Type of class to load - * @param parentClass Type of class that the class must extend. Use {@code Object.class} - * for classes without a type. + * @param parentClass Type of class that the class must extend. Use + * {@code Object.class} for classes without a type. * @return */ - @SuppressWarnings("unchecked") - public List load(Class classType, Class parentClass) { - ArrayList loadables = new ArrayList<>(); + public List load(final Class classType, final Class parentClass) { + final ArrayList loadables = new ArrayList<>(); - if (loader == null || jar == null) { + if (this.loader == null || this.jar == null) { return loadables; } - - Enumeration entries = jar.entries(); - - while (entries.hasMoreElements()) { - - - JarEntry entry = entries.nextElement(); - if (!entry.getName().endsWith(".class") || entry.getName().contains("$")) { + + final Enumeration entries = this.jar.entries(); + + while (entries.hasMoreElements()) { + + final JarEntry entry = entries.nextElement(); + if (!entry.getName().endsWith(".class") || entry.getName().contains("$")) { continue; } - String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); - if (!className.startsWith(path.replace('/', '.'))) { + final String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); + if (!className.startsWith(this.path.replace('/', '.'))) { continue; } - - + Class clazz = null; try { - clazz = Class.forName(className, true, loader); - + clazz = Class.forName(className, true, this.loader); + if (!classType.isAssignableFrom(clazz) || clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { continue; - } - - ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); - Constructor objDef = parentClass.getDeclaredConstructor(); - Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); - T loadable = (T) clazz.cast(intConstr.newInstance()); - + } + + final ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); + final Constructor objDef = parentClass.getDeclaredConstructor(); + final Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); + final T loadable = (T) clazz.cast(intConstr.newInstance()); + if (loadable == null) { continue; } loadables.add(loadable); - AbilityLoadEvent event = new AbilityLoadEvent(plugin, loadable, jar); - plugin.getServer().getPluginManager().callEvent(event); + final AbilityLoadEvent event = new AbilityLoadEvent(this.plugin, loadable, this.jar); + this.plugin.getServer().getPluginManager().callEvent(event); } catch (Exception | Error e) { continue; } - } - + } + return loadables; } diff --git a/src/com/projectkorra/projectkorra/ability/util/AddonAbilityLoader.java b/src/com/projectkorra/projectkorra/ability/util/AddonAbilityLoader.java index 61f003571..cf787f3a7 100644 --- a/src/com/projectkorra/projectkorra/ability/util/AddonAbilityLoader.java +++ b/src/com/projectkorra/projectkorra/ability/util/AddonAbilityLoader.java @@ -1,12 +1,5 @@ package com.projectkorra.projectkorra.ability.util; -import sun.reflect.ReflectionFactory; - -import com.projectkorra.projectkorra.event.AbilityLoadEvent; -import com.projectkorra.projectkorra.util.FileExtensionFilter; - -import org.bukkit.plugin.Plugin; - import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; @@ -21,6 +14,13 @@ import java.util.jar.JarFile; import java.util.logging.Level; +import org.bukkit.plugin.Plugin; + +import com.projectkorra.projectkorra.event.AbilityLoadEvent; +import com.projectkorra.projectkorra.util.FileExtensionFilter; + +import sun.reflect.ReflectionFactory; + public class AddonAbilityLoader { private final Plugin plugin; @@ -28,7 +28,7 @@ public class AddonAbilityLoader { private final ArrayList files; private ClassLoader loader; - public AddonAbilityLoader(Plugin plugin, File directory) { + public AddonAbilityLoader(final Plugin plugin, final File directory) { this.plugin = plugin; this.directory = directory; this.files = new ArrayList(); @@ -37,16 +37,16 @@ public AddonAbilityLoader(Plugin plugin, File directory) { return; } - for (File f : directory.listFiles(new FileExtensionFilter(".jar"))) { - files.add(f); + for (final File f : directory.listFiles(new FileExtensionFilter(".jar"))) { + this.files.add(f); } - List urls = new ArrayList(); - for (File file : files) { + final List urls = new ArrayList(); + for (final File file : this.files) { try { urls.add(file.toURI().toURL()); } - catch (MalformedURLException e) { + catch (final MalformedURLException e) { e.printStackTrace(); } } @@ -60,26 +60,25 @@ public AddonAbilityLoader(Plugin plugin, File directory) { * @return A list of all of the T objects that were loaded from the jar * files within @param directory */ - @SuppressWarnings("unchecked") - public List load(Class classType, Class parentClass) { - ArrayList loadables = new ArrayList<>(); + public List load(final Class classType, final Class parentClass) { + final ArrayList loadables = new ArrayList<>(); - for (File file : files) { + for (final File file : this.files) { JarFile jarFile = null; try { jarFile = new JarFile(file); - Enumeration entries = jarFile.entries(); + final Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); + final JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class")) { continue; } - String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); + final String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); Class clazz = null; try { - clazz = Class.forName(className, true, loader); + clazz = Class.forName(className, true, this.loader); } catch (Exception | Error e) { continue; @@ -89,28 +88,28 @@ public List load(Class classType, Class parentClass) { continue; } - ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); - Constructor objDef = parentClass.getDeclaredConstructor(); - Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); - T loadable = (T) clazz.cast(intConstr.newInstance()); + final ReflectionFactory rf = ReflectionFactory.getReflectionFactory(); + final Constructor objDef = parentClass.getDeclaredConstructor(); + final Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef); + final T loadable = (T) clazz.cast(intConstr.newInstance()); loadables.add(loadable); - AbilityLoadEvent event = new AbilityLoadEvent(plugin, loadable, jarFile); - plugin.getServer().getPluginManager().callEvent(event); + final AbilityLoadEvent event = new AbilityLoadEvent(this.plugin, loadable, jarFile); + this.plugin.getServer().getPluginManager().callEvent(event); } } catch (Exception | Error e) { e.printStackTrace(); - plugin.getLogger().log(Level.WARNING, "Unknown cause"); - plugin.getLogger().log(Level.WARNING, "The JAR file " + file.getName() + " failed to load"); + this.plugin.getLogger().log(Level.WARNING, "Unknown cause"); + this.plugin.getLogger().log(Level.WARNING, "The JAR file " + file.getName() + " failed to load"); } finally { if (jarFile != null) { try { jarFile.close(); } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } } @@ -120,19 +119,19 @@ public List load(Class classType, Class parentClass) { } public ClassLoader getLoader() { - return loader; + return this.loader; } public Plugin getPlugin() { - return plugin; + return this.plugin; } public File getDirectory() { - return directory; + return this.directory; } public ArrayList getFiles() { - return files; + return this.files; } } diff --git a/src/com/projectkorra/projectkorra/ability/util/Collision.java b/src/com/projectkorra/projectkorra/ability/util/Collision.java index 5e731dcbb..54555ec3f 100644 --- a/src/com/projectkorra/projectkorra/ability/util/Collision.java +++ b/src/com/projectkorra/projectkorra/ability/util/Collision.java @@ -7,11 +7,11 @@ /** * A Collision is used to represent the collision between two CoreAbility * objects. - * + * * To register Collisions Addon developers should use:
* ProjectKorra.getCollisionInitializer().addCollision(myCoreAbility) * ProjectKorra.getCollisionInitializer().addSmallAbility(myCoreAbility) - * + * * @see CollisionManager */ public class Collision { @@ -22,7 +22,7 @@ public class Collision { private Location locationFirst; private Location locationSecond; - public Collision(CoreAbility abilityFirst, CoreAbility abilitySecond, boolean removingFirst, boolean removingSecond, Location locationFirst, Location locationSecond) { + public Collision(final CoreAbility abilityFirst, final CoreAbility abilitySecond, final boolean removingFirst, final boolean removingSecond, final Location locationFirst, final Location locationSecond) { if (abilityFirst == null || abilitySecond == null) { return; } @@ -35,55 +35,55 @@ public Collision(CoreAbility abilityFirst, CoreAbility abilitySecond, boolean re this.locationSecond = locationSecond; } - public Collision(CoreAbility abilityFirst, CoreAbility abilitySecond, boolean removingFirst, boolean removingSecond) { + public Collision(final CoreAbility abilityFirst, final CoreAbility abilitySecond, final boolean removingFirst, final boolean removingSecond) { this(abilityFirst, abilitySecond, removingFirst, removingSecond, null, null); } public CoreAbility getAbilityFirst() { - return abilityFirst; + return this.abilityFirst; } - public void setAbilityFirst(CoreAbility abilityFirst) { + public void setAbilityFirst(final CoreAbility abilityFirst) { this.abilityFirst = abilityFirst; } public CoreAbility getAbilitySecond() { - return abilitySecond; + return this.abilitySecond; } - public void setAbilitySecond(CoreAbility abilitySecond) { + public void setAbilitySecond(final CoreAbility abilitySecond) { this.abilitySecond = abilitySecond; } public boolean isRemovingFirst() { - return removingFirst; + return this.removingFirst; } - public void setRemovingFirst(boolean removingFirst) { + public void setRemovingFirst(final boolean removingFirst) { this.removingFirst = removingFirst; } public boolean isRemovingSecond() { - return removingSecond; + return this.removingSecond; } - public void setRemovingSecond(boolean removingSecond) { + public void setRemovingSecond(final boolean removingSecond) { this.removingSecond = removingSecond; } public Location getLocationFirst() { - return locationFirst; + return this.locationFirst; } - public void setLocationFirst(Location locationFirst) { + public void setLocationFirst(final Location locationFirst) { this.locationFirst = locationFirst; } public Location getLocationSecond() { - return locationSecond; + return this.locationSecond; } - public void setLocationSecond(Location locationSecond) { + public void setLocationSecond(final Location locationSecond) { this.locationSecond = locationSecond; } diff --git a/src/com/projectkorra/projectkorra/ability/util/CollisionInitializer.java b/src/com/projectkorra/projectkorra/ability/util/CollisionInitializer.java index bed404af3..0b6fb69b0 100644 --- a/src/com/projectkorra/projectkorra/ability/util/CollisionInitializer.java +++ b/src/com/projectkorra/projectkorra/ability/util/CollisionInitializer.java @@ -14,7 +14,7 @@ import com.projectkorra.projectkorra.airbending.Tornado; import com.projectkorra.projectkorra.airbending.combo.AirStream; import com.projectkorra.projectkorra.airbending.combo.AirSweep; -import com.projectkorra.projectkorra.airbending.flight.AirFlight; +import com.projectkorra.projectkorra.airbending.flight.FlightMultiAbility; import com.projectkorra.projectkorra.earthbending.Catapult; import com.projectkorra.projectkorra.earthbending.Collapse; import com.projectkorra.projectkorra.earthbending.EarthArmor; @@ -56,144 +56,149 @@ /** * CollisionInitializer is used to create the default Collisions for a given * CollisionManager. - * + * * @see Collision * @see CollisionManager */ public class CollisionInitializer { - private CollisionManager collisionManager; + private final CollisionManager collisionManager; private ArrayList smallAbilities; private ArrayList largeAbilities; private ArrayList comboAbilities; private ArrayList removeSpoutAbilities; + private final ArrayList ignoreAbilities; - public CollisionInitializer(CollisionManager collisionManager) { + public CollisionInitializer(final CollisionManager collisionManager) { this.collisionManager = collisionManager; this.smallAbilities = new ArrayList<>(); this.comboAbilities = new ArrayList<>(); this.largeAbilities = new ArrayList<>(); this.removeSpoutAbilities = new ArrayList<>(); + this.ignoreAbilities = new ArrayList<>(); } - @SuppressWarnings("unused") public void initializeDefaultCollisions() { - CoreAbility airBlast = CoreAbility.getAbility(AirBlast.class); - CoreAbility airBurst = CoreAbility.getAbility(AirBurst.class); - CoreAbility airFlight = CoreAbility.getAbility(AirFlight.class); - CoreAbility airScooter = CoreAbility.getAbility(AirScooter.class); - CoreAbility airShield = CoreAbility.getAbility(AirShield.class); - CoreAbility airSpout = CoreAbility.getAbility(AirSpout.class); - CoreAbility airStream = CoreAbility.getAbility(AirStream.class); - CoreAbility airSuction = CoreAbility.getAbility(AirSuction.class); - CoreAbility airSweep = CoreAbility.getAbility(AirSweep.class); - CoreAbility airSwipe = CoreAbility.getAbility(AirSwipe.class); - CoreAbility suffocate = CoreAbility.getAbility(Suffocate.class); - CoreAbility tornado = CoreAbility.getAbility(Tornado.class); - - CoreAbility catapult = CoreAbility.getAbility(Catapult.class); - CoreAbility collapse = CoreAbility.getAbility(Collapse.class); - CoreAbility earthArmor = CoreAbility.getAbility(EarthArmor.class); - CoreAbility earthBlast = CoreAbility.getAbility(EarthBlast.class); - CoreAbility earthSmash = CoreAbility.getAbility(EarthSmash.class); - CoreAbility earthTunnel = CoreAbility.getAbility(EarthTunnel.class); - CoreAbility lavaFlow = CoreAbility.getAbility(LavaFlow.class); - CoreAbility raiseEarth = CoreAbility.getAbility(RaiseEarth.class); - CoreAbility ripple = CoreAbility.getAbility(Ripple.class); - - CoreAbility blazeArc = CoreAbility.getAbility(BlazeArc.class); - CoreAbility combustion = CoreAbility.getAbility(Combustion.class); - CoreAbility fireBlast = CoreAbility.getAbility(FireBlast.class); - CoreAbility fireBlastCharged = CoreAbility.getAbility(FireBlastCharged.class); - CoreAbility fireBurst = CoreAbility.getAbility(FireBurst.class); - CoreAbility fireJet = CoreAbility.getAbility(FireJet.class); - CoreAbility fireKick = CoreAbility.getAbility(FireKick.class); - CoreAbility fireSpin = CoreAbility.getAbility(FireSpin.class); - CoreAbility fireWheel = CoreAbility.getAbility(FireWheel.class); - CoreAbility fireShield = CoreAbility.getAbility(FireShield.class); - CoreAbility fireManipulation = CoreAbility.getAbility(FireManipulation.class); - CoreAbility lightning = CoreAbility.getAbility(Lightning.class); - CoreAbility wallOfFire = CoreAbility.getAbility(WallOfFire.class); - - CoreAbility bloodbending = CoreAbility.getAbility(Bloodbending.class); - CoreAbility healingWaters = CoreAbility.getAbility(HealingWaters.class); - CoreAbility iceBlast = CoreAbility.getAbility(IceBlast.class); - CoreAbility iceBullet = CoreAbility.getAbility(IceBullet.class); - CoreAbility iceWave = CoreAbility.getAbility(IceWave.class); - CoreAbility iceSpikeBlast = CoreAbility.getAbility(IceSpikeBlast.class); - CoreAbility octopusForm = CoreAbility.getAbility(OctopusForm.class); - CoreAbility surgeWall = CoreAbility.getAbility(SurgeWall.class); - CoreAbility surgeWave = CoreAbility.getAbility(SurgeWave.class); - CoreAbility torrent = CoreAbility.getAbility(Torrent.class); - CoreAbility torrentWave = CoreAbility.getAbility(TorrentWave.class); - CoreAbility waterBubble = CoreAbility.getAbility(WaterBubble.class); - CoreAbility waterManipulation = CoreAbility.getAbility(WaterManipulation.class); - CoreAbility waterSpout = CoreAbility.getAbility(WaterSpout.class); - CoreAbility waterSpoutWave = CoreAbility.getAbility(WaterSpoutWave.class); - - CoreAbility[] smallAbils = { airBlast, airSwipe, earthBlast, waterManipulation, fireBlast, combustion, blazeArc }; - CoreAbility[] largeAbils = { earthSmash, airShield, fireBlastCharged, fireKick, fireSpin, fireWheel, airSweep, iceBullet }; - CoreAbility[] comboAbils = { fireKick, fireSpin, fireWheel, airSweep, iceBullet }; - CoreAbility[] removeSpoutAbils = { airSwipe, earthBlast, waterManipulation, fireBlast, fireBlastCharged, earthSmash, fireKick, fireSpin, fireWheel, airSweep, iceBullet }; - - for (CoreAbility smallAbil : smallAbils) { - addSmallAbility(smallAbil); + final CoreAbility airBlast = CoreAbility.getAbility(AirBlast.class); + CoreAbility.getAbility(AirBurst.class); + CoreAbility.getAbility(AirScooter.class); + final CoreAbility airShield = CoreAbility.getAbility(AirShield.class); + CoreAbility.getAbility(AirSpout.class); + final CoreAbility airStream = CoreAbility.getAbility(AirStream.class); + final CoreAbility airSuction = CoreAbility.getAbility(AirSuction.class); + final CoreAbility airSweep = CoreAbility.getAbility(AirSweep.class); + final CoreAbility airSwipe = CoreAbility.getAbility(AirSwipe.class); + CoreAbility.getAbility(FlightMultiAbility.class); + CoreAbility.getAbility(Suffocate.class); + CoreAbility.getAbility(Tornado.class); + + CoreAbility.getAbility(Catapult.class); + CoreAbility.getAbility(Collapse.class); + CoreAbility.getAbility(EarthArmor.class); + final CoreAbility earthBlast = CoreAbility.getAbility(EarthBlast.class); + final CoreAbility earthSmash = CoreAbility.getAbility(EarthSmash.class); + CoreAbility.getAbility(EarthTunnel.class); + CoreAbility.getAbility(LavaFlow.class); + CoreAbility.getAbility(RaiseEarth.class); + CoreAbility.getAbility(Ripple.class); + + final CoreAbility blazeArc = CoreAbility.getAbility(BlazeArc.class); + final CoreAbility combustion = CoreAbility.getAbility(Combustion.class); + final CoreAbility fireBlast = CoreAbility.getAbility(FireBlast.class); + final CoreAbility fireBlastCharged = CoreAbility.getAbility(FireBlastCharged.class); + CoreAbility.getAbility(FireBurst.class); + CoreAbility.getAbility(FireJet.class); + final CoreAbility fireKick = CoreAbility.getAbility(FireKick.class); + final CoreAbility fireSpin = CoreAbility.getAbility(FireSpin.class); + final CoreAbility fireWheel = CoreAbility.getAbility(FireWheel.class); + final CoreAbility fireShield = CoreAbility.getAbility(FireShield.class); + final CoreAbility fireManipulation = CoreAbility.getAbility(FireManipulation.class); + CoreAbility.getAbility(Lightning.class); + CoreAbility.getAbility(WallOfFire.class); + + CoreAbility.getAbility(Bloodbending.class); + CoreAbility.getAbility(HealingWaters.class); + final CoreAbility iceBlast = CoreAbility.getAbility(IceBlast.class); + final CoreAbility iceBullet = CoreAbility.getAbility(IceBullet.class); + CoreAbility.getAbility(IceWave.class); + final CoreAbility iceSpikeBlast = CoreAbility.getAbility(IceSpikeBlast.class); + CoreAbility.getAbility(OctopusForm.class); + CoreAbility.getAbility(SurgeWall.class); + CoreAbility.getAbility(SurgeWave.class); + CoreAbility.getAbility(Torrent.class); + CoreAbility.getAbility(TorrentWave.class); + CoreAbility.getAbility(WaterBubble.class); + final CoreAbility waterManipulation = CoreAbility.getAbility(WaterManipulation.class); + CoreAbility.getAbility(WaterSpout.class); + CoreAbility.getAbility(WaterSpoutWave.class); + + final CoreAbility[] smallAbils = { airSwipe, earthBlast, waterManipulation, iceBlast, iceSpikeBlast, fireBlast }; + final CoreAbility[] largeAbils = { earthSmash, airShield, fireBlastCharged, fireKick, fireSpin, fireWheel, airSweep, iceBullet }; + final CoreAbility[] comboAbils = { fireKick, fireSpin, fireWheel, airSweep, iceBullet }; + final CoreAbility[] removeSpoutAbils = { airSwipe, earthBlast, waterManipulation, iceBlast, iceSpikeBlast, fireBlast, fireBlastCharged, earthSmash, fireKick, fireSpin, fireWheel, airSweep, iceBullet }; + final CoreAbility[] ignoreAbils = { airBlast, airSuction, blazeArc, combustion }; + + for (final CoreAbility smallAbil : smallAbils) { + this.addSmallAbility(smallAbil); } - for (CoreAbility largeAbil : largeAbils) { - addLargeAbility(largeAbil); + for (final CoreAbility largeAbil : largeAbils) { + this.addLargeAbility(largeAbil); } - for (CoreAbility comboAbil : comboAbils) { - addComboAbility(comboAbil); + for (final CoreAbility comboAbil : comboAbils) { + this.addComboAbility(comboAbil); } - for (CoreAbility removeSpoutAbil : removeSpoutAbils) { - addRemoveSpoutAbility(removeSpoutAbil); + for (final CoreAbility removeSpoutAbil : removeSpoutAbils) { + this.addRemoveSpoutAbility(removeSpoutAbil); } - - collisionManager.addCollision(new Collision(airShield, airBlast, false, true)); - collisionManager.addCollision(new Collision(airShield, airSuction, false, true)); - collisionManager.addCollision(new Collision(airShield, airStream, false, true)); - collisionManager.addCollision(new Collision(airShield, fireBlast, false, true)); - collisionManager.addCollision(new Collision(airShield, earthBlast, false, true)); - collisionManager.addCollision(new Collision(airShield, waterManipulation, false, true)); - for (CoreAbility comboAbil : comboAbils) { - collisionManager.addCollision(new Collision(airShield, comboAbil, false, true)); + for (final CoreAbility ignoreAbil : ignoreAbils) { + this.addIgnoreAbility(ignoreAbil); + } + for (final CoreAbility comboAbil : comboAbils) { + this.collisionManager.addCollision(new Collision(airShield, comboAbil, false, true)); } - collisionManager.addCollision(new Collision(fireShield, airBlast, false, true)); - collisionManager.addCollision(new Collision(fireShield, airSuction, false, true)); - collisionManager.addCollision(new Collision(fireShield, fireBlast, false, true)); - collisionManager.addCollision(new Collision(fireShield, fireBlastCharged, false, true)); - collisionManager.addCollision(new Collision(fireShield, waterManipulation, false, true)); - collisionManager.addCollision(new Collision(fireShield, earthBlast, false, true)); - collisionManager.addCollision(new Collision(fireShield, airSweep, false, true)); - - collisionManager.addCollision(new Collision(fireManipulation, airBlast, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, airSuction, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, fireBlast, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, fireBlastCharged, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, waterManipulation, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, earthBlast, false, true)); - collisionManager.addCollision(new Collision(fireManipulation, airSweep, false, true)); + this.collisionManager.addCollision(new Collision(airSwipe, airSwipe, false, false)); + + this.collisionManager.addCollision(new Collision(airShield, airSwipe, false, false)); + this.collisionManager.addCollision(new Collision(airShield, airSweep, false, false)); + this.collisionManager.addCollision(new Collision(airShield, fireBlastCharged, false, false)); + this.collisionManager.addCollision(new Collision(airShield, airStream, false, true)); + + this.collisionManager.addCollision(new Collision(airSweep, airSweep, false, false)); + + this.collisionManager.addCollision(new Collision(fireShield, fireBlastCharged, false, false)); + this.collisionManager.addCollision(new Collision(fireShield, fireBlast, false, true)); + this.collisionManager.addCollision(new Collision(fireShield, waterManipulation, false, true)); + this.collisionManager.addCollision(new Collision(fireShield, earthBlast, false, true)); + this.collisionManager.addCollision(new Collision(fireShield, airSweep, false, true)); + + this.collisionManager.addCollision(new Collision(fireManipulation, airBlast, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, airSuction, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, fireBlast, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, fireBlastCharged, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, waterManipulation, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, earthBlast, false, true)); + this.collisionManager.addCollision(new Collision(fireManipulation, airSweep, false, true)); } /** * An ability that collides with other small abilities. (EarthBlast, * FireBlast). Two colliding small abilities will remove each other. A small * ability is removed when it collides with a large ability. - * + * * @param smallAbility the small CoreAbility */ - public void addSmallAbility(CoreAbility smallAbility) { + public void addSmallAbility(final CoreAbility smallAbility) { if (smallAbility == null) { return; } - smallAbilities.add(smallAbility); - for (CoreAbility otherSmallAbility : smallAbilities) { - collisionManager.addCollision(new Collision(smallAbility, otherSmallAbility, true, true)); + this.smallAbilities.add(smallAbility); + for (final CoreAbility otherSmallAbility : this.smallAbilities) { + this.collisionManager.addCollision(new Collision(smallAbility, otherSmallAbility, true, true)); } - for (CoreAbility largeAbility : largeAbilities) { - collisionManager.addCollision(new Collision(largeAbility, smallAbility, false, true)); + for (final CoreAbility largeAbility : this.largeAbilities) { + this.collisionManager.addCollision(new Collision(largeAbility, smallAbility, false, true)); } } @@ -202,83 +207,107 @@ public void addSmallAbility(CoreAbility smallAbility) { * A large ability that removes small abilities (EarthSmash, Charged * FireBlast). The large ability remains while the small ability is * destroyed. - * + * * @param largeAbility the large CoreAbility */ - public void addLargeAbility(CoreAbility largeAbility) { + public void addLargeAbility(final CoreAbility largeAbility) { if (largeAbility == null) { return; } - largeAbilities.add(largeAbility); - for (CoreAbility smallAbility : smallAbilities) { - collisionManager.addCollision(new Collision(largeAbility, smallAbility, false, true)); + this.largeAbilities.add(largeAbility); + for (final CoreAbility smallAbility : this.smallAbilities) { + this.collisionManager.addCollision(new Collision(largeAbility, smallAbility, false, true)); } } /** * A combo ability that collides with all other combo abilities. Both * colliding combo abilities are destroyed. - * + * * @param comboAbility the combo CoreAbility */ - public void addComboAbility(CoreAbility comboAbility) { + public void addComboAbility(final CoreAbility comboAbility) { if (comboAbility == null) { return; } - comboAbilities.add(comboAbility); - for (CoreAbility otherComboAbility : smallAbilities) { - collisionManager.addCollision(new Collision(comboAbility, otherComboAbility, true, true)); + this.comboAbilities.add(comboAbility); + for (final CoreAbility otherComboAbility : this.smallAbilities) { + this.collisionManager.addCollision(new Collision(comboAbility, otherComboAbility, true, true)); } } /** * An ability that destroys WaterSpout, AirSpout, and SandSpout upon * contact. The spout is destroyed and this ability remains. - * + * * @param ability the ability that removes spouts */ - public void addRemoveSpoutAbility(CoreAbility ability) { + public void addRemoveSpoutAbility(final CoreAbility ability) { if (ability == null) { return; } - removeSpoutAbilities.add(ability); - collisionManager.addCollision(new Collision(ability, CoreAbility.getAbility(AirSpout.class), false, true)); - collisionManager.addCollision(new Collision(ability, CoreAbility.getAbility(WaterSpout.class), false, true)); + this.removeSpoutAbilities.add(ability); + this.collisionManager.addCollision(new Collision(ability, CoreAbility.getAbility(AirSpout.class), false, true)); + this.collisionManager.addCollision(new Collision(ability, CoreAbility.getAbility(WaterSpout.class), false, true)); + } + + /** + * An ability that collides with other small abilities. (EarthBlast, + * FireBlast). Two colliding small abilities will remove each other. A small + * ability is removed when it collides with a large ability. + * + * @param smallAbility the small CoreAbility + */ + public void addIgnoreAbility(final CoreAbility ignoreAbility) { + if (ignoreAbility == null) { + return; + } + this.ignoreAbilities.add(ignoreAbility); + for (final CoreAbility smallAbility : this.smallAbilities) { + this.collisionManager.addCollision(new Collision(ignoreAbility, smallAbility, false, false)); + } + + for (final CoreAbility largeAbility : this.largeAbilities) { + this.collisionManager.addCollision(new Collision(largeAbility, ignoreAbility, false, false)); + } + + this.collisionManager.addCollision(new Collision(ignoreAbility, CoreAbility.getAbility(AirSpout.class), false, false)); + this.collisionManager.addCollision(new Collision(ignoreAbility, CoreAbility.getAbility(WaterSpout.class), false, false)); } public CollisionManager getCollisionManager() { - return collisionManager; + return this.collisionManager; } public ArrayList getSmallAbilities() { - return smallAbilities; + return this.smallAbilities; } - public void setSmallAbilities(ArrayList smallAbilities) { + public void setSmallAbilities(final ArrayList smallAbilities) { this.smallAbilities = smallAbilities; } public ArrayList getLargeAbilities() { - return largeAbilities; + return this.largeAbilities; } - public void setLargeAbilities(ArrayList largeAbilities) { + public void setLargeAbilities(final ArrayList largeAbilities) { this.largeAbilities = largeAbilities; } public ArrayList getComboAbilities() { - return comboAbilities; + return this.comboAbilities; } - public void setComboAbilities(ArrayList comboAbilities) { + public void setComboAbilities(final ArrayList comboAbilities) { this.comboAbilities = comboAbilities; } public ArrayList getRemoveSpoutAbilities() { - return removeSpoutAbilities; + return this.removeSpoutAbilities; } - public void setRemoveSpoutAbilities(ArrayList removeSpoutAbilities) { + public void setRemoveSpoutAbilities(final ArrayList removeSpoutAbilities) { this.removeSpoutAbilities = removeSpoutAbilities; } diff --git a/src/com/projectkorra/projectkorra/ability/util/CollisionManager.java b/src/com/projectkorra/projectkorra/ability/util/CollisionManager.java index ac3cb4130..a7240332d 100644 --- a/src/com/projectkorra/projectkorra/ability/util/CollisionManager.java +++ b/src/com/projectkorra/projectkorra/ability/util/CollisionManager.java @@ -68,34 +68,34 @@ public CollisionManager() { private void detectCollisions() { int activeInstanceCount = 0; - - for (CoreAbility ability : CoreAbility.getAbilitiesByInstances()) { + + for (final CoreAbility ability : CoreAbility.getAbilitiesByInstances()) { if (!(ability instanceof PassiveAbility)) { if (++activeInstanceCount > 1) { break; } } } - + if (activeInstanceCount <= 1) { return; } - - HashMap> locationsCache = new HashMap<>(); - for (Collision collision : collisions) { - Collection instancesFirst = CoreAbility.getAbilities(collision.getAbilityFirst().getClass()); + final HashMap> locationsCache = new HashMap<>(); + + for (final Collision collision : this.collisions) { + final Collection instancesFirst = CoreAbility.getAbilities(collision.getAbilityFirst().getClass()); if (instancesFirst.isEmpty()) { continue; } - Collection instancesSecond = CoreAbility.getAbilities(collision.getAbilitySecond().getClass()); + final Collection instancesSecond = CoreAbility.getAbilities(collision.getAbilitySecond().getClass()); if (instancesSecond.isEmpty()) { continue; } - HashSet alreadyCollided = new HashSet(); - double certainNoCollisionDistSquared = Math.pow(certainNoCollisionDistance, 2); + final HashSet alreadyCollided = new HashSet(); + final double certainNoCollisionDistSquared = Math.pow(this.certainNoCollisionDistance, 2); - for (CoreAbility abilityFirst : instancesFirst) { + for (final CoreAbility abilityFirst : instancesFirst) { if (abilityFirst.getPlayer() == null || alreadyCollided.contains(abilityFirst) || !abilityFirst.isCollidable()) { continue; } @@ -103,32 +103,32 @@ private void detectCollisions() { if (!locationsCache.containsKey(abilityFirst)) { locationsCache.put(abilityFirst, abilityFirst.getLocations()); } - List locationsFirst = locationsCache.get(abilityFirst); + final List locationsFirst = locationsCache.get(abilityFirst); if (locationsFirst.isEmpty()) { continue; } - for (CoreAbility abilitySecond : instancesSecond) { + for (final CoreAbility abilitySecond : instancesSecond) { if (abilitySecond.getPlayer() == null || alreadyCollided.contains(abilitySecond) || !abilitySecond.isCollidable()) { continue; } else if (abilityFirst.getPlayer().equals(abilitySecond.getPlayer())) { continue; - } + } if (!locationsCache.containsKey(abilitySecond)) { locationsCache.put(abilitySecond, abilitySecond.getLocations()); } - List locationsSecond = locationsCache.get(abilitySecond); + final List locationsSecond = locationsCache.get(abilitySecond); if (locationsSecond.isEmpty()) { continue; } boolean collided = false; - boolean certainNoCollision = false; // Used for efficiency + boolean certainNoCollision = false; // Used for efficiency. Location locationFirst = null; Location locationSecond = null; - double requiredDist = abilityFirst.getCollisionRadius() + abilitySecond.getCollisionRadius(); - double requiredDistSquared = Math.pow(requiredDist, 2); + final double requiredDist = abilityFirst.getCollisionRadius() + abilitySecond.getCollisionRadius(); + final double requiredDistSquared = Math.pow(requiredDist, 2); for (int i = 0; i < locationsFirst.size(); i++) { locationFirst = locationsFirst.get(i); @@ -144,7 +144,7 @@ private void detectCollisions() { if (locationFirst.getWorld() != locationSecond.getWorld()) { continue; } - double distSquared = locationFirst.distanceSquared(locationSecond); + final double distSquared = locationFirst.distanceSquared(locationSecond); if (distSquared <= requiredDistSquared) { collided = true; break; @@ -159,16 +159,16 @@ private void detectCollisions() { } if (collided) { - Collision forwardCollision = new Collision(abilityFirst, abilitySecond, collision.isRemovingFirst(), collision.isRemovingSecond(), locationFirst, locationSecond); - Collision reverseCollision = new Collision(abilitySecond, abilityFirst, collision.isRemovingSecond(), collision.isRemovingFirst(), locationSecond, locationFirst); - AbilityCollisionEvent event = new AbilityCollisionEvent(forwardCollision); + final Collision forwardCollision = new Collision(abilityFirst, abilitySecond, collision.isRemovingFirst(), collision.isRemovingSecond(), locationFirst, locationSecond); + final Collision reverseCollision = new Collision(abilitySecond, abilityFirst, collision.isRemovingSecond(), collision.isRemovingFirst(), locationSecond, locationFirst); + final AbilityCollisionEvent event = new AbilityCollisionEvent(forwardCollision); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { continue; } abilityFirst.handleCollision(forwardCollision); abilitySecond.handleCollision(reverseCollision); - if (!removeMultipleInstances) { + if (!this.removeMultipleInstances) { alreadyCollided.add(abilityFirst); alreadyCollided.add(abilitySecond); break; @@ -183,78 +183,87 @@ private void detectCollisions() { * Adds a "fake" Collision to the CollisionManager so that two abilities can * be checked for collisions. This Collision only needs to define the * abilityFirst, abilitySecond, removeFirst, and removeSecond. - * + * * @param collision a Collision containing two CoreAbility classes */ - public void addCollision(Collision collision) { + public void addCollision(final Collision collision) { if (collision == null || collision.getAbilityFirst() == null || collision.getAbilitySecond() == null) { return; } - collisions.add(collision); + + for (int x = 0; x < this.collisions.size(); x++) { + if (this.collisions.get(x).getAbilityFirst().equals(collision.getAbilityFirst())) { + if (this.collisions.get(x).getAbilitySecond().equals(collision.getAbilitySecond())) { + this.collisions.remove(x); + } + } + } + + this.collisions.add(collision); } /** * Begins a BukkitRunnable to check for Collisions. */ public void startCollisionDetection() { - stopCollisionDetection(); - detectionRunnable = new BukkitRunnable() { + this.stopCollisionDetection(); + this.detectionRunnable = new BukkitRunnable() { @Override public void run() { - detectCollisions(); + CollisionManager.this.detectCollisions(); } }; - detectionRunnable.runTaskTimer(ProjectKorra.plugin, 0L, detectionDelay); + this.detectionRunnable.runTaskTimer(ProjectKorra.plugin, 0L, this.detectionDelay); } /** * Stops the collision detecting BukkitRunnable. */ public void stopCollisionDetection() { - if (detectionRunnable != null) { - detectionRunnable.cancel(); - detectionRunnable = null; + if (this.detectionRunnable != null) { + this.detectionRunnable.cancel(); + this.detectionRunnable = null; } } public boolean isRemoveMultipleInstances() { - return removeMultipleInstances; + return this.removeMultipleInstances; } - public void setRemoveMultipleInstances(boolean removeMultipleInstances) { + public void setRemoveMultipleInstances(final boolean removeMultipleInstances) { this.removeMultipleInstances = removeMultipleInstances; } public long getDetectionDelay() { - return detectionDelay; + return this.detectionDelay; } - public void setDetectionDelay(long detectionDelay) { + public void setDetectionDelay(final long detectionDelay) { this.detectionDelay = detectionDelay; } public double getCertainNoCollisionDistance() { - return certainNoCollisionDistance; + return this.certainNoCollisionDistance; } - public void setCertainNoCollisionDistance(double certainNoCollisionDistance) { + public void setCertainNoCollisionDistance(final double certainNoCollisionDistance) { this.certainNoCollisionDistance = certainNoCollisionDistance; } public ArrayList getCollisions() { - return collisions; + return this.collisions; } - public void setCollisions(ArrayList collisions) { + public void setCollisions(final ArrayList collisions) { this.collisions = collisions; } public BukkitRunnable getDetectionRunnable() { - return detectionRunnable; + return this.detectionRunnable; } - public void setDetectionRunnable(BukkitRunnable detectionRunnable) { + public void setDetectionRunnable(final BukkitRunnable detectionRunnable) { this.detectionRunnable = detectionRunnable; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/ability/util/ComboManager.java b/src/com/projectkorra/projectkorra/ability/util/ComboManager.java index c5dc2ff82..5221078c9 100644 --- a/src/com/projectkorra/projectkorra/ability/util/ComboManager.java +++ b/src/com/projectkorra/projectkorra/ability/util/ComboManager.java @@ -15,26 +15,15 @@ import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.ComboAbility; import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.airbending.combo.AirStream; -import com.projectkorra.projectkorra.airbending.combo.AirSweep; -import com.projectkorra.projectkorra.airbending.combo.Twister; -import com.projectkorra.projectkorra.chiblocking.combo.Immobilize; import com.projectkorra.projectkorra.configuration.ConfigManager; -import com.projectkorra.projectkorra.firebending.combo.FireKick; -import com.projectkorra.projectkorra.firebending.combo.FireSpin; -import com.projectkorra.projectkorra.firebending.combo.FireWheel; -import com.projectkorra.projectkorra.firebending.combo.JetBlast; -import com.projectkorra.projectkorra.firebending.combo.JetBlaze; +import com.projectkorra.projectkorra.earthbending.combo.EarthDomeOthers; import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.ReflectionHandler; -import com.projectkorra.projectkorra.waterbending.combo.IceBullet; import com.projectkorra.projectkorra.waterbending.combo.IceBullet.IceBulletLeftClick; import com.projectkorra.projectkorra.waterbending.combo.IceBullet.IceBulletRightClick; -import com.projectkorra.projectkorra.waterbending.combo.IceWave; public class ComboManager { - - private static final long CLEANUP_DELAY = 20 * 600; + private static final long CLEANUP_DELAY = 20 * 60; private static final Map> RECENTLY_USED = new ConcurrentHashMap<>(); private static final HashMap COMBO_ABILITIES = new HashMap<>(); private static final HashMap AUTHORS = new HashMap<>(); @@ -46,151 +35,37 @@ public ComboManager() { DESCRIPTIONS.clear(); INSTRUCTIONS.clear(); - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.FireKick.Enabled")) { - ArrayList fireKick = new ArrayList<>(); - fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); - fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); - fireKick.add(new AbilityInformation("FireBlast", ClickType.SHIFT_DOWN)); - fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("FireKick", new ComboAbilityInfo("FireKick", fireKick, FireKick.class)); - DESCRIPTIONS.put("FireKick", ConfigManager.languageConfig.get().getString("Abilities.Fire.Combo.FireKick.Description")); - INSTRUCTIONS.put("FireKick", "FireBlast > FireBlast > (Hold Shift) > FireBlast."); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.FireSpin.Enabled")) { - ArrayList fireSpin = new ArrayList<>(); - fireSpin.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); - fireSpin.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); - fireSpin.add(new AbilityInformation("FireShield", ClickType.LEFT_CLICK)); - fireSpin.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); - fireSpin.add(new AbilityInformation("FireShield", ClickType.SHIFT_UP)); - COMBO_ABILITIES.put("FireSpin", new ComboAbilityInfo("FireSpin", fireSpin, FireSpin.class)); - DESCRIPTIONS.put("FireSpin", ConfigManager.languageConfig.get().getString("Abilities.Fire.Combo.FireSpin.Description")); - INSTRUCTIONS.put("FireSpin", "FireBlast > FireBlast > FireShield (Left Click) > FireShield (Tap Shift)."); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.JetBlast.Enabled")) { - ArrayList jetBlast = new ArrayList<>(); - jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); - jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); - jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); - jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); - jetBlast.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); - jetBlast.add(new AbilityInformation("FireShield", ClickType.SHIFT_UP)); - jetBlast.add(new AbilityInformation("FireJet", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("JetBlast", new ComboAbilityInfo("JetBlast", jetBlast, JetBlast.class)); - DESCRIPTIONS.put("JetBlast", ConfigManager.languageConfig.get().getString("Abilities.Fire.Combo.JetBlast.Description")); - INSTRUCTIONS.put("JetBlast", "FireJet (Tap Shift) > FireJet (Tap Shift) > FireShield (Tap Shift) > FireJet."); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.JetBlaze.Enabled")) { - ArrayList jetBlaze = new ArrayList<>(); - jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); - jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); - jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); - jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); - jetBlaze.add(new AbilityInformation("Blaze", ClickType.SHIFT_DOWN)); - jetBlaze.add(new AbilityInformation("Blaze", ClickType.SHIFT_UP)); - jetBlaze.add(new AbilityInformation("FireJet", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("JetBlaze", new ComboAbilityInfo("JetBlaze", jetBlaze, JetBlaze.class)); - DESCRIPTIONS.put("JetBlaze", ConfigManager.languageConfig.get().getString("Abilities.Fire.Combo.JetBlaze.Description")); - INSTRUCTIONS.put("JetBlaze", "FireJet (Tap Shift) > FireJet (Tap Shift) > Blaze (Tap Shift) > FireJet."); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.FireWheel.Enabled")) { - ArrayList fireWheel = new ArrayList<>(); - fireWheel.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); - fireWheel.add(new AbilityInformation("FireShield", ClickType.RIGHT_CLICK_BLOCK)); - fireWheel.add(new AbilityInformation("FireShield", ClickType.RIGHT_CLICK_BLOCK)); - fireWheel.add(new AbilityInformation("Blaze", ClickType.SHIFT_UP)); - COMBO_ABILITIES.put("FireWheel", new ComboAbilityInfo("FireWheel", fireWheel, FireWheel.class)); - DESCRIPTIONS.put("FireWheel", ConfigManager.languageConfig.get().getString("Abilities.Fire.Combo.FireWheel.Description")); - INSTRUCTIONS.put("FireWheel", "FireShield (Hold Shift) > Right Click a block in front of you twice > Switch to Blaze > Release Shift."); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Air.Twister.Enabled")) { - ArrayList twister = new ArrayList(); - twister.add(new AbilityInformation("AirShield", ClickType.SHIFT_DOWN)); - twister.add(new AbilityInformation("AirShield", ClickType.SHIFT_UP)); - twister.add(new AbilityInformation("Tornado", ClickType.SHIFT_DOWN)); - twister.add(new AbilityInformation("AirBlast", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("Twister", new ComboAbilityInfo("Twister", twister, Twister.class)); - DESCRIPTIONS.put("Twister", ConfigManager.languageConfig.get().getString("Abilities.Air.Combo.Twister.Description")); - INSTRUCTIONS.put("Twister", "AirShield (Tap Shift) > Tornado (Hold Shift) > AirBlast (Left Click)"); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Air.AirStream.Enabled")) { - ArrayList airStream = new ArrayList<>(); - airStream.add(new AbilityInformation("AirShield", ClickType.SHIFT_DOWN)); - airStream.add(new AbilityInformation("AirSuction", ClickType.LEFT_CLICK)); - airStream.add(new AbilityInformation("AirBlast", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("AirStream", new ComboAbilityInfo("AirStream", airStream, AirStream.class)); - DESCRIPTIONS.put("AirStream", ConfigManager.languageConfig.get().getString("Abilities.Air.Combo.AirStream.Description")); - INSTRUCTIONS.put("AirStream", "AirShield (Hold Shift) > AirSuction (Left Click) > AirBlast (Left Click)"); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Air.AirSweep.Enabled")) { - ArrayList airSweep = new ArrayList<>(); - airSweep.add(new AbilityInformation("AirSwipe", ClickType.LEFT_CLICK)); - airSweep.add(new AbilityInformation("AirSwipe", ClickType.LEFT_CLICK)); - airSweep.add(new AbilityInformation("AirBurst", ClickType.SHIFT_DOWN)); - airSweep.add(new AbilityInformation("AirBurst", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("AirSweep", new ComboAbilityInfo("AirSweep", airSweep, AirSweep.class)); - DESCRIPTIONS.put("AirSweep", ConfigManager.languageConfig.get().getString("Abilities.Air.Combo.AirSweep.Description")); - INSTRUCTIONS.put("AirSweep", "AirSwipe (Left Click) > AirSwipe (Left Click) > AirBurst (Hold Shift) > AirBurst (Left Click)"); - } - - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.IceWave.Enabled")) { - ArrayList iceWave = new ArrayList<>(); - iceWave.add(new AbilityInformation("WaterSpout", ClickType.SHIFT_UP)); - iceWave.add(new AbilityInformation("PhaseChange", ClickType.LEFT_CLICK)); - COMBO_ABILITIES.put("IceWave", new ComboAbilityInfo("IceWave", iceWave, IceWave.class)); - DESCRIPTIONS.put("IceWave", ConfigManager.languageConfig.get().getString("Abilities.Water.Combo.IceWave.Description")); - INSTRUCTIONS.put("IceWave", "Create a WaterSpout Wave > PhaseChange (Left Click)"); - } - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Water.IceBullet.Enabled")) { - ArrayList iceBullet = new ArrayList<>(); - iceBullet.add(new AbilityInformation("WaterBubble", ClickType.SHIFT_DOWN)); - iceBullet.add(new AbilityInformation("WaterBubble", ClickType.SHIFT_UP)); - iceBullet.add(new AbilityInformation("IceBlast", ClickType.SHIFT_DOWN)); - COMBO_ABILITIES.put("IceBullet", new ComboAbilityInfo("IceBullet", iceBullet, IceBullet.class)); - DESCRIPTIONS.put("IceBullet", ConfigManager.languageConfig.get().getString("Abilities.Water.Combo.IceBullet.Description")); - INSTRUCTIONS.put("IceBullet", "WaterBubble (Tap Shift) > IceBlast (Hold Shift) > Wait for ice to Form > Then alternate between Left and Right click with IceBlast"); - - ArrayList iceBulletLeft = new ArrayList<>(); + final ArrayList iceBulletLeft = new ArrayList<>(); iceBulletLeft.add(new AbilityInformation("IceBlast", ClickType.LEFT_CLICK)); COMBO_ABILITIES.put("IceBulletLeftClick", new ComboAbilityInfo("IceBulletLeftClick", iceBulletLeft, IceBulletLeftClick.class)); - ArrayList iceBulletRight = new ArrayList<>(); + final ArrayList iceBulletRight = new ArrayList<>(); iceBulletRight.add(new AbilityInformation("IceBlast", ClickType.RIGHT_CLICK_BLOCK)); COMBO_ABILITIES.put("IceBulletRightClick", new ComboAbilityInfo("IceBulletRightClick", iceBulletRight, IceBulletRightClick.class)); } - if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Chi.Immobilize.Enabled")) { - ArrayList immobilize = new ArrayList<>(); - immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); - immobilize.add(new AbilityInformation("SwiftKick", ClickType.LEFT_CLICK_ENTITY)); - immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); - immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); - COMBO_ABILITIES.put("Immobilize", new ComboAbilityInfo("Immobilize", immobilize, Immobilize.class)); - DESCRIPTIONS.put("Immobilize", ConfigManager.languageConfig.get().getString("Abilities.Chi.Combo.Immobilize.Description")); - INSTRUCTIONS.put("Immobilize", "QuickStrike (Left Click) > SwiftKick (Left Click) > QuickStrike (Left Click) > QuickStrike (Left Click)"); + if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Earth.EarthDome.Enabled")) { + final ArrayList earthDomeOthers = new ArrayList<>(); + earthDomeOthers.add(new AbilityInformation("RaiseEarth", ClickType.RIGHT_CLICK_BLOCK)); + earthDomeOthers.add(new AbilityInformation("Shockwave", ClickType.LEFT_CLICK)); + COMBO_ABILITIES.put("EarthDomeOthers", new ComboAbilityInfo("EarthDomeOthers", earthDomeOthers, EarthDomeOthers.class)); } startCleanupTask(); } - public static void addComboAbility(final Player player, ClickType type) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void addComboAbility(final Player player, final ClickType type) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } - String abilityName = bPlayer.getBoundAbilityName(); + final String abilityName = bPlayer.getBoundAbilityName(); if (abilityName == null) { return; } - AbilityInformation info = new AbilityInformation(abilityName, type, System.currentTimeMillis()); + + final AbilityInformation info = new AbilityInformation(abilityName, type, System.currentTimeMillis()); addRecentAbility(player, info); final ComboAbilityInfo comboAbil = checkForValidCombo(player); @@ -204,11 +79,11 @@ public static void addComboAbility(final Player player, ClickType type) { @Override public void run() { if (comboAbil.getComboType() instanceof Class) { - Class clazz = (Class) comboAbil.getComboType(); + final Class clazz = (Class) comboAbil.getComboType(); try { ReflectionHandler.instantiateObject(clazz, player); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } else { @@ -225,18 +100,19 @@ public void run() { /** * Adds an {@link AbilityInformation} to the player's * {@link ComboManager#RECENTLY_USED recentlyUsedAbilities}. - * + * * @param player The player to add the AbilityInformation for * @param info The AbilityInformation to add */ - public static void addRecentAbility(Player player, AbilityInformation info) { + public static void addRecentAbility(final Player player, final AbilityInformation info) { ArrayList list; - String name = player.getName(); + final String name = player.getName(); if (RECENTLY_USED.containsKey(name)) { list = RECENTLY_USED.get(name); } else { list = new ArrayList(); } + list.add(info); RECENTLY_USED.put(name, list); } @@ -245,18 +121,18 @@ public static void addRecentAbility(Player player, AbilityInformation info) { * Checks if a Player's {@link ComboManager#RECENTLY_USED * recentlyUsedAbilities} contains a valid set of moves to perform any * combos. If it does, it returns the valid combo. - * + * * @param player The player for whom to check if a valid combo has been * performed * @return The ComboAbility of the combo that has been performed, or null if * no valid combo was found */ - public static ComboAbilityInfo checkForValidCombo(Player player) { - ArrayList playerCombo = getRecentlyUsedAbilities(player, 8); - for (String ability : COMBO_ABILITIES.keySet()) { - ComboAbilityInfo customAbility = COMBO_ABILITIES.get(ability); - ArrayList abilityCombo = customAbility.getAbilities(); - int size = abilityCombo.size(); + public static ComboAbilityInfo checkForValidCombo(final Player player) { + final ArrayList playerCombo = getRecentlyUsedAbilities(player, 8); + for (final String ability : COMBO_ABILITIES.keySet()) { + final ComboAbilityInfo customAbility = COMBO_ABILITIES.get(ability); + final ArrayList abilityCombo = customAbility.getAbilities(); + final int size = abilityCombo.size(); if (playerCombo.size() < size) { continue; @@ -264,8 +140,8 @@ public static ComboAbilityInfo checkForValidCombo(Player player) { boolean isValid = true; for (int i = 1; i <= size; i++) { - AbilityInformation playerInfo = playerCombo.get(playerCombo.size() - i); - AbilityInformation comboInfo = abilityCombo.get(abilityCombo.size() - i); + final AbilityInformation playerInfo = playerCombo.get(playerCombo.size() - i); + final AbilityInformation comboInfo = abilityCombo.get(abilityCombo.size() - i); if (playerInfo.getAbilityName().equals(comboInfo.getAbilityName()) && playerInfo.getClickType() == ClickType.LEFT_CLICK_ENTITY && comboInfo.getClickType() == ClickType.LEFT_CLICK) { continue; } else if (!playerInfo.equalsWithoutTime(comboInfo)) { @@ -273,10 +149,12 @@ public static ComboAbilityInfo checkForValidCombo(Player player) { break; } } + if (isValid) { return customAbility; } } + return null; } @@ -286,41 +164,42 @@ public static void cleanupOldCombos() { /** * Gets the player's most recently used abilities, up to a maximum of 10. - * + * * @param player The player to get recent abilities for * @param amount The amount of recent abilities to get, starting from most * recent and getting older * @return An ArrayList<{@link AbilityInformation}> of the player's recently * used abilities */ - public static ArrayList getRecentlyUsedAbilities(Player player, int amount) { - String name = player.getName(); + public static ArrayList getRecentlyUsedAbilities(final Player player, final int amount) { + final String name = player.getName(); if (!RECENTLY_USED.containsKey(name)) { return new ArrayList(); } - ArrayList list = RECENTLY_USED.get(name); + final ArrayList list = RECENTLY_USED.get(name); if (list.size() < amount) { return new ArrayList(list); } - ArrayList tempList = new ArrayList(); + final ArrayList tempList = new ArrayList(); for (int i = 0; i < amount; i++) { tempList.add(0, list.get(list.size() - 1 - i)); } + return tempList; } /** * Gets all of the combos for a given element. - * + * * @param element The element to get combos for * @return An ArrayList of the combos for that element */ - public static ArrayList getCombosForElement(Element element) { - ArrayList list = new ArrayList(); - for (String comboab : COMBO_ABILITIES.keySet()) { - CoreAbility coreAbil = CoreAbility.getAbility(comboab); + public static ArrayList getCombosForElement(final Element element) { + final ArrayList list = new ArrayList(); + for (final String comboab : COMBO_ABILITIES.keySet()) { + final CoreAbility coreAbil = CoreAbility.getAbility(comboab); if (coreAbil == null) { continue; } @@ -329,10 +208,12 @@ public static ArrayList getCombosForElement(Element element) { if (abilElement instanceof SubElement) { abilElement = ((SubElement) abilElement).getParentElement(); } + if (abilElement == element) { list.add(comboab); } } + Collections.sort(list); return list; } @@ -368,20 +249,20 @@ public static HashMap getInstructions() { /** * Contains information on an ability used in a combo. - * + * * @author kingbirdy - * + * */ public static class AbilityInformation { private String abilityName; private ClickType clickType; private long time; - public AbilityInformation(String name, ClickType type) { + public AbilityInformation(final String name, final ClickType type) { this(name, type, 0); } - public AbilityInformation(String name, ClickType type, long time) { + public AbilityInformation(final String name, final ClickType type, final long time) { this.abilityName = name; this.clickType = type; this.time = time; @@ -390,51 +271,51 @@ public AbilityInformation(String name, ClickType type, long time) { /** * Compares if two {@link AbilityInformation}'s are equal without * respect to {@link AbilityInformation#time time}. - * + * * @param info The AbilityInformation to compare against * @return True if they are equal without respect to time */ - public boolean equalsWithoutTime(AbilityInformation info) { + public boolean equalsWithoutTime(final AbilityInformation info) { return this.getAbilityName().equals(info.getAbilityName()) && this.getClickType().equals(info.getClickType()); } /** * Gets the name of the ability. - * + * * @return The name of the ability. */ public String getAbilityName() { - return abilityName; + return this.abilityName; } /** * Gets the {@link ClickType} of the {@link AbilityInformation}. - * + * * @return The ClickType */ public ClickType getClickType() { - return clickType; + return this.clickType; } public long getTime() { - return time; + return this.time; } - public void setAbilityName(String abilityName) { + public void setAbilityName(final String abilityName) { this.abilityName = abilityName; } - public void setClickType(ClickType clickType) { + public void setClickType(final ClickType clickType) { this.clickType = clickType; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } @Override public String toString() { - return abilityName + " " + clickType + " " + time; + return this.abilityName + " " + this.clickType + " " + this.time; } } @@ -443,39 +324,39 @@ public static class ComboAbilityInfo { private ArrayList abilities; private Object comboType; - public ComboAbilityInfo(String name, ArrayList abilities, Object comboType) { + public ComboAbilityInfo(final String name, final ArrayList abilities, final Object comboType) { this.name = name; this.abilities = abilities; this.comboType = comboType; } public ArrayList getAbilities() { - return abilities; + return this.abilities; } public Object getComboType() { - return comboType; + return this.comboType; } public String getName() { - return name; + return this.name; } - public void setAbilities(ArrayList abilities) { + public void setAbilities(final ArrayList abilities) { this.abilities = abilities; } - public void setComboType(Object comboType) { + public void setComboType(final Object comboType) { this.comboType = comboType; } - public void setName(String name) { + public void setName(final String name) { this.name = name; } @Override public String toString() { - return name; + return this.name; } } } diff --git a/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java b/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java index c57384f27..f79cf85b5 100644 --- a/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java +++ b/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java @@ -1,21 +1,21 @@ package com.projectkorra.projectkorra.ability.util; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.Element; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.event.BindChangeEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.event.BindChangeEvent; public class MultiAbilityManager { @@ -25,7 +25,7 @@ public class MultiAbilityManager { public static ArrayList multiAbilityList = new ArrayList(); public MultiAbilityManager() { - ArrayList waterArms = new ArrayList(); + final ArrayList waterArms = new ArrayList(); waterArms.add(new MultiAbilityInfoSub("Pull", Element.WATER)); waterArms.add(new MultiAbilityInfoSub("Punch", Element.WATER)); waterArms.add(new MultiAbilityInfoSub("Grapple", Element.WATER)); @@ -38,28 +38,30 @@ public MultiAbilityManager() { /** * Sets up a player's binds for a MultiAbility. - * + * * @param player Player having the multiability bound * @param multiAbility MultiAbility being bound */ - public static void bindMultiAbility(Player player, String multiAbility) { - BindChangeEvent event = new BindChangeEvent(player, multiAbility, true); + public static void bindMultiAbility(final Player player, final String multiAbility) { + final BindChangeEvent event = new BindChangeEvent(player, multiAbility, true); Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) + if (event.isCancelled()) { return; + } - if (playerAbilities.containsKey(player)) + if (playerAbilities.containsKey(player)) { unbindMultiAbility(player); + } playerSlot.put(player, player.getInventory().getHeldItemSlot()); playerBoundAbility.put(player, multiAbility); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - HashMap currAbilities = new HashMap(); - for (int i : bPlayer.getAbilities().keySet()) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final HashMap currAbilities = new HashMap(); + for (final int i : bPlayer.getAbilities().keySet()) { currAbilities.put(i, bPlayer.getAbilities().get(i)); } playerAbilities.put(player, currAbilities); - List modes = getMultiAbility(multiAbility).getAbilities(); + final List modes = getMultiAbility(multiAbility).getAbilities(); bPlayer.getAbilities().clear(); for (int i = 0; i < modes.size(); i++) { @@ -71,8 +73,7 @@ public static void bindMultiAbility(Player player, String multiAbility) { } if (player.isOnline()) { - bPlayer.addCooldown("MAM_Setup", 1L); // Support for bending - // scoreboards. + bPlayer.addCooldown("MAM_Setup", 1L); // Support for bending scoreboards. player.getInventory().setHeldItemSlot(0); } } @@ -80,39 +81,42 @@ public static void bindMultiAbility(Player player, String multiAbility) { /** * Returns the MultiAbility the player has bound. Returns null if no * multiability is bound and active. - * + * * @param player The player to use * @return name of multi ability bounded */ - public static String getBoundMultiAbility(Player player) { - if (playerBoundAbility.containsKey(player)) + public static String getBoundMultiAbility(final Player player) { + if (playerBoundAbility.containsKey(player)) { return playerBoundAbility.get(player); + } return null; } /** * Returns a MultiAbility based on name. - * + * * @param multiAbility Name of the multiability * @return the multiability object or null */ - public static MultiAbilityInfo getMultiAbility(String multiAbility) { - for (MultiAbilityInfo ma : multiAbilityList) { - if (ma.getName().equalsIgnoreCase(multiAbility)) + public static MultiAbilityInfo getMultiAbility(final String multiAbility) { + for (final MultiAbilityInfo ma : multiAbilityList) { + if (ma.getName().equalsIgnoreCase(multiAbility)) { return ma; + } } return null; } /** * Returns a boolean based on whether a player has a MultiAbility active. - * + * * @param player The player to check * @return true If player has a multiability active */ - public static boolean hasMultiAbilityBound(Player player) { - if (playerAbilities.containsKey(player)) + public static boolean hasMultiAbilityBound(final Player player) { + if (playerAbilities.containsKey(player)) { return true; + } return false; } @@ -120,20 +124,21 @@ public static boolean hasMultiAbilityBound(Player player) { * MultiAbility equivalent of * {@link GeneralMethods#getBoundAbility(Player)}. Returns a boolean based * on whether a player has a specific MultiAbility active. - * + * * @param player The player to check * @param multiAbility The multiability name * @return true If player has the specified multiability active */ - public static boolean hasMultiAbilityBound(Player player, String multiAbility) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean hasMultiAbilityBound(final Player player, final String multiAbility) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return false; } if (playerAbilities.containsKey(player)) { - if (!playerBoundAbility.get(player).equals(multiAbility) && bPlayer.getBoundAbility() != null) + if (!playerBoundAbility.get(player).equals(multiAbility) && bPlayer.getBoundAbility() != null) { return false; + } return true; } return false; @@ -141,6 +146,7 @@ public static boolean hasMultiAbilityBound(Player player, String multiAbility) { public static void manage() { new BukkitRunnable() { + @Override public void run() { scrollHotBarSlots(); } @@ -149,10 +155,10 @@ public void run() { /** * Clears all MultiAbility data for a player. Called on player quit event. - * + * * @param player */ - public static void remove(Player player) { + public static void remove(final Player player) { playerAbilities.remove(player); playerBoundAbility.remove(player); playerSlot.remove(player); @@ -172,8 +178,8 @@ public static void removeAll() { */ public static void scrollHotBarSlots() { if (!playerAbilities.isEmpty()) { - for (Player player : playerAbilities.keySet()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + for (final Player player : playerAbilities.keySet()) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { continue; } @@ -193,43 +199,48 @@ public static void scrollHotBarSlots() { /** * Reverts a player's binds to a previous state before use of a * MultiAbility. - * + * * @param player */ - public static void unbindMultiAbility(Player player) { + public static void unbindMultiAbility(final Player player) { if (playerAbilities.containsKey(player)) { - HashMap prevBinds = playerAbilities.get(player); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final HashMap prevBinds = playerAbilities.get(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } int lastNonNull = -1; for (int i = 1; i < 10; i++) { - if (prevBinds.get(i) != null) + if (prevBinds.get(i) != null) { lastNonNull = i; + } bPlayer.getAbilities().put(i, prevBinds.get(i)); } - if (lastNonNull > -1) + if (lastNonNull > -1) { GeneralMethods.saveAbility(bPlayer, lastNonNull, prevBinds.get(lastNonNull)); + } - if (player.isOnline()) - bPlayer.addCooldown("MAM_Setup", 1L); // Support for bending - // scoreboards. + if (player.isOnline()) { + bPlayer.addCooldown("MAM_Setup", 1L); // Support for bending scoreboards. + } playerAbilities.remove(player); } if (playerSlot.containsKey(player)) { - if (player.isOnline()) + if (player.isOnline()) { player.getInventory().setHeldItemSlot(playerSlot.get(player)); + } playerSlot.remove(player); } else { - if (player.isOnline()) + if (player.isOnline()) { player.getInventory().setHeldItemSlot(0); + } } - if (playerBoundAbility.containsKey(player)) + if (playerBoundAbility.containsKey(player)) { playerBoundAbility.remove(player); + } } /** @@ -240,24 +251,24 @@ public static class MultiAbilityInfo { private String name; private ArrayList abilities; - public MultiAbilityInfo(String name, ArrayList abilities) { + public MultiAbilityInfo(final String name, final ArrayList abilities) { this.name = name; this.abilities = abilities; } public ArrayList getAbilities() { - return abilities; + return this.abilities; } public String getName() { - return name; + return this.name; } - public void setAbilities(ArrayList abilities) { + public void setAbilities(final ArrayList abilities) { this.abilities = abilities; } - public void setName(String name) { + public void setName(final String name) { this.name = name; } } @@ -266,29 +277,29 @@ public static class MultiAbilityInfoSub { private String name; private Element element; - public MultiAbilityInfoSub(String name, Element element) { + public MultiAbilityInfoSub(final String name, final Element element) { this.name = name; this.element = element; } public Element getElement() { - return element; + return this.element; } public String getName() { - return name; + return this.name; } - public void setElement(Element element) { + public void setElement(final Element element) { this.element = element; } - public void setName(String name) { + public void setName(final String name) { this.name = name; } public ChatColor getAbilityColor() { - return element != null ? element.getColor() : null; + return this.element != null ? this.element.getColor() : null; } } diff --git a/src/com/projectkorra/projectkorra/ability/util/PassiveManager.java b/src/com/projectkorra/projectkorra/ability/util/PassiveManager.java index b5ac6e878..990aa7e63 100644 --- a/src/com/projectkorra/projectkorra/ability/util/PassiveManager.java +++ b/src/com/projectkorra/projectkorra/ability/util/PassiveManager.java @@ -20,12 +20,12 @@ public class PassiveManager { private static final Map PASSIVES = new HashMap<>(); private static final Map> PASSIVE_CLASSES = new HashMap<>(); - public static void registerPassives(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void registerPassives(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } - for (CoreAbility ability : CoreAbility.getAbilities()) { + for (final CoreAbility ability : PASSIVES.values()) { if (ability instanceof PassiveAbility) { if (!hasPassive(player, ability)) { continue; @@ -37,13 +37,16 @@ public static void registerPassives(Player player) { * here. This just enables the passive to be displayed in /b * d [element]passive */ - } else if (!((PassiveAbility) ability).isInstantiable()) { + } + + if (!((PassiveAbility) ability).isInstantiable()) { continue; } + try { - Class clazz = PASSIVE_CLASSES.get((PassiveAbility) ability); - Constructor constructor = clazz.getConstructor(Player.class); - Object object = constructor.newInstance(new Object[] { player }); + final Class clazz = PASSIVE_CLASSES.get(ability); + final Constructor constructor = clazz.getConstructor(Player.class); + final Object object = constructor.newInstance(player); ((CoreAbility) object).start(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { @@ -53,13 +56,13 @@ public static void registerPassives(Player player) { } } - public static boolean hasPassive(Player player, CoreAbility passive) { + public static boolean hasPassive(final Player player, final CoreAbility passive) { if (player == null) { return false; } else if (passive == null) { return false; } - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); Element element = passive.getElement(); if (passive.getElement() instanceof SubElement) { element = ((SubElement) passive.getElement()).getParentElement(); @@ -70,7 +73,7 @@ public static boolean hasPassive(Player player, CoreAbility passive) { return false; } else if (!passive.isEnabled()) { return false; - } else if (!bPlayer.canBendPassive(passive.getElement())) { + } else if (!bPlayer.canBendPassive(passive)) { return false; } else if (!bPlayer.isToggled()) { return false; @@ -80,13 +83,13 @@ public static boolean hasPassive(Player player, CoreAbility passive) { return true; } - public static Set getPassivesForElement(Element element) { - Set passives = new HashSet<>(); - for (CoreAbility passive : PASSIVES.values()) { + public static Set getPassivesForElement(final Element element) { + final Set passives = new HashSet<>(); + for (final CoreAbility passive : PASSIVES.values()) { if (passive.getElement() == element) { passives.add(passive.getName()); } else if (passive.getElement() instanceof SubElement) { - Element check = ((SubElement)passive.getElement()).getParentElement(); + final Element check = ((SubElement) passive.getElement()).getParentElement(); if (check == element) { passives.add(passive.getName()); } diff --git a/src/com/projectkorra/projectkorra/airbending/AirBlast.java b/src/com/projectkorra/projectkorra/airbending/AirBlast.java index 3daf3dff0..0ade5ca71 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirBlast.java +++ b/src/com/projectkorra/projectkorra/airbending/AirBlast.java @@ -9,7 +9,6 @@ import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; @@ -17,6 +16,7 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.material.Button; +import org.bukkit.material.Door; import org.bukkit.material.Lever; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; @@ -25,13 +25,12 @@ import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; +import com.projectkorra.projectkorra.earthbending.lava.LavaFlow; import com.projectkorra.projectkorra.object.HorizontalVelocityTracker; import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.Flight; import com.projectkorra.projectkorra.util.TempBlock; public class AirBlast extends AirAbility { @@ -70,38 +69,38 @@ public class AirBlast extends AirAbility { private ArrayList affectedLevers; private ArrayList affectedEntities; - public AirBlast(Player player) { + public AirBlast(final Player player) { super(player); - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } else if (player.getEyeLocation().getBlock().isLiquid()) { return; } - setFields(); + this.setFields(); if (ORIGINS.containsKey(player)) { - Entity entity = GeneralMethods.getTargetedEntity(player, range); + final Entity entity = GeneralMethods.getTargetedEntity(player, this.range); this.isFromOtherOrigin = true; this.origin = ORIGINS.get(player); ORIGINS.remove(player); if (entity != null) { - this.direction = GeneralMethods.getDirection(origin, entity.getLocation()).normalize(); + this.direction = GeneralMethods.getDirection(this.origin, entity.getLocation()).normalize(); } else { - this.direction = GeneralMethods.getDirection(origin, GeneralMethods.getTargetedLocation(player, range)).normalize(); + this.direction = GeneralMethods.getDirection(this.origin, GeneralMethods.getTargetedLocation(player, this.range)).normalize(); } } else { - origin = player.getEyeLocation(); - direction = player.getEyeLocation().getDirection().normalize(); + this.origin = player.getEyeLocation(); + this.direction = player.getEyeLocation().getDirection().normalize(); } - this.location = origin.clone(); - bPlayer.addCooldown(this); - start(); + this.location = this.origin.clone(); + this.bPlayer.addCooldown(this); + this.start(); } - public AirBlast(Player player, Location location, Vector direction, double modifiedPushFactor, AirBurst burst) { + public AirBlast(final Player player, final Location location, final Vector direction, final double modifiedPushFactor, final AirBurst burst) { super(player); if (location.getBlock().isLiquid()) { return; @@ -111,23 +110,24 @@ public AirBlast(Player player, Location location, Vector direction, double modif this.direction = direction.clone(); this.location = location.clone(); - setFields(); - + this.setFields(); + this.affectedLevers = new ArrayList<>(); this.affectedEntities = new ArrayList<>(); - //prevent the airburst related airblasts from triggering doors/levers/buttons + + // prevent the airburst related airblasts from triggering doors/levers/buttons. this.canOpenDoors = false; this.canPressButtons = false; this.canFlickLevers = false; - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.pushFactor = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirBlast.Push.Self"); this.pushFactorForOthers = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirBlast.Push.Entities"); } - + this.pushFactor *= modifiedPushFactor; - start(); + this.start(); } private void setFields() { @@ -151,13 +151,13 @@ private void setFields() { this.affectedEntities = new ArrayList<>(); } - private static void playOriginEffect(Player player) { + private static void playOriginEffect(final Player player) { if (!ORIGINS.containsKey(player)) { return; } - Location origin = ORIGINS.get(player); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Location origin = ORIGINS.get(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null || player.isDead() || !player.isOnline()) { return; } else if (!origin.getWorld().equals(player.getWorld())) { @@ -175,13 +175,13 @@ private static void playOriginEffect(Player player) { } public static void progressOrigins() { - for (Player player : ORIGINS.keySet()) { + for (final Player player : ORIGINS.keySet()) { playOriginEffect(player); } } - public static void setOrigin(Player player) { - Location location = GeneralMethods.getTargetedLocation(player, getSelectRange(), getTransparentMaterials()); + public static void setOrigin(final Player player) { + final Location location = GeneralMethods.getTargetedLocation(player, getSelectRange(), getTransparentMaterials()); if (location.getBlock().isLiquid() || GeneralMethods.isSolid(location.getBlock())) { return; } else if (GeneralMethods.isRegionProtectedFromBuild(player, "AirBlast", location)) { @@ -193,25 +193,30 @@ public static void setOrigin(Player player) { } private void advanceLocation() { - if (showParticles) { - playAirbendingParticles(location, particles, 0.275F, 0.275F, 0.275F); + if (this.showParticles) { + playAirbendingParticles(this.location, this.particles, 0.275F, 0.275F, 0.275F); } - if (random.nextInt(4) == 0) { - playAirbendingSound(location); + if (this.random.nextInt(4) == 0) { + playAirbendingSound(this.location); } - location = location.add(direction.clone().multiply(speedFactor)); + if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { + this.remove(); + return; + } + + this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); } - private void affect(Entity entity) { - boolean isUser = entity.getUniqueId() == player.getUniqueId(); + private void affect(final Entity entity) { + final boolean isUser = entity.getUniqueId() == this.player.getUniqueId(); - if (!isUser || isFromOtherOrigin) { - pushFactor = pushFactorForOthers; - Vector velocity = entity.getVelocity(); - double max = speed / speedFactor; - double factor = pushFactor; + if (!isUser || this.isFromOtherOrigin) { + this.pushFactor = this.pushFactorForOthers; + final Vector velocity = entity.getVelocity(); + final double max = this.speed / this.speedFactor; + double factor = this.pushFactor; - Vector push = direction.clone(); + final Vector push = this.direction.clone(); if (Math.abs(push.getY()) > max && !isUser) { if (push.getY() < 0) { push.setY(-max); @@ -219,15 +224,15 @@ private void affect(Entity entity) { push.setY(max); } } - if (location.getWorld().equals(origin.getWorld())) { - factor *= 1 - location.distance(origin) / (2 * range); + if (this.location.getWorld().equals(this.origin.getWorld())) { + factor *= 1 - this.location.distance(this.origin) / (2 * this.range); } - if (isUser && GeneralMethods.isSolid(player.getLocation().add(0, -.5, 0).getBlock())) { + if (isUser && GeneralMethods.isSolid(this.player.getLocation().add(0, -.5, 0).getBlock())) { factor *= .5; } - double comp = velocity.dot(push.clone().normalize()); + final double comp = velocity.dot(push.clone().normalize()); if (comp > factor) { velocity.multiply(.5); velocity.add(push.clone().normalize().multiply(velocity.clone().dot(push.clone().normalize()))); @@ -248,14 +253,14 @@ private void affect(Entity entity) { } GeneralMethods.setVelocity(entity, velocity); - if (source != null) { - new HorizontalVelocityTracker(entity, player, 200l, CoreAbility.getAbility("AirBurst")); + if (this.source != null) { + new HorizontalVelocityTracker(entity, this.player, 200l, this.source); } else { - new HorizontalVelocityTracker(entity, player, 200l, this); + new HorizontalVelocityTracker(entity, this.player, 200l, this); } if (!isUser && entity instanceof Player) { - new Flight((Player) entity, player); + ProjectKorra.flightHandler.createInstance((Player) entity, this.player, 1000L, this.getName()); } if (entity.getFireTicks() > 0) { entity.getWorld().playEffect(entity.getLocation(), Effect.EXTINGUISH, 0); @@ -264,37 +269,36 @@ private void affect(Entity entity) { entity.setFireTicks(0); breakBreathbendingHold(entity); - if (source != null && (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(player) && !affectedEntities.contains(entity))) { - DamageHandler.damageEntity((LivingEntity) entity, damage, CoreAbility.getAbility("AirBurst")); - affectedEntities.add(entity); - } else if (source == null && (damage > 0 && entity instanceof LivingEntity && !entity.equals(player) && !affectedEntities.contains(entity))) { - DamageHandler.damageEntity((LivingEntity) entity, damage, this); - affectedEntities.add(entity); + if (this.source != null && (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(this.player) && !this.affectedEntities.contains(entity))) { + DamageHandler.damageEntity(entity, this.damage, this.source); + this.affectedEntities.add(entity); + } else if (this.source == null && (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(this.player) && !this.affectedEntities.contains(entity))) { + DamageHandler.damageEntity(entity, this.damage, this); + this.affectedEntities.add(entity); } } } - @SuppressWarnings("deprecation") @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } - speedFactor = speed * (ProjectKorra.time_step / 1000.0); - ticks++; + this.speedFactor = this.speed * (ProjectKorra.time_step / 1000.0); + this.ticks++; - if (ticks > MAX_TICKS) { - remove(); + if (this.ticks > MAX_TICKS) { + this.remove(); return; } - Block block = location.getBlock(); - for (Block testblock : GeneralMethods.getBlocksAroundPoint(location, radius)) { + Block block = this.location.getBlock(); + for (final Block testblock : GeneralMethods.getBlocksAroundPoint(this.location, this.radius)) { if (testblock.getType() == Material.FIRE) { testblock.setType(Material.AIR); testblock.getWorld().playEffect(testblock.getLocation(), Effect.EXTINGUISH, 0); @@ -303,110 +307,112 @@ public void progress() { continue; } - Material doorTypes[] = { Material.WOODEN_DOOR, Material.SPRUCE_DOOR, Material.BIRCH_DOOR, Material.JUNGLE_DOOR, Material.ACACIA_DOOR, Material.DARK_OAK_DOOR }; - if (Arrays.asList(doorTypes).contains(block.getType()) && canOpenDoors) { - if (block.getData() >= 8) { + final Material doorTypes[] = { Material.WOODEN_DOOR, Material.SPRUCE_DOOR, Material.BIRCH_DOOR, Material.JUNGLE_DOOR, Material.ACACIA_DOOR, Material.DARK_OAK_DOOR, Material.TRAP_DOOR }; + if (Arrays.asList(doorTypes).contains(block.getType()) && !this.affectedLevers.contains(block) && this.canOpenDoors) { + if (block.getData() >= 8 && block.getType() != Material.TRAP_DOOR) { block = block.getRelative(BlockFace.DOWN); } - if (block.getData() < 4) { - block.setData((byte) (block.getData() + 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_WOODEN_DOOR_CLOSE, 10, 1); - } else { - block.setData((byte) (block.getData() - 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_WOODEN_DOOR_OPEN, 10, 1); - } + this.handleDoorMechanics(block); } - if ((block.getType() == Material.LEVER) && !affectedLevers.contains(block) && canFlickLevers) { - Lever lever = new Lever(Material.LEVER, block.getData()); + if ((block.getType() == Material.LEVER) && !this.affectedLevers.contains(block) && this.canFlickLevers) { + final Lever lever = new Lever(Material.LEVER, block.getData()); lever.setPowered(!lever.isPowered()); block.setData(lever.getData()); - Block supportBlock = block.getRelative(lever.getAttachedFace()); + final Block supportBlock = block.getRelative(lever.getAttachedFace()); if (supportBlock != null && supportBlock.getType() != Material.AIR) { - BlockState initialSupportState = supportBlock.getState(); - BlockState supportState = supportBlock.getState(); + final BlockState initialSupportState = supportBlock.getState(); + final BlockState supportState = supportBlock.getState(); supportState.setType(Material.AIR); supportState.update(true, false); initialSupportState.update(true); } - affectedLevers.add(block); - } else if ((block.getType() == Material.STONE_BUTTON) && !affectedLevers.contains(block) && canPressButtons) { + this.affectedLevers.add(block); + } else if ((block.getType() == Material.STONE_BUTTON) && !this.affectedLevers.contains(block) && this.canPressButtons) { final Button button = new Button(Material.STONE_BUTTON, block.getData()); - button.setPowered(!button.isPowered()); - block.setData(button.getData()); - - Block supportBlock = block.getRelative(button.getAttachedFace()); - if (supportBlock != null && supportBlock.getType() != Material.AIR) { - BlockState initialSupportState = supportBlock.getState(); - BlockState supportState = supportBlock.getState(); - supportState.setType(Material.AIR); - supportState.update(true, false); - initialSupportState.update(true); - } - - final Block btBlock = block; - new BukkitRunnable() { - public void run() { - button.setPowered(!button.isPowered()); - btBlock.setData(button.getData()); - - Block supportBlock = btBlock.getRelative(button.getAttachedFace()); - if (supportBlock != null && supportBlock.getType() != Material.AIR) { - BlockState initialSupportState = supportBlock.getState(); - BlockState supportState = supportBlock.getState(); - supportState.setType(Material.AIR); - supportState.update(true, false); - initialSupportState.update(true); - } + if (!button.isPowered()) { + button.setPowered(!button.isPowered()); + block.setData(button.getData()); + + final Block supportBlock = block.getRelative(button.getAttachedFace()); + if (supportBlock != null && supportBlock.getType() != Material.AIR) { + final BlockState initialSupportState = supportBlock.getState(); + final BlockState supportState = supportBlock.getState(); + supportState.setType(Material.AIR); + supportState.update(true, false); + initialSupportState.update(true); } - }.runTaskLater(ProjectKorra.plugin, 10); - affectedLevers.add(block); - } else if ((block.getType() == Material.WOOD_BUTTON) && !affectedLevers.contains(block) && canPressButtons) { - final Button button = new Button(Material.WOOD_BUTTON, block.getData()); - button.setPowered(!button.isPowered()); - block.setData(button.getData()); + final Block btBlock = block; + new BukkitRunnable() { + @Override + public void run() { + button.setPowered(!button.isPowered()); + btBlock.setData(button.getData()); + + final Block supportBlock = btBlock.getRelative(button.getAttachedFace()); + if (supportBlock != null && supportBlock.getType() != Material.AIR) { + final BlockState initialSupportState = supportBlock.getState(); + final BlockState supportState = supportBlock.getState(); + supportState.setType(Material.AIR); + supportState.update(true, false); + initialSupportState.update(true); + } + } + }.runTaskLater(ProjectKorra.plugin, 10); - Block supportBlock = block.getRelative(button.getAttachedFace()); - if (supportBlock != null && supportBlock.getType() != Material.AIR) { - BlockState initialSupportState = supportBlock.getState(); - BlockState supportState = supportBlock.getState(); - supportState.setType(Material.AIR); - supportState.update(true, false); - initialSupportState.update(true); + this.affectedLevers.add(block); } + } else if ((block.getType() == Material.WOOD_BUTTON) && !this.affectedLevers.contains(block) && this.canPressButtons) { + final Button button = new Button(Material.WOOD_BUTTON, block.getData()); + if (!button.isPowered()) { + button.setPowered(!button.isPowered()); + block.setData(button.getData()); + + final Block supportBlock = block.getRelative(button.getAttachedFace()); + if (supportBlock != null && supportBlock.getType() != Material.AIR) { + final BlockState initialSupportState = supportBlock.getState(); + final BlockState supportState = supportBlock.getState(); + supportState.setType(Material.AIR); + supportState.update(true, false); + initialSupportState.update(true); + } - final Block btBlock = block; - - new BukkitRunnable() { - public void run() { - button.setPowered(!button.isPowered()); - btBlock.setData(button.getData()); - - Block supportBlock = btBlock.getRelative(button.getAttachedFace()); - if (supportBlock != null && supportBlock.getType() != Material.AIR) { - BlockState initialSupportState = supportBlock.getState(); - BlockState supportState = supportBlock.getState(); - supportState.setType(Material.AIR); - supportState.update(true, false); - initialSupportState.update(true); + final Block btBlock = block; + + new BukkitRunnable() { + @Override + public void run() { + button.setPowered(!button.isPowered()); + btBlock.setData(button.getData()); + + final Block supportBlock = btBlock.getRelative(button.getAttachedFace()); + if (supportBlock != null && supportBlock.getType() != Material.AIR) { + final BlockState initialSupportState = supportBlock.getState(); + final BlockState supportState = supportBlock.getState(); + supportState.setType(Material.AIR); + supportState.update(true, false); + initialSupportState.update(true); + } } - } - }.runTaskLater(ProjectKorra.plugin, 15); + }.runTaskLater(ProjectKorra.plugin, 15); - affectedLevers.add(block); + this.affectedLevers.add(block); + } } } - if ((GeneralMethods.isSolid(block) || block.isLiquid()) && !affectedLevers.contains(block) && canCoolLava) { + if ((GeneralMethods.isSolid(block) || block.isLiquid()) && !this.affectedLevers.contains(block) && this.canCoolLava) { if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) { - if (block.getData() == 0x0) { + if (LavaFlow.isLavaFlowBlock(block)) { + LavaFlow.removeBlock(block); // TODO: Make more generic for future lava generating moves. + } else if (block.getData() == 0x0) { new TempBlock(block, Material.OBSIDIAN, (byte) 0); } else { - new TempBlock(block, Material.COBBLESTONE, (byte)0); + new TempBlock(block, Material.COBBLESTONE, (byte) 0); } } - remove(); + this.remove(); return; } @@ -417,19 +423,19 @@ public void run() { * never be removed. */ double dist = 0; - if (location.getWorld().equals(origin.getWorld())) { - dist = location.distance(origin); + if (this.location.getWorld().equals(this.origin.getWorld())) { + dist = this.location.distance(this.origin); } - if (Double.isNaN(dist) || dist > range) { - remove(); + if (Double.isNaN(dist) || dist > this.range) { + this.remove(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, radius)) { - affect(entity); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.radius)) { + this.affect(entity); } - advanceLocation(); + this.advanceLocation(); return; } @@ -438,10 +444,10 @@ public void run() { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeAirBlastsAroundPoint(Location location, double radius) { + public static boolean removeAirBlastsAroundPoint(final Location location, final double radius) { boolean removed = false; - for (AirBlast airBlast : getAbilities(AirBlast.class)) { - Location airBlastlocation = airBlast.location; + for (final AirBlast airBlast : getAbilities(AirBlast.class)) { + final Location airBlastlocation = airBlast.location; if (location.getWorld() == airBlastlocation.getWorld()) { if (location.distanceSquared(airBlastlocation) <= radius * radius) { airBlast.remove(); @@ -452,6 +458,52 @@ public static boolean removeAirBlastsAroundPoint(Location location, double radiu return removed; } + private void handleDoorMechanics(final Block block) { + boolean tDoor = false; + final boolean open = (block.getData() & 0x4) == 0x4; + + if (block.getType() != Material.TRAP_DOOR) { + final Door door = (Door) block.getState().getData(); + final BlockFace face = door.getFacing(); + final Vector toPlayer = GeneralMethods.getDirection(block.getLocation(), this.player.getLocation().getBlock().getLocation()); + final double[] dims = { toPlayer.getX(), toPlayer.getY(), toPlayer.getZ() }; + + for (int i = 0; i < 3; i++) { + if (i == 1) { + continue; + } + final BlockFace bf = GeneralMethods.getBlockFaceFromValue(i, dims[i]); + + if (bf == face) { + if (open) { + return; + } + } else if (bf.getOppositeFace() == face) { + if (!open) { + return; + } + } + } + } else { + tDoor = true; + + if (this.origin.getY() < block.getY()) { + if (!open) { + return; + } + } else { + if (open) { + return; + } + } + } + + block.setData((byte) ((block.getData() & 0x4) == 0x4 ? (block.getData() & ~0x4) : (block.getData() | 0x4))); + final String sound = "BLOCK_WOODEN_" + (tDoor ? "TRAP" : "") + "DOOR_" + (!open ? "OPEN" : "CLOSE"); + block.getWorld().playSound(block.getLocation(), sound, 0.5f, 0); + this.affectedLevers.add(block); + } + @Override public String getName() { return "AirBlast"; @@ -459,12 +511,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -479,166 +531,166 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public int getTicks() { - return ticks; + return this.ticks; } - public void setTicks(int ticks) { + public void setTicks(final int ticks) { this.ticks = ticks; } public double getSpeedFactor() { - return speedFactor; + return this.speedFactor; } - public void setSpeedFactor(double speedFactor) { + public void setSpeedFactor(final double speedFactor) { this.speedFactor = speedFactor; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getPushFactorForOthers() { - return pushFactorForOthers; + return this.pushFactorForOthers; } - public void setPushFactorForOthers(double pushFactorForOthers) { + public void setPushFactorForOthers(final double pushFactorForOthers) { this.pushFactorForOthers = pushFactorForOthers; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public boolean isCanFlickLevers() { - return canFlickLevers; + return this.canFlickLevers; } - public void setCanFlickLevers(boolean canFlickLevers) { + public void setCanFlickLevers(final boolean canFlickLevers) { this.canFlickLevers = canFlickLevers; } public boolean isCanOpenDoors() { - return canOpenDoors; + return this.canOpenDoors; } - public void setCanOpenDoors(boolean canOpenDoors) { + public void setCanOpenDoors(final boolean canOpenDoors) { this.canOpenDoors = canOpenDoors; } public boolean isCanPressButtons() { - return canPressButtons; + return this.canPressButtons; } - public void setCanPressButtons(boolean canPressButtons) { + public void setCanPressButtons(final boolean canPressButtons) { this.canPressButtons = canPressButtons; } public boolean isCanCoolLava() { - return canCoolLava; + return this.canCoolLava; } - public void setCanCoolLava(boolean canCoolLava) { + public void setCanCoolLava(final boolean canCoolLava) { this.canCoolLava = canCoolLava; } public boolean isFromOtherOrigin() { - return isFromOtherOrigin; + return this.isFromOtherOrigin; } - public void setFromOtherOrigin(boolean isFromOtherOrigin) { + public void setFromOtherOrigin(final boolean isFromOtherOrigin) { this.isFromOtherOrigin = isFromOtherOrigin; } public boolean isShowParticles() { - return showParticles; + return this.showParticles; } - public void setShowParticles(boolean showParticles) { + public void setShowParticles(final boolean showParticles) { this.showParticles = showParticles; } public AirBurst getSource() { - return source; + return this.source; } - public void setSource(AirBurst source) { + public void setSource(final AirBurst source) { this.source = source; } public ArrayList getAffectedLevers() { - return affectedLevers; + return this.affectedLevers; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } public int getParticles() { - return particles; + return this.particles; } - public void setParticles(int particles) { + public void setParticles(final int particles) { this.particles = particles; } diff --git a/src/com/projectkorra/projectkorra/airbending/AirBurst.java b/src/com/projectkorra/projectkorra/airbending/AirBurst.java index 2dc248ff1..da40b3bd7 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirBurst.java +++ b/src/com/projectkorra/projectkorra/airbending/AirBurst.java @@ -21,6 +21,7 @@ public class AirBurst extends AirAbility { private float playerFallDistance; @Attribute(Attribute.CHARGE_DURATION) private long chargeTime; + private long cooldown; private double fallThreshold; @Attribute(Attribute.POWER) private double pushFactor; @@ -32,10 +33,10 @@ public class AirBurst extends AirAbility { private ArrayList blasts; private ArrayList affectedEntities; - public AirBurst(Player player, boolean isFallBurst) { + public AirBurst(final Player player, final boolean isFallBurst) { super(player); - if (bPlayer.isOnCooldown(this)) { - remove(); + if (this.bPlayer.isOnCooldown(this)) { + this.remove(); return; } if (hasAbility(player, AirBurst.class)) { @@ -48,6 +49,7 @@ public AirBurst(Player player, boolean isFallBurst) { this.isCharged = false; this.playerFallDistance = player.getFallDistance(); this.chargeTime = getConfig().getLong("Abilities.Air.AirBurst.ChargeTime"); + this.cooldown = getConfig().getLong("Abilities.Air.AirBurst.Cooldown"); this.fallThreshold = getConfig().getDouble("Abilities.Air.AirBurst.FallThreshold"); this.pushFactor = getConfig().getDouble("Abilities.Air.AirBurst.PushFactor"); this.damage = getConfig().getDouble("Abilities.Air.AirBurst.Damage"); @@ -58,103 +60,105 @@ public AirBurst(Player player, boolean isFallBurst) { this.blasts = new ArrayList<>(); this.affectedEntities = new ArrayList<>(); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Air.AirBurst.ChargeTime"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirBurst.Damage"); } - start(); + this.start(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } - if (isFallBurst) { - if (playerFallDistance >= fallThreshold) { - fallBurst(); + if (this.isFallBurst) { + if (this.playerFallDistance >= this.fallThreshold) { + this.fallBurst(); + this.bPlayer.addCooldown(this); } - remove(); + this.remove(); return; } - if (System.currentTimeMillis() > getStartTime() + chargeTime && !isCharged) { - isCharged = true; + if (System.currentTimeMillis() > this.getStartTime() + this.chargeTime && !this.isCharged) { + this.isCharged = true; } - if (!player.isSneaking()) { - if (isCharged) { - sphereBurst(); - remove(); + if (!this.player.isSneaking()) { + if (this.isCharged) { + this.bPlayer.addCooldown(this); + this.sphereBurst(); + this.remove(); return; } else { - remove(); + this.remove(); return; } - } else if (isCharged) { - Location location = player.getEyeLocation(); - playAirbendingParticles(location, sneakParticles); + } else if (this.isCharged) { + final Location location = this.player.getEyeLocation(); + playAirbendingParticles(location, this.sneakParticles); } } private void fallBurst() { - if (bPlayer.isOnCooldown("AirBurst")) { + if (this.bPlayer.isOnCooldown("AirBurst")) { return; } - Location location = player.getLocation(); + final Location location = this.player.getLocation(); double x, y, z; - double r = 1; + final double r = 1; - for (double theta = 75; theta < 105; theta += blastAngleTheta) { - double dphi = blastAnglePhi / Math.sin(Math.toRadians(theta)); + for (double theta = 75; theta < 105; theta += this.blastAngleTheta) { + final double dphi = this.blastAnglePhi / Math.sin(Math.toRadians(theta)); for (double phi = 0; phi < 360; phi += dphi) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); x = r * Math.cos(rphi) * Math.sin(rtheta); y = r * Math.sin(rphi) * Math.sin(rtheta); z = r * Math.cos(rtheta); - Vector direction = new Vector(x, z, y); - AirBlast blast = new AirBlast(player, location, direction.normalize(), pushFactor, this); - blast.setDamage(damage); + final Vector direction = new Vector(x, z, y); + final AirBlast blast = new AirBlast(this.player, location, direction.normalize(), this.pushFactor, this); + blast.setDamage(this.damage); } } } - public static void coneBurst(Player player) { + public static void coneBurst(final Player player) { if (hasAbility(player, AirBurst.class)) { - AirBurst airBurst = getAbility(player, AirBurst.class); + final AirBurst airBurst = getAbility(player, AirBurst.class); airBurst.startConeBurst(); airBurst.remove(); } } private void startConeBurst() { - if (isCharged) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - double angle = Math.toRadians(30); + if (this.isCharged) { + final Location location = this.player.getEyeLocation(); + final Vector vector = location.getDirection(); + final double angle = Math.toRadians(30); double x, y, z; - double r = 1; + final double r = 1; - for (double theta = 0; theta <= 180; theta += blastAngleTheta) { - double dphi = blastAnglePhi / Math.sin(Math.toRadians(theta)); + for (double theta = 0; theta <= 180; theta += this.blastAngleTheta) { + final double dphi = this.blastAnglePhi / Math.sin(Math.toRadians(theta)); for (double phi = 0; phi < 360; phi += dphi) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); x = r * Math.cos(rphi) * Math.sin(rtheta); y = r * Math.sin(rphi) * Math.sin(rtheta); z = r * Math.cos(rtheta); - Vector direction = new Vector(x, z, y); + final Vector direction = new Vector(x, z, y); if (direction.angle(vector) <= angle) { - AirBlast blast = new AirBlast(player, location, direction.normalize(), pushFactor, this); - blast.setDamage(damage); + final AirBlast blast = new AirBlast(this.player, location, direction.normalize(), this.pushFactor, this); + blast.setDamage(this.damage); } } } @@ -162,14 +166,15 @@ private void startConeBurst() { } public void handleSmoothParticles() { - for (int i = 0; i < blasts.size(); i++) { - final AirBlast blast = blasts.get(i); + for (int i = 0; i < this.blasts.size(); i++) { + final AirBlast blast = this.blasts.get(i); int toggleTime = 0; if (i % 4 != 0) { - toggleTime = (int) (i % (100 / particlePercentage)) + 3; + toggleTime = (int) (i % (100 / this.particlePercentage)) + 3; } new BukkitRunnable() { + @Override public void run() { blast.setShowParticles(true); } @@ -178,32 +183,32 @@ public void run() { } private void sphereBurst() { - if (isCharged) { - Location location = player.getEyeLocation(); + if (this.isCharged) { + final Location location = this.player.getEyeLocation(); double x, y, z; - double r = 1; + final double r = 1; - for (double theta = 0; theta <= 180; theta += blastAngleTheta) { - double dphi = blastAnglePhi / Math.sin(Math.toRadians(theta)); + for (double theta = 0; theta <= 180; theta += this.blastAngleTheta) { + final double dphi = this.blastAnglePhi / Math.sin(Math.toRadians(theta)); for (double phi = 0; phi < 360; phi += dphi) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); x = r * Math.cos(rphi) * Math.sin(rtheta); y = r * Math.sin(rphi) * Math.sin(rtheta); z = r * Math.cos(rtheta); - Vector direction = new Vector(x, z, y); - AirBlast blast = new AirBlast(player, location, direction.normalize(), pushFactor, this); + final Vector direction = new Vector(x, z, y); + final AirBlast blast = new AirBlast(this.player, location, direction.normalize(), this.pushFactor, this); - blast.setDamage(damage); + blast.setDamage(this.damage); blast.setShowParticles(false); - blasts.add(blast); + this.blasts.add(blast); } } } - handleSmoothParticles(); + this.handleSmoothParticles(); } @Override @@ -213,12 +218,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return 0; + return this.cooldown; } @Override @@ -233,90 +238,90 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (AirBlast blast : blasts) { + final ArrayList locations = new ArrayList<>(); + for (final AirBlast blast : this.blasts) { locations.add(blast.getLocation()); } return locations; } - public void addAffectedEntity(Entity entity) { - affectedEntities.add(entity); + public void addAffectedEntity(final Entity entity) { + this.affectedEntities.add(entity); } - public boolean isAffectedEntity(Entity entity) { - return affectedEntities.contains(entity); + public boolean isAffectedEntity(final Entity entity) { + return this.affectedEntities.contains(entity); } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public double getFallThreshold() { - return fallThreshold; + return this.fallThreshold; } - public void setFallThreshold(double fallThreshold) { + public void setFallThreshold(final double fallThreshold) { this.fallThreshold = fallThreshold; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getBlastAngleTheta() { - return blastAngleTheta; + return this.blastAngleTheta; } - public void setBlastAngleTheta(double blastAngleTheta) { + public void setBlastAngleTheta(final double blastAngleTheta) { this.blastAngleTheta = blastAngleTheta; } public double getBlastAnglePhi() { - return blastAnglePhi; + return this.blastAnglePhi; } - public void setBlastAnglePhi(double blastAnglePhi) { + public void setBlastAnglePhi(final double blastAnglePhi) { this.blastAnglePhi = blastAnglePhi; } public boolean isCharged() { - return isCharged; + return this.isCharged; } - public void setCharged(boolean isCharged) { + public void setCharged(final boolean isCharged) { this.isCharged = isCharged; } public boolean isFallBurst() { - return isFallBurst; + return this.isFallBurst; } - public void setFallBurst(boolean isFallBurst) { + public void setFallBurst(final boolean isFallBurst) { this.isFallBurst = isFallBurst; } public ArrayList getBlasts() { - return blasts; + return this.blasts; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } } diff --git a/src/com/projectkorra/projectkorra/airbending/AirScooter.java b/src/com/projectkorra/projectkorra/airbending/AirScooter.java index 8027febe3..78e07ec7a 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirScooter.java +++ b/src/com/projectkorra/projectkorra/airbending/AirScooter.java @@ -11,10 +11,10 @@ import org.bukkit.util.Vector; import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.util.Flight; public class AirScooter extends AirAbility { @@ -25,38 +25,37 @@ public class AirScooter extends AirAbility { private double radius; @Attribute(Attribute.COOLDOWN) private long cooldown; + private long duration; private double maxHeightFromGround; private Block floorblock; private Random random; private ArrayList angles; - private boolean canFly; - private boolean hadFly; private double phi = 0; - public AirScooter(Player player) { + public AirScooter(final Player player) { super(player); - if (check(player)) + if (check(player)) { return; - else if (!player.isSprinting() || GeneralMethods.isSolid(player.getEyeLocation().getBlock()) || player.getEyeLocation().getBlock().isLiquid()) + } else if (!player.isSprinting() || GeneralMethods.isSolid(player.getEyeLocation().getBlock()) || player.getEyeLocation().getBlock().isLiquid()) { return; - else if (GeneralMethods.isSolid(player.getLocation().add(0, -.5, 0).getBlock())) + } else if (GeneralMethods.isSolid(player.getLocation().add(0, -.5, 0).getBlock())) { return; - else if (bPlayer.isOnCooldown(this)) + } else if (this.bPlayer.isOnCooldown(this)) { return; + } this.speed = getConfig().getDouble("Abilities.Air.AirScooter.Speed"); this.interval = getConfig().getDouble("Abilities.Air.AirScooter.Interval"); this.radius = getConfig().getDouble("Abilities.Air.AirScooter.Radius"); this.cooldown = getConfig().getLong("Abilities.Air.AirScooter.Cooldown"); + this.duration = getConfig().getLong("Abilities.Air.AirScooter.Duration"); this.maxHeightFromGround = getConfig().getDouble("Abilities.Air.AirScooter.MaxHeightFromGround"); this.random = new Random(); this.angles = new ArrayList<>(); - canFly = player.getAllowFlight(); - hadFly = player.isFlying(); - new Flight(player); + ProjectKorra.flightHandler.createInstance(player, this.getName()); player.setAllowFlight(true); player.setFlying(true); @@ -64,19 +63,19 @@ else if (bPlayer.isOnCooldown(this)) player.setSneaking(false); for (int i = 0; i < 5; i++) { - angles.add((double) (60 * i)); + this.angles.add((double) (60 * i)); } - start(); + this.start(); } /** * Checks if player has an instance already and removes if they do. - * + * * @param player The player to check * @return false If player doesn't have an instance */ - public static boolean check(Player player) { + public static boolean check(final Player player) { if (hasAbility(player, AirScooter.class)) { getAbility(player, AirScooter.class).remove(); return true; @@ -89,11 +88,11 @@ public static boolean check(Player player) { * the player if it within the maximum height */ private void getFloor() { - floorblock = null; - for (int i = 0; i <= maxHeightFromGround; i++) { - Block block = player.getEyeLocation().getBlock().getRelative(BlockFace.DOWN, i); + this.floorblock = null; + for (int i = 0; i <= this.maxHeightFromGround; i++) { + final Block block = this.player.getEyeLocation().getBlock().getRelative(BlockFace.DOWN, i); if (GeneralMethods.isSolid(block) || block.isLiquid()) { - floorblock = block; + this.floorblock = block; return; } } @@ -101,41 +100,45 @@ private void getFloor() { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); + return; + } else if (this.duration != 0 && System.currentTimeMillis() > this.getStartTime() + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - getFloor(); - if (floorblock == null) { - remove(); + this.getFloor(); + if (this.floorblock == null) { + this.remove(); return; } - if (player.isSneaking()) { - bPlayer.addCooldown(this); - remove(); + if (this.player.isSneaking()) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - Vector velocity = player.getEyeLocation().getDirection().clone().normalize(); - velocity = velocity.clone().normalize().multiply(speed); + Vector velocity = this.player.getEyeLocation().getDirection().clone().normalize(); + velocity = velocity.clone().normalize().multiply(this.speed); /* * checks the players speed and ends the move if they are going too slow */ - if (System.currentTimeMillis() > getStartTime() + interval) { - if (player.getVelocity().length() < speed * 0.3) { - remove(); + if (System.currentTimeMillis() > this.getStartTime() + this.interval) { + if (this.player.getVelocity().length() < this.speed * 0.3) { + this.remove(); return; } - spinScooter(); + this.spinScooter(); } /* * Checks for how far the ground is away from the player it elevates or * lowers the player based on their distance from the ground. */ - double distance = player.getLocation().getY() - (double) floorblock.getY(); - double dx = Math.abs(distance - 2.4); + final double distance = this.player.getLocation().getY() - this.floorblock.getY(); + final double dx = Math.abs(distance - 2.4); if (distance > 2.75) { velocity.setY(-.25 * dx * dx); } else if (distance < 2) { @@ -143,28 +146,28 @@ public void progress() { } else { velocity.setY(0); } - - Vector v = velocity.clone().setY(0); - Block b = floorblock.getLocation().clone().add(v.multiply(1.2)).getBlock(); + + final Vector v = velocity.clone().setY(0); + final Block b = this.floorblock.getLocation().clone().add(v.multiply(1.2)).getBlock(); if (!GeneralMethods.isSolid(b) && !b.isLiquid()) { velocity.add(new Vector(0, -0.6, 0)); } else if (GeneralMethods.isSolid(b.getRelative(BlockFace.UP)) || b.getRelative(BlockFace.UP).isLiquid()) { velocity.add(new Vector(0, 1.0, 0)); } - Location loc = player.getLocation(); - if (!WaterAbility.isWater(player.getLocation().add(0, 2, 0).getBlock())) { - loc.setY((double) floorblock.getY() + 1.5); + final Location loc = this.player.getLocation(); + if (!ElementalAbility.isWater(this.player.getLocation().add(0, 2, 0).getBlock())) { + loc.setY(this.floorblock.getY() + 1.5); } else { return; } - player.setSprinting(false); - player.removePotionEffect(PotionEffectType.SPEED); - player.setVelocity(velocity); + this.player.setSprinting(false); + this.player.removePotionEffect(PotionEffectType.SPEED); + this.player.setVelocity(velocity); - if (random.nextInt(4) == 0) { - playAirbendingSound(player.getLocation()); + if (this.random.nextInt(4) == 0) { + playAirbendingSound(this.player.getLocation()); } } @@ -174,9 +177,8 @@ public void progress() { @Override public void remove() { super.remove(); - player.setAllowFlight(canFly); - player.setFlying(hadFly); - bPlayer.addCooldown(this); + ProjectKorra.flightHandler.removeInstance(this.player, this.getName()); + this.bPlayer.addCooldown(this); } /* @@ -184,23 +186,23 @@ public void remove() { * sphere has. theta = how dense the rings are. r = Radius of the sphere */ private void spinScooter() { - Location origin = player.getLocation(); - Location origin2 = player.getLocation(); - phi += Math.PI / 10 * 4; + final Location origin = this.player.getLocation(); + final Location origin2 = this.player.getLocation(); + this.phi += Math.PI / 10 * 4; for (double theta = 0; theta <= 2 * Math.PI; theta += Math.PI / 10) { - double r = 0.6; - double x = r * Math.cos(theta) * Math.sin(phi); - double y = r * Math.cos(phi); - double z = r * Math.sin(theta) * Math.sin(phi); + final double r = 0.6; + final double x = r * Math.cos(theta) * Math.sin(this.phi); + final double y = r * Math.cos(this.phi); + final double z = r * Math.sin(theta) * Math.sin(this.phi); origin.add(x, y, z); playAirbendingParticles(origin, 1, 0F, 0F, 0F); origin.subtract(x, y, z); } for (double theta = 0; theta <= 2 * Math.PI; theta += Math.PI / 10) { - double r = 0.6; - double x = r * Math.cos(theta) * Math.sin(phi); - double y = r * Math.cos(phi); - double z = r * Math.sin(theta) * Math.sin(phi); + final double r = 0.6; + final double x = r * Math.cos(theta) * Math.sin(this.phi); + final double y = r * Math.cos(this.phi); + final double z = r * Math.sin(theta) * Math.sin(this.phi); origin2.subtract(x, y, z); playAirbendingParticles(origin2, 1, 0F, 0F, 0F); origin2.add(x, y, z); @@ -214,12 +216,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -234,50 +236,50 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getInterval() { - return interval; + return this.interval; } - public void setInterval(double interval) { + public void setInterval(final double interval) { this.interval = interval; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getMaxHeightFromGround() { - return maxHeightFromGround; + return this.maxHeightFromGround; } - public void setMaxHeightFromGround(double maxHeightFromGround) { + public void setMaxHeightFromGround(final double maxHeightFromGround) { this.maxHeightFromGround = maxHeightFromGround; } public Block getFloorblock() { - return floorblock; + return this.floorblock; } - public void setFloorblock(Block floorblock) { + public void setFloorblock(final Block floorblock) { this.floorblock = floorblock; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } } diff --git a/src/com/projectkorra/projectkorra/airbending/AirShield.java b/src/com/projectkorra/projectkorra/airbending/AirShield.java index 4c7e23d55..8596c690b 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirShield.java +++ b/src/com/projectkorra/projectkorra/airbending/AirShield.java @@ -29,40 +29,42 @@ public class AirShield extends AirAbility { @Attribute(Attribute.SPEED) private double speed; private int streams; - private long cooldown; private int particles; + private long cooldown; + private long duration; private Random random; private HashMap angles; - public AirShield(Player player) { + public AirShield(final Player player) { super(player); - + this.maxRadius = getConfig().getDouble("Abilities.Air.AirShield.Radius"); this.isToggledByAvatarState = getConfig().getBoolean("Abilities.Avatar.AvatarState.Air.AirShield.IsAvatarStateToggle"); this.radius = this.maxRadius; this.cooldown = getConfig().getLong("Abilities.Air.AirShield.Cooldown"); + this.duration = getConfig().getLong("Abilities.Air.AirShield.Duration"); this.speed = getConfig().getDouble("Abilities.Air.AirShield.Speed"); this.streams = getConfig().getInt("Abilities.Air.AirShield.Streams"); this.particles = getConfig().getInt("Abilities.Air.AirShield.Particles"); this.random = new Random(); this.angles = new HashMap<>(); - if (bPlayer.isAvatarState() && hasAbility(player, AirShield.class) && isToggledByAvatarState) { + if (this.bPlayer.isAvatarState() && hasAbility(player, AirShield.class) && this.isToggledByAvatarState) { getAbility(player, AirShield.class).remove(); return; } int angle = 0; - int di = (int) (maxRadius * 2 / streams); - for (int i = -(int) maxRadius + di; i < (int) maxRadius; i += di) { - angles.put(i, angle); + final int di = (int) (this.maxRadius * 2 / this.streams); + for (int i = -(int) this.maxRadius + di; i < (int) this.maxRadius; i += di) { + this.angles.put(i, angle); angle += 90; if (angle == 360) { angle = 0; } } - - start(); + + this.start(); } /** @@ -70,8 +72,8 @@ public AirShield(Player player) { * {@link Collision} for the new system. */ @Deprecated - public static boolean isWithinShield(Location loc) { - for (AirShield ashield : getAbilities(AirShield.class)) { + public static boolean isWithinShield(final Location loc) { + for (final AirShield ashield : getAbilities(AirShield.class)) { if (!ashield.player.getWorld().equals(loc.getWorld())) { return false; } else if (ashield.player.getLocation().distanceSquared(loc) <= ashield.radius * ashield.radius) { @@ -83,27 +85,34 @@ public static boolean isWithinShield(Location loc) { @Override public void progress() { - // AvatarState can use AirShield even when AirShield is not in the bound slot - if (player.getEyeLocation().getBlock().isLiquid()) { - remove(); + // AvatarState can use AirShield even when AirShield is not in the bound slot. + if (this.player.getEyeLocation().getBlock().isLiquid()) { + this.remove(); return; - } else if (!bPlayer.isAvatarState() || !isToggledByAvatarState) { - if (!player.isSneaking() || !bPlayer.canBend(this)) { - bPlayer.addCooldown(this); - remove(); + } else if (!this.bPlayer.isAvatarState() || !this.isToggledByAvatarState) { + if (!this.player.isSneaking() || !this.bPlayer.canBend(this)) { + this.bPlayer.addCooldown(this); + this.remove(); return; + } else if (this.duration != 0) { + if (this.getStartTime() + this.duration <= System.currentTimeMillis()) { + this.bPlayer.addCooldown(this); + this.remove(); + return; + } } - } else if (!bPlayer.canBendIgnoreBinds(this)) { - remove(); + + } else if (!this.bPlayer.canBendIgnoreBinds(this)) { + this.remove(); return; } - rotateShield(); + this.rotateShield(); } private void rotateShield() { - Location origin = player.getLocation(); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(origin, radius)) { - if (GeneralMethods.isRegionProtectedFromBuild(player, "AirShield", entity.getLocation())) { + final Location origin = this.player.getLocation(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(origin, this.radius)) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, "AirShield", entity.getLocation())) { continue; } if (origin.distanceSquared(entity.getLocation()) > 4) { @@ -119,8 +128,8 @@ private void rotateShield() { vx = (x * Math.cos(angle) - z * Math.sin(angle)) / mag; vz = (x * Math.sin(angle) + z * Math.cos(angle)) / mag; - Vector velocity = entity.getVelocity(); - if (bPlayer.isAvatarState()) { + final Vector velocity = entity.getVelocity(); + if (this.bPlayer.isAvatarState()) { velocity.setX(AvatarState.getValue(vx)); velocity.setZ(AvatarState.getValue(vz)); } else { @@ -140,41 +149,41 @@ private void rotateShield() { } } - for (Block testblock : GeneralMethods.getBlocksAroundPoint(player.getLocation(), radius)) { + for (final Block testblock : GeneralMethods.getBlocksAroundPoint(this.player.getLocation(), this.radius)) { if (testblock.getType() == Material.FIRE) { testblock.setType(Material.AIR); testblock.getWorld().playEffect(testblock.getLocation(), Effect.EXTINGUISH, 0); } } - Set keys = angles.keySet(); - for (int i : keys) { + final Set keys = this.angles.keySet(); + for (final int i : keys) { double x, y, z; - double factor = radius / maxRadius; - double angle = (double) angles.get(i); + final double factor = this.radius / this.maxRadius; + double angle = this.angles.get(i); angle = Math.toRadians(angle); - y = origin.getY() + factor * (double) i; - double f = Math.sqrt(1 - factor * factor * ((double) i / radius) * ((double) i / radius)); + y = origin.getY() + factor * i; + final double f = Math.sqrt(1 - factor * factor * (i / this.radius) * (i / this.radius)); - x = origin.getX() + radius * Math.cos(angle) * f; - z = origin.getZ() + radius * Math.sin(angle) * f; + x = origin.getX() + this.radius * Math.cos(angle) * f; + z = origin.getZ() + this.radius * Math.sin(angle) * f; - Location effect = new Location(origin.getWorld(), x, y, z); + final Location effect = new Location(origin.getWorld(), x, y, z); if (!GeneralMethods.isRegionProtectedFromBuild(this, effect)) { - playAirbendingParticles(effect, particles); - if (random.nextInt(4) == 0) { + playAirbendingParticles(effect, this.particles); + if (this.random.nextInt(4) == 0) { playAirbendingSound(effect); } } - angles.put(i, angles.get(i) + (int) (speed)); + this.angles.put(i, this.angles.get(i) + (int) (this.speed)); } - if (radius < maxRadius) { - radius += .3; + if (this.radius < this.maxRadius) { + this.radius += .3; } - if (radius > maxRadius) { - radius = maxRadius; + if (this.radius > this.maxRadius) { + this.radius = this.maxRadius; } } @@ -185,12 +194,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -205,58 +214,58 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public boolean isToggledByAvatarState() { - return isToggledByAvatarState; + return this.isToggledByAvatarState; } - public void setToggledByAvatarState(boolean isToggledByAvatarState) { + public void setToggledByAvatarState(final boolean isToggledByAvatarState) { this.isToggledByAvatarState = isToggledByAvatarState; } public double getMaxRadius() { - return maxRadius; + return this.maxRadius; } - public void setMaxRadius(double maxRadius) { + public void setMaxRadius(final double maxRadius) { this.maxRadius = maxRadius; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public int getStreams() { - return streams; + return this.streams; } - public void setStreams(int streams) { + public void setStreams(final int streams) { this.streams = streams; } public int getParticles() { - return particles; + return this.particles; } - public void setParticles(int particles) { + public void setParticles(final int particles) { this.particles = particles; } public HashMap getAngles() { - return angles; + return this.angles; } } diff --git a/src/com/projectkorra/projectkorra/airbending/AirSpout.java b/src/com/projectkorra/projectkorra/airbending/AirSpout.java index 70fd50db3..84ab40fe1 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirSpout.java +++ b/src/com/projectkorra/projectkorra/airbending/AirSpout.java @@ -10,10 +10,10 @@ import org.bukkit.entity.Player; import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.AirAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.util.Flight; public class AirSpout extends AirAbility { @@ -22,43 +22,44 @@ public class AirSpout extends AirAbility { private int angle; private long animTime; private long interval; + private long duration; @Attribute(Attribute.COOLDOWN) private long cooldown; @Attribute(Attribute.HEIGHT) private double height; - public AirSpout(Player player) { + public AirSpout(final Player player) { super(player); - AirSpout spout = getAbility(player, AirSpout.class); + final AirSpout spout = getAbility(player, AirSpout.class); if (spout != null) { spout.remove(); return; } - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { return; } this.angle = 0; this.cooldown = getConfig().getLong("Abilities.Air.AirSpout.Cooldown"); + this.duration = getConfig().getLong("Abilities.Air.AirSpout.Duration"); this.animTime = System.currentTimeMillis(); this.interval = getConfig().getLong("Abilities.Air.AirSpout.Interval"); this.height = getConfig().getDouble("Abilities.Air.AirSpout.Height"); - double heightRemoveThreshold = 2; - if (!isWithinMaxSpoutHeight(heightRemoveThreshold)) { + final double heightRemoveThreshold = 2; + if (!this.isWithinMaxSpoutHeight(heightRemoveThreshold)) { return; } - new Flight(player); + ProjectKorra.flightHandler.createInstance(player, this.getName()); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.height = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSpout.Height"); } - start(); + this.start(); } /** @@ -66,17 +67,17 @@ public AirSpout(Player player) { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeSpouts(Location loc0, double radius, Player sourceplayer) { + public static boolean removeSpouts(Location loc0, final double radius, final Player sourceplayer) { boolean removed = false; - for (AirSpout spout : getAbilities(AirSpout.class)) { + for (final AirSpout spout : getAbilities(AirSpout.class)) { if (!spout.player.equals(sourceplayer)) { - Location loc1 = spout.player.getLocation().getBlock().getLocation(); + final Location loc1 = spout.player.getLocation().getBlock().getLocation(); loc0 = loc0.getBlock().getLocation(); - double dx = loc1.getX() - loc0.getX(); - double dy = loc1.getY() - loc0.getY(); - double dz = loc1.getZ() - loc0.getZ(); + final double dx = loc1.getX() - loc0.getX(); + final double dy = loc1.getY() - loc0.getY(); + final double dz = loc1.getZ() - loc0.getZ(); - double distance = Math.sqrt(dx * dx + dz * dz); + final double distance = Math.sqrt(dx * dx + dz * dz); if (distance <= radius && dy > 0 && dy < spout.height) { spout.remove(); @@ -88,26 +89,26 @@ public static boolean removeSpouts(Location loc0, double radius, Player sourcepl } private void allowFlight() { - player.setAllowFlight(true); - player.setFlying(true); + this.player.setAllowFlight(true); + this.player.setFlying(true); } - private boolean isWithinMaxSpoutHeight(double threshold) { - Block ground = getGround(); + private boolean isWithinMaxSpoutHeight(final double threshold) { + final Block ground = this.getGround(); if (ground == null) { return false; } - double playerHeight = player.getLocation().getY(); - if (playerHeight > ground.getLocation().getY() + height + threshold) { + final double playerHeight = this.player.getLocation().getY(); + if (playerHeight > ground.getLocation().getY() + this.height + threshold) { return false; } return true; } private Block getGround() { - Block standingblock = player.getLocation().getBlock(); - for (int i = 0; i <= height + 5; i++) { - Block block = standingblock.getRelative(BlockFace.DOWN, i); + final Block standingblock = this.player.getLocation().getBlock(); + for (int i = 0; i <= this.height + 5; i++) { + final Block block = standingblock.getRelative(BlockFace.DOWN, i); if (GeneralMethods.isSolid(block) || block.isLiquid()) { return block; } @@ -117,72 +118,76 @@ private Block getGround() { @Override public void progress() { - if (player.isDead() || !player.isOnline() || !bPlayer.canBendIgnoreBinds(this) || !bPlayer.canBind(this)) { - remove(); + if (this.player.isDead() || !this.player.isOnline() || !this.bPlayer.canBendIgnoreBinds(this) || !this.bPlayer.canBind(this)) { + this.remove(); + return; + } else if (this.duration != 0 && System.currentTimeMillis() > this.getStartTime() + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - double heightRemoveThreshold = 2; - if (!isWithinMaxSpoutHeight(heightRemoveThreshold)) { - remove(); + final double heightRemoveThreshold = 2; + if (!this.isWithinMaxSpoutHeight(heightRemoveThreshold)) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - - Block eyeBlock = player.getEyeLocation().getBlock(); + final Block eyeBlock = this.player.getEyeLocation().getBlock(); if (eyeBlock.isLiquid() || GeneralMethods.isSolid(eyeBlock)) { - remove(); + this.remove(); return; } - player.setFallDistance(0); - player.setSprinting(false); + this.player.setFallDistance(0); + this.player.setSprinting(false); if ((new Random()).nextInt(4) == 0) { - playAirbendingSound(player.getLocation()); + playAirbendingSound(this.player.getLocation()); } - Block block = getGround(); + final Block block = this.getGround(); if (block != null) { - double dy = player.getLocation().getY() - block.getY(); - if (dy > height) { - removeFlight(); + final double dy = this.player.getLocation().getY() - block.getY(); + if (dy > this.height) { + this.removeFlight(); } else { - allowFlight(); + this.allowFlight(); } - rotateAirColumn(block); - } else { - remove(); + this.rotateAirColumn(block); + } else { + this.remove(); } } + @Override public void remove() { super.remove(); - removeFlight(); - bPlayer.addCooldown(this); + ProjectKorra.flightHandler.removeInstance(this.player, this.getName()); } private void removeFlight() { - player.setAllowFlight(false); - player.setFlying(false); + this.player.setAllowFlight(false); + this.player.setFlying(false); } - private void rotateAirColumn(Block block) { - if (!player.getWorld().equals(block.getWorld())) { + private void rotateAirColumn(final Block block) { + if (!this.player.getWorld().equals(block.getWorld())) { return; } - if (System.currentTimeMillis() >= animTime + interval) { - animTime = System.currentTimeMillis(); + if (System.currentTimeMillis() >= this.animTime + this.interval) { + this.animTime = System.currentTimeMillis(); Location location = block.getLocation(); - Location playerloc = player.getLocation(); + final Location playerloc = this.player.getLocation(); location = new Location(location.getWorld(), playerloc.getX(), location.getY(), playerloc.getZ()); - int index = angle; - double dy = Math.min(playerloc.getY() - block.getY(), height); - angle = angle >= DIRECTIONS.length ? 0 : angle + 1; + int index = this.angle; + final double dy = Math.min(playerloc.getY() - block.getY(), this.height); + this.angle = this.angle >= DIRECTIONS.length ? 0 : this.angle + 1; for (int i = 1; i <= dy; i++) { index = index >= DIRECTIONS.length ? 0 : index + 1; - Location effectloc2 = new Location(location.getWorld(), location.getX(), block.getY() + i, location.getZ()); + final Location effectloc2 = new Location(location.getWorld(), location.getX(), block.getY() + i, location.getZ()); playAirbendingParticles(effectloc2, 3, 0.4F, 0.4F, 0.4F); } } @@ -195,12 +200,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -220,48 +225,48 @@ public boolean isCollidable() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - Location topLoc = player.getLocation().getBlock().getLocation(); - double ySpacing = 3; - for (double i = 0; i <= height; i += ySpacing) { + final ArrayList locations = new ArrayList<>(); + final Location topLoc = this.player.getLocation().getBlock().getLocation(); + final double ySpacing = 3; + for (double i = 0; i <= this.height; i += ySpacing) { locations.add(topLoc.clone().add(0, -i, 0)); } return locations; } public int getAngle() { - return angle; + return this.angle; } - public void setAngle(int angle) { + public void setAngle(final int angle) { this.angle = angle; } public long getAnimTime() { - return animTime; + return this.animTime; } - public void setAnimTime(long animTime) { + public void setAnimTime(final long animTime) { this.animTime = animTime; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getHeight() { - return height; + return this.height; } - public void setHeight(double height) { + public void setHeight(final double height) { this.height = height; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/airbending/AirSuction.java b/src/com/projectkorra/projectkorra/airbending/AirSuction.java index 5cff90a23..cc985257e 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirSuction.java +++ b/src/com/projectkorra/projectkorra/airbending/AirSuction.java @@ -1,13 +1,20 @@ package com.projectkorra.projectkorra.airbending; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.bukkit.material.Door; import org.bukkit.util.Vector; import com.projectkorra.projectkorra.BendingPlayer; @@ -18,13 +25,14 @@ import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; import com.projectkorra.projectkorra.object.HorizontalVelocityTracker; -import com.projectkorra.projectkorra.util.Flight; import com.projectkorra.projectkorra.waterbending.WaterSpout; public class AirSuction extends AirAbility { private static final int MAX_TICKS = 10000; private static final Map ORIGINS = new ConcurrentHashMap<>(); + private static Material doorTypes[] = { Material.WOODEN_DOOR, Material.SPRUCE_DOOR, Material.BIRCH_DOOR, Material.JUNGLE_DOOR, Material.ACACIA_DOOR, Material.DARK_OAK_DOOR, Material.TRAP_DOOR }; + private final List affectedDoors = new ArrayList<>(); private boolean hasOtherOrigin; private int ticks; @@ -44,10 +52,10 @@ public class AirSuction extends AirAbility { private Location origin; private Vector direction; - public AirSuction(Player player) { + public AirSuction(final Player player) { super(player); - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } else if (player.getEyeLocation().getBlock().isLiquid()) { return; @@ -66,36 +74,36 @@ public AirSuction(Player player) { this.random = new Random(); if (ORIGINS.containsKey(player)) { - origin = ORIGINS.get(player); - hasOtherOrigin = true; + this.origin = ORIGINS.get(player); + this.hasOtherOrigin = true; ORIGINS.remove(player); } else { - origin = player.getEyeLocation(); + this.origin = player.getEyeLocation(); } - location = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterials()); - direction = GeneralMethods.getDirection(location, origin).normalize(); - Entity entity = GeneralMethods.getTargetedEntity(player, range); + this.location = GeneralMethods.getTargetedLocation(player, this.range, getTransparentMaterials()); + this.direction = GeneralMethods.getDirection(this.location, this.origin).normalize(); + final Entity entity = GeneralMethods.getTargetedEntity(player, this.range); if (entity != null) { - direction = GeneralMethods.getDirection(entity.getLocation(), origin).normalize(); - location = getLocation(origin, direction.clone().multiply(-1)); + this.direction = GeneralMethods.getDirection(entity.getLocation(), this.origin).normalize(); + this.location = this.getLocation(this.origin, this.direction.clone().multiply(-1)); } - bPlayer.addCooldown(this); - if (bPlayer.isAvatarState()) { + this.bPlayer.addCooldown(this); + if (this.bPlayer.isAvatarState()) { this.pushFactor = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSuction.Push"); } - start(); + this.start(); } - private static void playOriginEffect(Player player) { + private static void playOriginEffect(final Player player) { if (!ORIGINS.containsKey(player)) { return; } - Location origin = ORIGINS.get(player); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final Location origin = ORIGINS.get(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null || player.isDead() || !player.isOnline()) { return; } else if (!origin.getWorld().equals(player.getWorld())) { @@ -113,13 +121,21 @@ private static void playOriginEffect(Player player) { } public static void progressOrigins() { - for (Player player : ORIGINS.keySet()) { + for (final Player player : ORIGINS.keySet()) { playOriginEffect(player); } } - public static void setOrigin(Player player) { - Location location = GeneralMethods.getTargetedLocation(player, getSelectRange(), getTransparentMaterials()); + public static void setOrigin(final Player player) { + final Material[] ignore = new Material[getTransparentMaterials().length + doorTypes.length]; + for (int i = 0; i < ignore.length; i++) { + if (i < getTransparentMaterials().length) { + ignore[i] = getTransparentMaterials()[i]; + } else { + ignore[i] = doorTypes[i - getTransparentMaterials().length]; + } + } + final Location location = GeneralMethods.getTargetedLocation(player, getSelectRange(), ignore); if (location.getBlock().isLiquid() || GeneralMethods.isSolid(location.getBlock())) { return; } else if (GeneralMethods.isRegionProtectedFromBuild(player, "AirSuction", location)) { @@ -130,19 +146,69 @@ public static void setOrigin(Player player) { } private void advanceLocation() { - playAirbendingParticles(location, particleCount, 0.275F, 0.275F, 0.275F); - if (random.nextInt(4) == 0) { - playAirbendingSound(location); + playAirbendingParticles(this.location, this.particleCount, 0.275F, 0.275F, 0.275F); + if (this.random.nextInt(4) == 0) { + playAirbendingSound(this.location); + } + final double speedFactor = this.speed * (ProjectKorra.time_step / 1000.); + this.location = this.location.add(this.direction.clone().multiply(speedFactor)); + + if (Arrays.asList(doorTypes).contains(this.location.getBlock().getType()) && !this.affectedDoors.contains(this.location.getBlock())) { + this.handleDoorMechanics(this.location.getBlock()); } - double speedFactor = speed * (ProjectKorra.time_step / 1000.); - location = location.add(direction.clone().multiply(speedFactor)); } - private Location getLocation(Location origin, Vector direction) { + private void handleDoorMechanics(final Block block) { + boolean tDoor = false; + final boolean open = (block.getData() & 0x4) == 0x4; + + if (block.getType() != Material.TRAP_DOOR) { + final Door door = (Door) block.getState().getData(); + final BlockFace face = door.getFacing(); + final Vector toPlayer = GeneralMethods.getDirection(block.getLocation(), this.player.getLocation().getBlock().getLocation()); + final double[] dims = { toPlayer.getX(), toPlayer.getY(), toPlayer.getZ() }; + + for (int i = 0; i < 3; i++) { + if (i == 1) { + continue; + } + final BlockFace bf = GeneralMethods.getBlockFaceFromValue(i, dims[i]); + + if (bf == face) { + if (!open) { + return; + } + } else if (bf.getOppositeFace() == face) { + if (open) { + return; + } + } + } + } else { + tDoor = true; + + if (this.origin.getY() < block.getY()) { + if (open) { + return; + } + } else { + if (!open) { + return; + } + } + } + + block.setData((byte) ((block.getData() & 0x4) == 0x4 ? (block.getData() & ~0x4) : (block.getData() | 0x4))); + final String sound = "BLOCK_WOODEN_" + (tDoor ? "TRAP" : "") + "DOOR_" + (!open ? "OPEN" : "CLOSE"); + block.getWorld().playSound(block.getLocation(), sound, 0.5f, 0); + this.affectedDoors.add(block); + } + + private Location getLocation(final Location origin, final Vector direction) { Location location = origin.clone(); - for (double i = 1; i <= range; i++) { + for (double i = 1; i <= this.range; i++) { location = origin.clone().add(direction.clone().multiply(i)); - if (!isTransparent(location.getBlock()) || GeneralMethods.isRegionProtectedFromBuild(this, location)) { + if ((!this.isTransparent(location.getBlock()) && !Arrays.asList(doorTypes).contains(location.getBlock().getType())) || GeneralMethods.isRegionProtectedFromBuild(this, location)) { return origin.clone().add(direction.clone().multiply(i - 1)); } } @@ -151,42 +217,42 @@ private Location getLocation(Location origin, Vector direction) { @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(player, "AirSuction", location)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this.player, "AirSuction", this.location)) { + this.remove(); return; } - ticks++; - if (ticks > MAX_TICKS) { - remove(); + this.ticks++; + if (this.ticks > MAX_TICKS) { + this.remove(); return; - } else if ((location.distanceSquared(origin) > range * range) || (location.distanceSquared(origin) <= 1)) { - remove(); + } else if ((this.location.distanceSquared(this.origin) > this.range * this.range) || (this.location.distanceSquared(this.origin) <= 1)) { + this.remove(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, radius)) { - if (entity.getEntityId() != player.getEntityId() || hasOtherOrigin) { - Vector velocity = entity.getVelocity(); - double max = speed; - double factor = pushFactor; + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.radius)) { + if (entity.getEntityId() != this.player.getEntityId() || this.hasOtherOrigin) { + final Vector velocity = entity.getVelocity(); + final double max = this.speed; + double factor = this.pushFactor; - Vector push = direction.clone(); - if (Math.abs(push.getY()) > max && entity.getEntityId() != player.getEntityId()) { + final Vector push = this.direction.clone(); + if (Math.abs(push.getY()) > max && entity.getEntityId() != this.player.getEntityId()) { if (push.getY() < 0) { push.setY(-max); } else { push.setY(max); } } - if (location.getWorld().equals(origin.getWorld())) { - factor *= 1 - location.distance(origin) / (2 * range); + if (this.location.getWorld().equals(this.origin.getWorld())) { + factor *= 1 - this.location.distance(this.origin) / (2 * this.range); } - double comp = velocity.dot(push.clone().normalize()); + final double comp = velocity.dot(push.clone().normalize()); if (comp > factor) { velocity.multiply(.5); velocity.add(push.clone().normalize().multiply(velocity.clone().dot(push.clone().normalize()))); @@ -203,10 +269,10 @@ public void progress() { } GeneralMethods.setVelocity(entity, velocity); - new HorizontalVelocityTracker(entity, player, 200l, this); + new HorizontalVelocityTracker(entity, this.player, 200l, this); entity.setFallDistance(0); - if (entity.getEntityId() != player.getEntityId() && entity instanceof Player) { - new Flight((Player) entity, player); + if (entity.getEntityId() != this.player.getEntityId() && entity instanceof Player) { + ProjectKorra.flightHandler.createInstance((Player) entity, this.player, 5000L, this.getName()); } if (entity.getFireTicks() > 0) { @@ -217,7 +283,7 @@ public void progress() { } } - advanceLocation(); + this.advanceLocation(); } /** @@ -225,10 +291,10 @@ public void progress() { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeAirSuctionsAroundPoint(Location location, double radius) { + public static boolean removeAirSuctionsAroundPoint(final Location location, final double radius) { boolean removed = false; - for (AirSuction airSuction : getAbilities(AirSuction.class)) { - Location airSuctionlocation = airSuction.location; + for (final AirSuction airSuction : getAbilities(AirSuction.class)) { + final Location airSuctionlocation = airSuction.location; if (location.getWorld() == airSuctionlocation.getWorld()) { if (location.distanceSquared(airSuctionlocation) <= radius * radius) { airSuction.remove(); @@ -246,12 +312,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -266,86 +332,86 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public boolean isHasOtherOrigin() { - return hasOtherOrigin; + return this.hasOtherOrigin; } - public void setHasOtherOrigin(boolean hasOtherOrigin) { + public void setHasOtherOrigin(final boolean hasOtherOrigin) { this.hasOtherOrigin = hasOtherOrigin; } public int getTicks() { - return ticks; + return this.ticks; } - public void setTicks(int ticks) { + public void setTicks(final int ticks) { this.ticks = ticks; } public int getParticleCount() { - return particleCount; + return this.particleCount; } - public void setParticleCount(int particleCount) { + public void setParticleCount(final int particleCount) { this.particleCount = particleCount; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/airbending/AirSwipe.java b/src/com/projectkorra/projectkorra/airbending/AirSwipe.java index b767cfd26..aaa556b34 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirSwipe.java +++ b/src/com/projectkorra/projectkorra/airbending/AirSwipe.java @@ -1,7 +1,6 @@ package com.projectkorra.projectkorra.airbending; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; @@ -20,19 +19,18 @@ import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.AirAbility; import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.firebending.Illumination; +import com.projectkorra.projectkorra.earthbending.lava.LavaFlow; import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.Flight; +import com.projectkorra.projectkorra.util.TempBlock; public class AirSwipe extends AirAbility { - // Limiting the entities reduces the risk of crashing + // Limiting the entities reduces the risk of crashing. private static final int MAX_AFFECTABLE_ENTITIES = 10; - private static final Integer[] BREAKABLES = { 6, 31, 32, 37, 38, 39, 40, 59, 81, 83, 106, 175 }; private boolean charging; private int arc; @@ -58,15 +56,15 @@ public class AirSwipe extends AirAbility { private Map elements; private ArrayList affectedEntities; - public AirSwipe(Player player) { + public AirSwipe(final Player player) { this(player, false); } - public AirSwipe(Player player, boolean charging) { + public AirSwipe(final Player player, final boolean charging) { super(player); if (CoreAbility.hasAbility(player, AirSwipe.class)) { - for (AirSwipe ability : CoreAbility.getAbilities(player, AirSwipe.class)) { + for (final AirSwipe ability : CoreAbility.getAbilities(player, AirSwipe.class)) { if (ability.charging) { ability.launch(); ability.charging = false; @@ -92,27 +90,29 @@ public AirSwipe(Player player, boolean charging) { this.elements = new ConcurrentHashMap<>(); this.affectedEntities = new ArrayList<>(); - if (bPlayer.isOnCooldown(this) || player.getEyeLocation().getBlock().isLiquid()) { - remove(); + if (this.bPlayer.isOnCooldown(this) || player.getEyeLocation().getBlock().isLiquid()) { + this.remove(); return; } - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } if (!charging) { - launch(); + this.launch(); } - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Air.AirSwipe.Cooldown"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSwipe.Damage"); this.pushFactor = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSwipe.Push"); + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSwipe.Range"); + this.radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSwipe.Radius"); } - start(); + this.start(); } /** @@ -120,11 +120,11 @@ public AirSwipe(Player player, boolean charging) { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeSwipesAroundPoint(Location loc, double radius) { + public static boolean removeSwipesAroundPoint(final Location loc, final double radius) { boolean removed = false; - for (AirSwipe aswipe : getAbilities(AirSwipe.class)) { - for (Vector vec : aswipe.elements.keySet()) { - Location vectorLoc = aswipe.elements.get(vec); + for (final AirSwipe aswipe : getAbilities(AirSwipe.class)) { + for (final Vector vec : aswipe.elements.keySet()) { + final Location vectorLoc = aswipe.elements.get(vec); if (vectorLoc != null && vectorLoc.getWorld().equals(loc.getWorld())) { if (vectorLoc.distanceSquared(loc) <= radius * radius) { aswipe.remove(); @@ -136,78 +136,73 @@ public static boolean removeSwipesAroundPoint(Location loc, double radius) { return removed; } - @SuppressWarnings("deprecation") private void advanceSwipe() { - affectedEntities.clear(); - for (Vector direction : elements.keySet()) { - Location location = elements.get(direction); + this.affectedEntities.clear(); + for (final Vector direction : this.elements.keySet()) { + Location location = this.elements.get(direction); if (direction != null && location != null) { - location = location.clone().add(direction.clone().multiply(speed)); - elements.put(direction, location); + location = location.clone().add(direction.clone().multiply(this.speed)); + this.elements.put(direction, location); - if (location.distanceSquared(origin) > range * range || GeneralMethods.isRegionProtectedFromBuild(this, location)) { - elements.clear(); + if (location.distanceSquared(this.origin) > this.range * this.range || GeneralMethods.isRegionProtectedFromBuild(this, location)) { + this.elements.clear(); } else { - Block block = location.getBlock(); - if (!EarthAbility.isTransparent(player, block)) { - remove(); + final Block block = location.getBlock(); + if (!ElementalAbility.isTransparent(this.player, block)) { + this.remove(); return; } - for (Block testblock : GeneralMethods.getBlocksAroundPoint(location, radius)) { + for (final Block testblock : GeneralMethods.getBlocksAroundPoint(location, this.radius)) { if (testblock.getType() == Material.FIRE) { testblock.setType(Material.AIR); } - if (isBlockBreakable(testblock)) { - GeneralMethods.breakBlock(testblock); - } } if (block.getType() != Material.AIR) { - if (isBlockBreakable(block)) { - GeneralMethods.breakBlock(block); - } if (block.getType().equals(Material.SNOW)) { continue; } else { - - elements.remove(direction); + this.elements.remove(direction); } if (isLava(block)) { - if (block.getData() == 0x0) { - block.setType(Material.OBSIDIAN); + if (LavaFlow.isLavaFlowBlock(block)) { + LavaFlow.removeBlock(block); // TODO: Make more generic for future lava generating moves. + } else if (block.getData() == 0x0) { + new TempBlock(block, Material.OBSIDIAN, (byte) 0); } else { - block.setType(Material.COBBLESTONE); + new TempBlock(block, Material.COBBLESTONE, (byte) 0); } } } else { - playAirbendingParticles(location, particles, 0.2F, 0.2F, 0); - if (random.nextInt(4) == 0) { + playAirbendingParticles(location, this.particles, 0.2F, 0.2F, 0); + if (this.random.nextInt(4) == 0) { playAirbendingSound(location); } - affectPeople(location, direction); + this.affectPeople(location, direction); } } } } - if (elements.isEmpty()) { - remove(); + if (this.elements.isEmpty()) { + this.remove(); } } - private void affectPeople(Location location, Vector direction) { - final List entities = GeneralMethods.getEntitiesAroundPoint(location, radius); + private void affectPeople(final Location location, final Vector direction) { + final List entities = GeneralMethods.getEntitiesAroundPoint(location, this.radius); final Vector fDirection = direction; for (int i = 0; i < entities.size(); i++) { final Entity entity = entities.get(i); final AirSwipe abil = this; new BukkitRunnable() { + @Override public void run() { if (GeneralMethods.isRegionProtectedFromBuild(AirSwipe.this, entity.getLocation())) { return; } - if (entity.getEntityId() != player.getEntityId() && entity instanceof LivingEntity) { + if (entity.getEntityId() != AirSwipe.this.player.getEntityId() && entity instanceof LivingEntity) { if (entity instanceof Player) { if (Commands.invincible.contains(((Player) entity).getName())) { return; @@ -215,25 +210,25 @@ public void run() { } if (entities.size() < MAX_AFFECTABLE_ENTITIES) { - GeneralMethods.setVelocity(entity, fDirection.multiply(pushFactor)); + GeneralMethods.setVelocity(entity, fDirection.multiply(AirSwipe.this.pushFactor)); } - if (entity instanceof LivingEntity && !affectedEntities.contains(entity)) { - if (damage != 0) { - DamageHandler.damageEntity(entity, damage, abil); + if (entity instanceof LivingEntity && !AirSwipe.this.affectedEntities.contains(entity)) { + if (AirSwipe.this.damage != 0) { + DamageHandler.damageEntity(entity, AirSwipe.this.damage, abil); } - affectedEntities.add(entity); + AirSwipe.this.affectedEntities.add(entity); } if (entity instanceof Player) { - new Flight((Player) entity, player); + ProjectKorra.flightHandler.createInstance((Player) entity, AirSwipe.this.player, 1000L, AirSwipe.this.getName()); } breakBreathbendingHold(entity); - if (elements.containsKey(fDirection)) { - elements.remove(fDirection); + if (AirSwipe.this.elements.containsKey(fDirection)) { + AirSwipe.this.elements.remove(fDirection); } - } else if (entity.getEntityId() != player.getEntityId() && !(entity instanceof LivingEntity)) { + } else if (entity.getEntityId() != AirSwipe.this.player.getEntityId() && !(entity instanceof LivingEntity)) { - GeneralMethods.setVelocity(entity, fDirection.multiply(pushFactor)); + GeneralMethods.setVelocity(entity, fDirection.multiply(AirSwipe.this.pushFactor)); } } @@ -241,21 +236,12 @@ public void run() { } } - @SuppressWarnings("deprecation") - private boolean isBlockBreakable(Block block) { - Integer id = block.getTypeId(); - if (Arrays.asList(BREAKABLES).contains(id) && !Illumination.getBlocks().containsKey(block)) { - return true; - } - return false; - } - private void launch() { - bPlayer.addCooldown("AirSwipe", cooldown); - origin = player.getEyeLocation(); - for (double i = -arc; i <= arc; i += stepSize) { - double angle = Math.toRadians((double) i); - Vector direction = player.getEyeLocation().getDirection().clone(); + this.bPlayer.addCooldown("AirSwipe", this.cooldown); + this.origin = this.player.getEyeLocation(); + for (double i = -this.arc; i <= this.arc; i += this.stepSize) { + final double angle = Math.toRadians(i); + final Vector direction = this.player.getEyeLocation().getDirection().clone(); double x, z, vx, vz; x = direction.getX(); @@ -267,43 +253,44 @@ private void launch() { direction.setX(vx); direction.setZ(vz); - elements.put(direction, origin); + this.elements.put(direction, this.origin); } } + @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; } - if (!charging) { - if (elements.isEmpty()) { - remove(); + if (!this.charging) { + if (this.elements.isEmpty()) { + this.remove(); return; } - advanceSwipe(); + this.advanceSwipe(); } else { - if (!player.isSneaking()) { + if (!this.player.isSneaking()) { double factor = 1; - if (System.currentTimeMillis() >= getStartTime() + maxChargeTime) { - factor = maxChargeFactor; + if (System.currentTimeMillis() >= this.getStartTime() + this.maxChargeTime) { + factor = this.maxChargeFactor; } else { - factor = maxChargeFactor * (double) (System.currentTimeMillis() - getStartTime()) / (double) maxChargeTime; + factor = this.maxChargeFactor * (System.currentTimeMillis() - this.getStartTime()) / this.maxChargeTime; } - charging = false; - launch(); + this.charging = false; + this.launch(); factor = Math.max(1, factor); - damage *= factor; - pushFactor *= factor; - } else if (System.currentTimeMillis() >= getStartTime() + maxChargeTime) { - playAirbendingParticles(player.getEyeLocation(), particles); + this.damage *= factor; + this.pushFactor *= factor; + } else if (System.currentTimeMillis() >= this.getStartTime() + this.maxChargeTime) { + playAirbendingParticles(this.player.getEyeLocation(), this.particles); } } } @@ -315,12 +302,12 @@ public String getName() { @Override public Location getLocation() { - return elements.size() != 0 ? elements.values().iterator().next() : null; + return this.elements.size() != 0 ? this.elements.values().iterator().next() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -335,52 +322,52 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return origin != null; + return this.origin != null; } @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (Location swipeLoc : elements.values()) { + final ArrayList locations = new ArrayList<>(); + for (final Location swipeLoc : this.elements.values()) { locations.add(swipeLoc); } return locations; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public boolean isCharging() { - return charging; + return this.charging; } - public void setCharging(boolean charging) { + public void setCharging(final boolean charging) { this.charging = charging; } public int getArc() { - return arc; + return this.arc; } - public void setArc(int arc) { + public void setArc(final int arc) { this.arc = arc; } public int getParticles() { - return particles; + return this.particles; } - public void setParticles(int particles) { + public void setParticles(final int particles) { this.particles = particles; } @@ -388,83 +375,79 @@ public static int getMaxAffectableEntities() { return MAX_AFFECTABLE_ENTITIES; } - public static Integer[] getBreakables() { - return BREAKABLES; - } - public long getMaxChargeTime() { - return maxChargeTime; + return this.maxChargeTime; } - public void setMaxChargeTime(long maxChargeTime) { + public void setMaxChargeTime(final long maxChargeTime) { this.maxChargeTime = maxChargeTime; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getMaxChargeFactor() { - return maxChargeFactor; + return this.maxChargeFactor; } - public void setMaxChargeFactor(double maxChargeFactor) { + public void setMaxChargeFactor(final double maxChargeFactor) { this.maxChargeFactor = maxChargeFactor; } public Map getElements() { - return elements; + return this.elements; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } public int getStepSize() { - return stepSize; + return this.stepSize; } - public void setStepSize(int stepSize) { + public void setStepSize(final int stepSize) { this.stepSize = stepSize; } diff --git a/src/com/projectkorra/projectkorra/airbending/Suffocate.java b/src/com/projectkorra/projectkorra/airbending/Suffocate.java index 69ddcd5ac..91eb20448 100644 --- a/src/com/projectkorra/projectkorra/airbending/Suffocate.java +++ b/src/com/projectkorra/projectkorra/airbending/Suffocate.java @@ -19,7 +19,7 @@ /** * Suffocate - * + * * Suffocate is an air ability that causes entities to be surrounded by a sphere * air that causes constant damage after a configurable delay. Suffocate also * causes Blinding and Slowing affects to entities depending on how the ability @@ -61,10 +61,10 @@ public static enum SpiralType { private ArrayList tasks; private ArrayList targets; - public Suffocate(Player player) { + public Suffocate(final Player player) { super(player); - ability = this; - if (bPlayer.isOnCooldown(this)) { + this.ability = this; + if (this.bPlayer.isOnCooldown(this)) { return; } else if (hasAbility(player, Suffocate.class)) { return; @@ -92,35 +92,34 @@ public Suffocate(Player player) { this.targets = new ArrayList<>(); this.tasks = new ArrayList<>(); - if (bPlayer.isAvatarState()) { - cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Air.Suffocate.Cooldown"); - chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Air.Suffocate.ChargeTime"); - damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Suffocate.Damage"); - range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Suffocate.Range"); + if (this.bPlayer.isAvatarState()) { + this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Air.Suffocate.Cooldown"); + this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Air.Suffocate.ChargeTime"); + this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Suffocate.Damage"); + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Suffocate.Range"); } - if (particleCount < 1) { - particleCount = 1; - } else if (particleCount > 2) { - particleCount = 2; + if (this.particleCount < 1) { + this.particleCount = 1; + } else if (this.particleCount > 2) { + this.particleCount = 2; } - if (bPlayer.isAvatarState()) { - for (Entity ent : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), range)) { + if (this.bPlayer.isAvatarState()) { + for (final Entity ent : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), this.range)) { if (ent instanceof LivingEntity && !ent.equals(player)) { - targets.add((LivingEntity) ent); + this.targets.add((LivingEntity) ent); } } } else { - //Location location = GeneralMethods.getTargetedLocation(player, 6, getTransparentMaterial()); - //List entities = GeneralMethods.getEntitiesAroundPoint(location, 1.5); List entities = new ArrayList(); for (int i = 0; i < 6; i++) { - Location location = GeneralMethods.getTargetedLocation(player, i, getTransparentMaterials()); + final Location location = GeneralMethods.getTargetedLocation(player, i, getTransparentMaterials()); entities = GeneralMethods.getEntitiesAroundPoint(location, 1.7); - if (entities.contains(player)) + if (entities.contains(player)) { entities.remove(player); + } if (entities != null && !entities.isEmpty() && !entities.contains(player)) { break; } @@ -128,111 +127,111 @@ public Suffocate(Player player) { if (entities == null || entities.isEmpty()) { return; } - Entity target = entities.get(0); + final Entity target = entities.get(0); if (target != null && target instanceof LivingEntity) { - targets.add((LivingEntity) target); + this.targets.add((LivingEntity) target); } } - if (!canSuffocateUndead) { - for (int i = 0; i < targets.size(); i++) { - LivingEntity target = targets.get(i); + if (!this.canSuffocateUndead) { + for (int i = 0; i < this.targets.size(); i++) { + final LivingEntity target = this.targets.get(i); if (GeneralMethods.isUndead(target)) { - targets.remove(i); + this.targets.remove(i); i--; } } } - bPlayer.addCooldown(this); - start(); + this.bPlayer.addCooldown(this); + this.start(); } @Override public void progress() { - for (int i = 0; i < targets.size(); i++) { - LivingEntity target = targets.get(i); - if (target.isDead() || !target.getWorld().equals(player.getWorld()) || target.getLocation().distanceSquared(player.getEyeLocation()) > range * range || GeneralMethods.isRegionProtectedFromBuild(this, target.getLocation())) { - breakSuffocateLocal(target); + for (int i = 0; i < this.targets.size(); i++) { + final LivingEntity target = this.targets.get(i); + if (target.isDead() || !target.getWorld().equals(this.player.getWorld()) || target.getLocation().distanceSquared(this.player.getEyeLocation()) > this.range * this.range || GeneralMethods.isRegionProtectedFromBuild(this, target.getLocation())) { + this.breakSuffocateLocal(target); i--; } else if (target instanceof Player) { - Player targPlayer = (Player) target; + final Player targPlayer = (Player) target; if (!targPlayer.isOnline()) { - breakSuffocateLocal(target); + this.breakSuffocateLocal(target); i--; } } } - if (targets.size() == 0 || !bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (this.targets.size() == 0 || !this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (requireConstantAim) { + if (this.requireConstantAim) { double dist = 0; - if (player.getWorld().equals(targets.get(0).getWorld())) { - dist = player.getEyeLocation().distance(targets.get(0).getEyeLocation()); + if (this.player.getWorld().equals(this.targets.get(0).getWorld())) { + dist = this.player.getEyeLocation().distance(this.targets.get(0).getEyeLocation()); } - Location targetLoc = player.getEyeLocation().clone().add(player.getEyeLocation().getDirection().normalize().multiply(dist)); - List ents = GeneralMethods.getEntitiesAroundPoint(targetLoc, constantAimRadius); + final Location targetLoc = this.player.getEyeLocation().clone().add(this.player.getEyeLocation().getDirection().normalize().multiply(dist)); + final List ents = GeneralMethods.getEntitiesAroundPoint(targetLoc, this.constantAimRadius); - for (int i = 0; i < targets.size(); i++) { - LivingEntity target = targets.get(i); + for (int i = 0; i < this.targets.size(); i++) { + final LivingEntity target = this.targets.get(i); if (!ents.contains(target)) { - breakSuffocateLocal(target); + this.breakSuffocateLocal(target); i--; } } - if (targets.size() == 0) { - remove(); + if (this.targets.size() == 0) { + this.remove(); return; } } - if (System.currentTimeMillis() - getStartTime() < chargeTime) { + if (System.currentTimeMillis() - this.getStartTime() < this.chargeTime) { return; - } else if (!started) { - started = true; - for (LivingEntity targ : targets) { + } else if (!this.started) { + this.started = true; + for (final LivingEntity targ : this.targets) { final LivingEntity target = targ; - BukkitRunnable br1 = new BukkitRunnable() { + final BukkitRunnable br1 = new BukkitRunnable() { @Override public void run() { - DamageHandler.damageEntity(target, damage, ability); + DamageHandler.damageEntity(target, Suffocate.this.damage, Suffocate.this.ability); } }; - BukkitRunnable br2 = new BukkitRunnable() { + final BukkitRunnable br2 = new BukkitRunnable() { @Override public void run() { - target.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, (int) (slowRepeat * 20), (int) slow)); + target.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, (int) (Suffocate.this.slowRepeat * 20), (int) Suffocate.this.slow)); } }; - BukkitRunnable br3 = new BukkitRunnable() { + final BukkitRunnable br3 = new BukkitRunnable() { @Override public void run() { - target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, (int) (blindRepeat * 20), (int) blind)); + target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, (int) (Suffocate.this.blindRepeat * 20), (int) Suffocate.this.blind)); } }; - tasks.add(br1); - tasks.add(br2); - tasks.add(br3); - br1.runTaskTimer(ProjectKorra.plugin, (long) (damageDelay * 20), (long) (damageRepeat * 20)); - br2.runTaskTimer(ProjectKorra.plugin, (long) (slowDelay * 20), (long) (slowRepeat * 20 / 0.25)); - br3.runTaskTimer(ProjectKorra.plugin, (long) (blindDelay * 20), (long) (blindRepeat * 20)); + this.tasks.add(br1); + this.tasks.add(br2); + this.tasks.add(br3); + br1.runTaskTimer(ProjectKorra.plugin, (long) (this.damageDelay * 20), (long) (this.damageRepeat * 20)); + br2.runTaskTimer(ProjectKorra.plugin, (long) (this.slowDelay * 20), (long) (this.slowRepeat * 20 / 0.25)); + br3.runTaskTimer(ProjectKorra.plugin, (long) (this.blindDelay * 20), (long) (this.blindRepeat * 20)); } } - animate(); - if (!player.isSneaking()) { - remove(); + this.animate(); + if (!this.player.isSneaking()) { + this.remove(); return; } } /** Stops an entity from being suffocated **/ - public static void breakSuffocate(Entity entity) { - for (Suffocate suffocate : getAbilities(Suffocate.class)) { + public static void breakSuffocate(final Entity entity) { + for (final Suffocate suffocate : getAbilities(Suffocate.class)) { if (suffocate.targets.contains(entity)) { suffocate.breakSuffocateLocal(entity); } @@ -240,8 +239,8 @@ public static void breakSuffocate(Entity entity) { } /** Checks if an entity is being suffocated **/ - public static boolean isBreathbent(Entity entity) { - for (Suffocate suffocate : getAbilities(Suffocate.class)) { + public static boolean isBreathbent(final Entity entity) { + for (final Suffocate suffocate : getAbilities(Suffocate.class)) { if (suffocate.targets.contains(entity)) { return suffocate.started; } @@ -250,7 +249,7 @@ public static boolean isBreathbent(Entity entity) { } /** Determines if a player is Suffocating entities **/ - public static boolean isChannelingSphere(Player player) { + public static boolean isChannelingSphere(final Player player) { return hasAbility(player, Suffocate.class); } @@ -258,8 +257,8 @@ public static boolean isChannelingSphere(Player player) { * Removes an instance of Suffocate if player is the one suffocating * entities **/ - public static void remove(Player player) { - Suffocate suff = getAbility(player, Suffocate.class); + public static void remove(final Player player) { + final Suffocate suff = getAbility(player, Suffocate.class); if (suff != null) { suff.remove(); } @@ -269,16 +268,16 @@ public static void remove(Player player) { * Removes all instances of Suffocate at loc within the radius threshold. * The location of a Suffocate is defined at the benders location, not the * location of the entities being suffocated. - * + * * @param causer The player causing this instance to be removed **/ - public static boolean removeAtLocation(Player causer, Location loc, double radius) { + public static boolean removeAtLocation(final Player causer, final Location loc, final double radius) { if (causer == null) { return false; } - for (Suffocate suff : getAbilities(Suffocate.class)) { + for (final Suffocate suff : getAbilities(Suffocate.class)) { if (!suff.player.equals(causer)) { - Location playerLoc = suff.getPlayer().getLocation(); + final Location playerLoc = suff.getPlayer().getLocation(); if (playerLoc.getWorld().equals(loc.getWorld()) && playerLoc.distanceSquared(loc) <= radius * radius) { suff.remove(); return true; @@ -294,43 +293,43 @@ public static boolean removeAtLocation(Player causer, Location loc, double radiu * SuffocationSpirals. */ public void animate() { - int steps = 8 * particleCount; - long curTime = System.currentTimeMillis(); - long dt = curTime - getStartTime() - chargeTime; - long delay = 2 / particleCount; - long t1 = (long) (1500 * animationSpeed); - long t2 = (long) (2500 * animationSpeed); - long t3 = (long) (5000 * animationSpeed); - long t4 = (long) (6000 * animationSpeed); - for (LivingEntity lent : targets) { + final int steps = 8 * this.particleCount; + final long curTime = System.currentTimeMillis(); + final long dt = curTime - this.getStartTime() - this.chargeTime; + final long delay = 2 / this.particleCount; + final long t1 = (long) (1500 * this.animationSpeed); + final long t2 = (long) (2500 * this.animationSpeed); + final long t3 = (long) (5000 * this.animationSpeed); + final long t4 = (long) (6000 * this.animationSpeed); + for (final LivingEntity lent : this.targets) { final LivingEntity target = lent; if (dt < t1) { - new SuffocateSpiral(target, steps, radius, delay, 0, 0.25 - (0.25 * (double) dt / (double) t1), 0, SpiralType.HORIZONTAL1); - new SuffocateSpiral(target, steps, radius, delay, 0, 0.25 - (0.25 * (double) dt / (double) t1), 0, SpiralType.HORIZONTAL2); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0.25 - (0.25 * dt / t1), 0, SpiralType.HORIZONTAL1); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0.25 - (0.25 * dt / t1), 0, SpiralType.HORIZONTAL2); } else if (dt < t2) { - new SuffocateSpiral(target, steps, radius, delay, 0, 0, 0, SpiralType.HORIZONTAL1); - new SuffocateSpiral(target, steps * 2, radius, delay, 0, 0, 0, SpiralType.VERTICAL1); - new SuffocateSpiral(target, steps * 2, radius, delay, 0, 0, 0, SpiralType.VERTICAL2); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0, 0, SpiralType.HORIZONTAL1); + new SuffocateSpiral(target, steps * 2, this.radius, delay, 0, 0, 0, SpiralType.VERTICAL1); + new SuffocateSpiral(target, steps * 2, this.radius, delay, 0, 0, 0, SpiralType.VERTICAL2); } else if (dt < t3) { - new SuffocateSpiral(target, steps, radius, delay, 0, 0, 0, SpiralType.HORIZONTAL1); - new SuffocateSpiral(target, steps, radius, delay, 0, 0, 0, SpiralType.VERTICAL1); - new SuffocateSpiral(target, steps, radius, delay, 0, 0, 0, SpiralType.VERTICAL2); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0, 0, SpiralType.HORIZONTAL1); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0, 0, SpiralType.VERTICAL1); + new SuffocateSpiral(target, steps, this.radius, delay, 0, 0, 0, SpiralType.VERTICAL2); } else if (dt < t4) { - new SuffocateSpiral(target, steps, radius - Math.min(radius * 3 / 4, (radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.HORIZONTAL1); - new SuffocateSpiral(target, steps, radius - Math.min(radius * 3 / 4, (radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.VERTICAL1); - new SuffocateSpiral(target, steps, radius - Math.min(radius * 3 / 4, (radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.VERTICAL2); + new SuffocateSpiral(target, steps, this.radius - Math.min(this.radius * 3 / 4, (this.radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.HORIZONTAL1); + new SuffocateSpiral(target, steps, this.radius - Math.min(this.radius * 3 / 4, (this.radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.VERTICAL1); + new SuffocateSpiral(target, steps, this.radius - Math.min(this.radius * 3 / 4, (this.radius * 3.0 / 4 * ((double) (dt - t3) / (double) (t4 - t3)))), delay, 0, 0, 0, SpiralType.VERTICAL2); } else { - new SuffocateSpiral(target, steps, radius - (radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.HORIZONTAL1); - new SuffocateSpiral(target, steps, radius - (radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.VERTICAL1); - new SuffocateSpiral(target, steps, radius - (radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.VERTICAL2); + new SuffocateSpiral(target, steps, this.radius - (this.radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.HORIZONTAL1); + new SuffocateSpiral(target, steps, this.radius - (this.radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.VERTICAL1); + new SuffocateSpiral(target, steps, this.radius - (this.radius * 3.0 / 4.0), delay, 0, 0, 0, SpiralType.VERTICAL2); } } } /** Stops an entity from being suffocated **/ - public void breakSuffocateLocal(Entity entity) { - if (targets.contains(entity)) { - targets.remove(entity); + public void breakSuffocateLocal(final Entity entity) { + if (this.targets.contains(entity)) { + this.targets.remove(entity); } } @@ -338,9 +337,9 @@ public void breakSuffocateLocal(Entity entity) { @Override public void remove() { super.remove(); - for (int i = 0; i < tasks.size(); i++) { - tasks.get(i).cancel(); - tasks.remove(i); + for (int i = 0; i < this.tasks.size(); i++) { + this.tasks.get(i).cancel(); + this.tasks.remove(i); i--; } } @@ -352,12 +351,12 @@ public void remove() { */ public class SuffocateSpiral extends BukkitRunnable { private Location startLoc; - private Location loc; + private final Location loc; private LivingEntity target; - private int totalSteps; - private double radius; - private double dx, dy, dz; - private SpiralType type; + private final int totalSteps; + private final double radius; + private final double dx, dy, dz; + private final SpiralType type; private int i; /** @@ -370,7 +369,7 @@ public class SuffocateSpiral extends BukkitRunnable { * @param dz z offset * @param type Spiral animation direction */ - public SuffocateSpiral(LivingEntity lent, int totalSteps, double radius, long interval, double dx, double dy, double dz, SpiralType type) { + public SuffocateSpiral(final LivingEntity lent, final int totalSteps, final double radius, final long interval, final double dx, final double dy, final double dz, final SpiralType type) { this.target = lent; this.totalSteps = totalSteps; this.radius = radius; @@ -378,10 +377,10 @@ public SuffocateSpiral(LivingEntity lent, int totalSteps, double radius, long in this.dy = dy; this.dz = dz; this.type = type; - this.loc = target.getEyeLocation(); + this.loc = this.target.getEyeLocation(); this.i = 0; this.runTaskTimer(ProjectKorra.plugin, 0L, interval); - tasks.add(this); + Suffocate.this.tasks.add(this); } /** @@ -394,7 +393,7 @@ public SuffocateSpiral(LivingEntity lent, int totalSteps, double radius, long in * @param dz z offset * @param type Spiral animation direction */ - public SuffocateSpiral(Location startLoc, int totalSteps, double radius, long interval, double dx, double dy, double dz, SpiralType type) { + public SuffocateSpiral(final Location startLoc, final int totalSteps, final double radius, final long interval, final double dx, final double dy, final double dz, final SpiralType type) { this.startLoc = startLoc; this.totalSteps = totalSteps; this.radius = radius; @@ -405,52 +404,53 @@ public SuffocateSpiral(Location startLoc, int totalSteps, double radius, long in this.loc = startLoc.clone(); this.i = 0; this.runTaskTimer(ProjectKorra.plugin, 0L, interval); - tasks.add(this); + Suffocate.this.tasks.add(this); } /** * Starts the initial animation, and removes itself when it is finished. */ + @Override public void run() { Location tempLoc; - if (target != null) { - tempLoc = target.getEyeLocation(); + if (this.target != null) { + tempLoc = this.target.getEyeLocation(); tempLoc.setY(tempLoc.getY() - 0.5); } else { - tempLoc = startLoc.clone(); + tempLoc = this.startLoc.clone(); } - if (type == SpiralType.HORIZONTAL1) { - loc.setX(tempLoc.getX() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setY(tempLoc.getY() + dy * i); - loc.setZ(tempLoc.getZ() + radius * Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - } else if (type == SpiralType.HORIZONTAL2) { - loc.setX(tempLoc.getX() + radius * -Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setY(tempLoc.getY() + dy * i); - loc.setZ(tempLoc.getZ() + radius * -Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - } else if (type == SpiralType.VERTICAL1) { - loc.setX(tempLoc.getX() + radius * Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setY(tempLoc.getY() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setZ(tempLoc.getZ() + dz * i); - } else if (type == SpiralType.VERTICAL2) { - loc.setX(tempLoc.getX() + dx * i); - loc.setY(tempLoc.getY() + radius * Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setZ(tempLoc.getZ() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - } else if (type == SpiralType.DIAGONAL1) { - loc.setX(tempLoc.getX() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setY(tempLoc.getY() + radius * Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setZ(tempLoc.getZ() + radius * -Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - } else if (type == SpiralType.DIAGONAL2) { - loc.setX(tempLoc.getX() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setY(tempLoc.getY() + radius * Math.sin(Math.toRadians((double) i / (double) totalSteps * 360))); - loc.setZ(tempLoc.getZ() + radius * Math.cos(Math.toRadians((double) i / (double) totalSteps * 360))); + if (this.type == SpiralType.HORIZONTAL1) { + this.loc.setX(tempLoc.getX() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setY(tempLoc.getY() + this.dy * this.i); + this.loc.setZ(tempLoc.getZ() + this.radius * Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + } else if (this.type == SpiralType.HORIZONTAL2) { + this.loc.setX(tempLoc.getX() + this.radius * -Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setY(tempLoc.getY() + this.dy * this.i); + this.loc.setZ(tempLoc.getZ() + this.radius * -Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + } else if (this.type == SpiralType.VERTICAL1) { + this.loc.setX(tempLoc.getX() + this.radius * Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setY(tempLoc.getY() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setZ(tempLoc.getZ() + this.dz * this.i); + } else if (this.type == SpiralType.VERTICAL2) { + this.loc.setX(tempLoc.getX() + this.dx * this.i); + this.loc.setY(tempLoc.getY() + this.radius * Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setZ(tempLoc.getZ() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + } else if (this.type == SpiralType.DIAGONAL1) { + this.loc.setX(tempLoc.getX() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setY(tempLoc.getY() + this.radius * Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setZ(tempLoc.getZ() + this.radius * -Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + } else if (this.type == SpiralType.DIAGONAL2) { + this.loc.setX(tempLoc.getX() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setY(tempLoc.getY() + this.radius * Math.sin(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); + this.loc.setZ(tempLoc.getZ() + this.radius * Math.cos(Math.toRadians((double) this.i / (double) this.totalSteps * 360))); } - getAirbendingParticles().display(loc, (float) 0, (float) 0, (float) 0, 0, 1); - if (i == totalSteps + 1) { + getAirbendingParticles().display(this.loc, 0, 0, 0, 0, 1); + if (this.i == this.totalSteps + 1) { this.cancel(); } - i++; + this.i++; } } @@ -461,17 +461,17 @@ public String getName() { @Override public Location getLocation() { - if (targets.size() > 0) { - return targets.get(0).getLocation(); - } else if (player != null) { - return player.getLocation(); + if (this.targets.size() > 0) { + return this.targets.get(0).getLocation(); + } else if (this.player != null) { + return this.player.getLocation(); } return null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -486,164 +486,165 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - locations.add(player.getLocation()); + final ArrayList locations = new ArrayList<>(); + locations.add(this.player.getLocation()); return locations; } + @Override public boolean isStarted() { - return started; + return this.started; } - public void setStarted(boolean started) { + public void setStarted(final boolean started) { this.started = started; } public boolean isRequireConstantAim() { - return requireConstantAim; + return this.requireConstantAim; } - public void setRequireConstantAim(boolean requireConstantAim) { + public void setRequireConstantAim(final boolean requireConstantAim) { this.requireConstantAim = requireConstantAim; } public boolean isCanSuffocateUndead() { - return canSuffocateUndead; + return this.canSuffocateUndead; } - public void setCanSuffocateUndead(boolean canSuffocateUndead) { + public void setCanSuffocateUndead(final boolean canSuffocateUndead) { this.canSuffocateUndead = canSuffocateUndead; } public int getParticleCount() { - return particleCount; + return this.particleCount; } - public void setParticleCount(int particleCount) { + public void setParticleCount(final int particleCount) { this.particleCount = particleCount; } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getDamageDelay() { - return damageDelay; + return this.damageDelay; } - public void setDamageDelay(double damageDelay) { + public void setDamageDelay(final double damageDelay) { this.damageDelay = damageDelay; } public double getDamageRepeat() { - return damageRepeat; + return this.damageRepeat; } - public void setDamageRepeat(double damageRepeat) { + public void setDamageRepeat(final double damageRepeat) { this.damageRepeat = damageRepeat; } public double getSlow() { - return slow; + return this.slow; } - public void setSlow(double slow) { + public void setSlow(final double slow) { this.slow = slow; } public double getSlowRepeat() { - return slowRepeat; + return this.slowRepeat; } - public void setSlowRepeat(double slowRepeat) { + public void setSlowRepeat(final double slowRepeat) { this.slowRepeat = slowRepeat; } public double getSlowDelay() { - return slowDelay; + return this.slowDelay; } - public void setSlowDelay(double slowDelay) { + public void setSlowDelay(final double slowDelay) { this.slowDelay = slowDelay; } public double getConstantAimRadius() { - return constantAimRadius; + return this.constantAimRadius; } - public void setConstantAimRadius(double constantAimRadius) { + public void setConstantAimRadius(final double constantAimRadius) { this.constantAimRadius = constantAimRadius; } public double getBlind() { - return blind; + return this.blind; } - public void setBlind(double blind) { + public void setBlind(final double blind) { this.blind = blind; } public double getBlindDelay() { - return blindDelay; + return this.blindDelay; } - public void setBlindDelay(double blindDelay) { + public void setBlindDelay(final double blindDelay) { this.blindDelay = blindDelay; } public double getBlindRepeat() { - return blindRepeat; + return this.blindRepeat; } - public void setBlindRepeat(double blindRepeat) { + public void setBlindRepeat(final double blindRepeat) { this.blindRepeat = blindRepeat; } public double getAnimationSpeed() { - return animationSpeed; + return this.animationSpeed; } - public void setAnimationSpeed(double animationSpeed) { + public void setAnimationSpeed(final double animationSpeed) { this.animationSpeed = animationSpeed; } public ArrayList getTasks() { - return tasks; + return this.tasks; } public ArrayList getTargets() { - return targets; + return this.targets; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } } diff --git a/src/com/projectkorra/projectkorra/airbending/Tornado.java b/src/com/projectkorra/projectkorra/airbending/Tornado.java index a89c084f9..10901e9c7 100644 --- a/src/com/projectkorra/projectkorra/airbending/Tornado.java +++ b/src/com/projectkorra/projectkorra/airbending/Tornado.java @@ -1,10 +1,9 @@ package com.projectkorra.projectkorra.airbending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.util.Flight; +import java.util.HashSet; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -12,14 +11,16 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.HashSet; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.attribute.Attribute; +import com.projectkorra.projectkorra.command.Commands; public class Tornado extends AirAbility { - - private long cooldown; + + private final long cooldown; + private final long duration; private int numberOfStreams; private int particleCount; @Attribute(Attribute.SPEED) @@ -35,91 +36,93 @@ public class Tornado extends AirAbility { private double npcPushFactor; private double currentHeight; private double currentRadius; - private boolean couldFly; - private Flight flight; private Location origin; - private Random random; - private Map angles; + private final Random random; + private final Map angles; - public Tornado(Player player) { + public Tornado(final Player player) { super(player); - + this.cooldown = getConfig().getLong("Abilities.Air.Tornado.Cooldown"); + this.duration = getConfig().getLong("Abilities.Air.Tornado.Duration"); this.range = getConfig().getDouble("Abilities.Air.Tornado.Range"); - this.origin = player.getTargetBlock((HashSet) null, (int) range).getLocation(); - this.origin.setY(origin.getY() - 1.0 / 10.0 * currentHeight); + this.origin = player.getTargetBlock((HashSet) null, (int) this.range).getLocation(); + this.origin.setY(this.origin.getY() - 1.0 / 10.0 * this.currentHeight); this.maxHeight = getConfig().getDouble("Abilities.Air.Tornado.Height"); this.playerPushFactor = getConfig().getDouble("Abilities.Air.Tornado.PlayerPushFactor"); this.radius = getConfig().getDouble("Abilities.Air.Tornado.Radius"); this.npcPushFactor = getConfig().getDouble("Abilities.Air.Tornado.NpcPushFactor"); this.speed = getConfig().getDouble("Abilities.Air.Tornado.Speed"); - this.numberOfStreams = (int) (.3 * (double) maxHeight); + this.numberOfStreams = (int) (.3 * this.maxHeight); this.currentHeight = 2; - this.currentRadius = currentHeight / maxHeight * radius; + this.currentRadius = this.currentHeight / this.maxHeight * this.radius; this.random = new Random(); this.angles = new ConcurrentHashMap<>(); int angle = 0; - for (int i = 0; i <= maxHeight; i += (int) maxHeight / numberOfStreams) { - angles.put(i, angle); + for (int i = 0; i <= this.maxHeight; i += (int) this.maxHeight / this.numberOfStreams) { + this.angles.put(i, angle); angle += 90; if (angle == 360) { angle = 0; } } - - this.flight = new Flight(player); - this.couldFly = player.getAllowFlight(); + ProjectKorra.flightHandler.createInstance(player, this.getName()); player.setAllowFlight(true); - start(); + this.start(); } @Override public void progress() { - if (player.getEyeLocation().getBlock().isLiquid() || !player.isSneaking() || !bPlayer.canBendIgnoreCooldowns(this)) { - bPlayer.addCooldown(this); - remove(); + if (this.player.getEyeLocation().getBlock().isLiquid() || !this.player.isSneaking() || !this.bPlayer.canBend(this)) { + this.bPlayer.addCooldown(this); + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, origin)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.origin)) { + this.remove(); return; + } else if (this.duration != 0) { + if (this.getStartTime() + this.duration <= System.currentTimeMillis()) { + this.bPlayer.addCooldown(this); + this.remove(); + return; + } } - rotateTornado(); + this.rotateTornado(); } @Override public void remove() { super.remove(); - flight.remove(); - player.setAllowFlight(couldFly); + ProjectKorra.flightHandler.removeInstance(this.player, this.getName()); } private void rotateTornado() { - origin = player.getTargetBlock((HashSet) null, (int) range).getLocation(); - double timefactor = currentHeight / maxHeight; - currentRadius = timefactor * radius; + this.origin = this.player.getTargetBlock((HashSet) null, (int) this.range).getLocation(); + final double timefactor = this.currentHeight / this.maxHeight; + this.currentRadius = timefactor * this.radius; - if (origin.getBlock().getType() != Material.AIR && origin.getBlock().getType() != Material.BARRIER) { - origin.setY(origin.getY() - 1. / 10. * currentHeight); + if (this.origin.getBlock().getType() != Material.AIR && this.origin.getBlock().getType() != Material.BARRIER) { + this.origin.setY(this.origin.getY() - 1. / 10. * this.currentHeight); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(origin, currentHeight)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.origin, this.currentHeight)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } - double y = entity.getLocation().getY(); + final double y = entity.getLocation().getY(); double factor; - if (y > origin.getY() && y < origin.getY() + currentHeight) { - factor = (y - origin.getY()) / currentHeight; - Location testloc = new Location(origin.getWorld(), origin.getX(), y, origin.getZ()); - if (testloc.getWorld().equals(entity.getWorld()) && testloc.distance(entity.getLocation()) < currentRadius * factor) { + if (y > this.origin.getY() && y < this.origin.getY() + this.currentHeight) { + factor = (y - this.origin.getY()) / this.currentHeight; + final Location testloc = new Location(this.origin.getWorld(), this.origin.getX(), y, this.origin.getZ()); + if (testloc.getWorld().equals(entity.getWorld()) && testloc.distance(entity.getLocation()) < this.currentRadius * factor) { double x, z, vx, vz, mag; double angle = 100; - double vy = 0.7 * npcPushFactor; + double vy = 0.7 * this.npcPushFactor; angle = Math.toRadians(angle); - x = entity.getLocation().getX() - origin.getX(); - z = entity.getLocation().getZ() - origin.getZ(); + x = entity.getLocation().getX() - this.origin.getX(); + z = entity.getLocation().getZ() - this.origin.getZ(); mag = Math.sqrt(x * x + z * z); @@ -127,22 +130,22 @@ private void rotateTornado() { vz = (x * Math.sin(angle) + z * Math.cos(angle)) / mag; if (entity instanceof Player) { - vy = 0.05 * playerPushFactor; + vy = 0.05 * this.playerPushFactor; } - if (entity.getEntityId() == player.getEntityId()) { - Vector direction = player.getEyeLocation().getDirection().clone().normalize(); + if (entity.getEntityId() == this.player.getEntityId()) { + final Vector direction = this.player.getEyeLocation().getDirection().clone().normalize(); vx = direction.getX(); vz = direction.getZ(); - Location playerloc = player.getLocation(); - double py = playerloc.getY(); - double oy = origin.getY(); - double dy = py - oy; + final Location playerloc = this.player.getLocation(); + final double py = playerloc.getY(); + final double oy = this.origin.getY(); + final double dy = py - oy; - if (dy >= currentHeight * .95) { + if (dy >= this.currentHeight * .95) { vy = 0; - } else if (dy >= currentHeight * .85) { - vy = 6.0 * (.95 - dy / currentHeight); + } else if (dy >= this.currentHeight * .85) { + vy = 6.0 * (.95 - dy / this.currentHeight); } else { vy = .6; } @@ -154,7 +157,7 @@ private void rotateTornado() { } } - Vector velocity = entity.getVelocity(); + final Vector velocity = entity.getVelocity(); velocity.setX(vx); velocity.setZ(vz); velocity.setY(vy); @@ -165,34 +168,34 @@ private void rotateTornado() { breakBreathbendingHold(entity); if (entity instanceof Player) { - new Flight((Player) entity); + ProjectKorra.flightHandler.createInstance((Player) entity, 50L, this.getName()); } } } } - for (int i : angles.keySet()) { + for (final int i : this.angles.keySet()) { double x, y, z, factor; - double angle = (double) angles.get(i); + double angle = this.angles.get(i); angle = Math.toRadians(angle); - y = origin.getY() + timefactor * (double) i; - factor = (double) i / currentHeight; + y = this.origin.getY() + timefactor * i; + factor = i / this.currentHeight; - x = origin.getX() + timefactor * factor * currentRadius * Math.cos(angle); - z = origin.getZ() + timefactor * factor * currentRadius * Math.sin(angle); + x = this.origin.getX() + timefactor * factor * this.currentRadius * Math.cos(angle); + z = this.origin.getZ() + timefactor * factor * this.currentRadius * Math.sin(angle); - Location effect = new Location(origin.getWorld(), x, y, z); + final Location effect = new Location(this.origin.getWorld(), x, y, z); if (!GeneralMethods.isRegionProtectedFromBuild(this, effect)) { - playAirbendingParticles(effect, particleCount); - if (random.nextInt(20) == 0) { + playAirbendingParticles(effect, this.particleCount); + if (this.random.nextInt(20) == 0) { playAirbendingSound(effect); } } - angles.put(i, angles.get(i) + 25 * (int) speed); + this.angles.put(i, this.angles.get(i) + 25 * (int) this.speed); } } - currentHeight = currentHeight > maxHeight ? maxHeight : currentHeight + 1; + this.currentHeight = this.currentHeight > this.maxHeight ? this.maxHeight : this.currentHeight + 1; } @Override @@ -202,12 +205,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -222,98 +225,98 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public int getNumberOfStreams() { - return numberOfStreams; + return this.numberOfStreams; } - public void setNumberOfStreams(int numberOfStreams) { + public void setNumberOfStreams(final int numberOfStreams) { this.numberOfStreams = numberOfStreams; } public int getParticleCount() { - return particleCount; + return this.particleCount; } - public void setParticleCount(int particleCount) { + public void setParticleCount(final int particleCount) { this.particleCount = particleCount; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getMaxHeight() { - return maxHeight; + return this.maxHeight; } - public void setMaxHeight(double maxHeight) { + public void setMaxHeight(final double maxHeight) { this.maxHeight = maxHeight; } public double getPlayerPushFactor() { - return playerPushFactor; + return this.playerPushFactor; } - public void setPlayerPushFactor(double playerPushFactor) { + public void setPlayerPushFactor(final double playerPushFactor) { this.playerPushFactor = playerPushFactor; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getNpcPushFactor() { - return npcPushFactor; + return this.npcPushFactor; } - public void setNpcPushFactor(double npcPushFactor) { + public void setNpcPushFactor(final double npcPushFactor) { this.npcPushFactor = npcPushFactor; } public double getCurrentHeight() { - return currentHeight; + return this.currentHeight; } - public void setCurrentHeight(double currentHeight) { + public void setCurrentHeight(final double currentHeight) { this.currentHeight = currentHeight; } public double getCurrentRadius() { - return currentRadius; + return this.currentRadius; } - public void setCurrentRadius(double currentRadius) { + public void setCurrentRadius(final double currentRadius) { this.currentRadius = currentRadius; } public Map getAngles() { - return angles; + return this.angles; } } diff --git a/src/com/projectkorra/projectkorra/airbending/combo/AirStream.java b/src/com/projectkorra/projectkorra/airbending/combo/AirStream.java index 488fd6f9c..9b827a5fb 100644 --- a/src/com/projectkorra/projectkorra/airbending/combo/AirStream.java +++ b/src/com/projectkorra/projectkorra/airbending/combo/AirStream.java @@ -1,6 +1,8 @@ package com.projectkorra.projectkorra.airbending.combo; import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; import org.bukkit.Location; import org.bukkit.entity.Entity; @@ -15,7 +17,7 @@ import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.util.Flight; +import com.projectkorra.projectkorra.util.ClickType; public class AirStream extends AirAbility implements ComboAbility { private long cooldown; @@ -32,20 +34,20 @@ public class AirStream extends AirAbility implements ComboAbility { private Vector direction; private ArrayList affectedEntities; private ArrayList tasks; - private ArrayList flights; - - public AirStream(Player player) { + private Set flights; + + public AirStream(final Player player) { super(player); this.affectedEntities = new ArrayList<>(); this.tasks = new ArrayList<>(); - this.flights = new ArrayList<>(); + this.flights = new HashSet<>(); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } @@ -55,15 +57,15 @@ public AirStream(Player player) { this.airStreamMaxEntityHeight = getConfig().getDouble("Abilities.Air.AirStream.EntityHeight"); this.airStreamEntityCarryDuration = getConfig().getLong("Abilities.Air.AirStream.EntityDuration"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirStream.Range"); this.airStreamMaxEntityHeight = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirStream.EntityHeight"); this.airStreamEntityCarryDuration = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirStream.EntityDuration"); } - - bPlayer.addCooldown(this); - start(); + + this.bPlayer.addCooldown(this); + this.start(); } @Override @@ -78,106 +80,108 @@ public boolean isCollidable() { @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) { - remove(); + } else if (this.currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, this.currentLoc)) { + this.remove(); return; } - - if (destination == null) { - origin = player.getEyeLocation(); - currentLoc = origin.clone(); + + if (this.destination == null) { + this.origin = this.player.getEyeLocation(); + this.currentLoc = this.origin.clone(); } - Entity target = GeneralMethods.getTargetedEntity(player, range); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range); if (target instanceof Player) { if (Commands.invincible.contains(((Player) target).getName())) { return; } } - if (target != null && target.getLocation().distanceSquared(currentLoc) > 49) { - destination = target.getLocation(); + if (target != null && target.getLocation().distanceSquared(this.currentLoc) > 49) { + this.destination = target.getLocation(); } else { - destination = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterials()); + this.destination = GeneralMethods.getTargetedLocation(this.player, this.range, getTransparentMaterials()); } - direction = GeneralMethods.getDirection(currentLoc, destination).normalize(); - currentLoc.add(direction.clone().multiply(speed)); + this.direction = GeneralMethods.getDirection(this.currentLoc, this.destination).normalize(); + this.currentLoc.add(this.direction.clone().multiply(this.speed)); - if (player.getWorld() != currentLoc.getWorld()) { - remove(); + if (this.player.getWorld() != this.currentLoc.getWorld()) { + this.remove(); return; - } else if (!player.isSneaking()) { - remove(); + } else if (!this.player.isSneaking()) { + this.remove(); return; - } else if (player.getWorld().equals(currentLoc.getWorld()) && Math.abs(player.getLocation().distanceSquared(currentLoc)) > range * range) { - remove(); + } else if (this.player.getWorld().equals(this.currentLoc.getWorld()) && Math.abs(this.player.getLocation().distanceSquared(this.currentLoc)) > this.range * this.range) { + this.remove(); return; - } else if (affectedEntities.size() > 0 && System.currentTimeMillis() - time >= airStreamEntityCarryDuration) { - remove(); + } else if (this.affectedEntities.size() > 0 && System.currentTimeMillis() - this.time >= this.airStreamEntityCarryDuration) { + this.remove(); return; - } else if (!isTransparent(currentLoc.getBlock())) { - remove(); + } else if (!this.isTransparent(this.currentLoc.getBlock())) { + this.remove(); return; - } else if (currentLoc.getY() - origin.getY() > airStreamMaxEntityHeight) { - remove(); + } else if (this.currentLoc.getY() - this.origin.getY() > this.airStreamMaxEntityHeight) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.currentLoc)) { + this.remove(); return; - } else if (!isTransparent(currentLoc.getBlock())) { - currentLoc.subtract(direction.clone().multiply(speed)); + } else if (!this.isTransparent(this.currentLoc.getBlock())) { + this.currentLoc.subtract(this.direction.clone().multiply(this.speed)); } for (int i = 0; i < 10; i++) { - BukkitRunnable br = new BukkitRunnable() { - final Location loc = currentLoc.clone(); - final Vector dir = direction.clone(); + final BukkitRunnable br = new BukkitRunnable() { + final Location loc = AirStream.this.currentLoc.clone(); + final Vector dir = AirStream.this.direction.clone(); @Override public void run() { for (int angle = -180; angle <= 180; angle += 45) { - Vector orthog = GeneralMethods.getOrthogonalVector(dir.clone(), angle, 0.5); - playAirbendingParticles(loc.clone().add(orthog), 1, 0F, 0F, 0F); + final Vector orthog = GeneralMethods.getOrthogonalVector(this.dir.clone(), angle, 0.5); + playAirbendingParticles(this.loc.clone().add(orthog), 1, 0F, 0F, 0F); } } }; br.runTaskLater(ProjectKorra.plugin, i * 2); - tasks.add(br); + this.tasks.add(br); } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(currentLoc, 2.8)) { - if (affectedEntities.size() == 0) { - // Set the timer to remove the ability - time = System.currentTimeMillis(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.currentLoc, 2.8)) { + if (this.affectedEntities.size() == 0) { + // Set the timer to remove the ability. + this.time = System.currentTimeMillis(); } - if (!entity.equals(player) && !affectedEntities.contains(entity)) { - affectedEntities.add(entity); + if (!entity.equals(this.player) && !this.affectedEntities.contains(entity)) { + this.affectedEntities.add(entity); if (entity instanceof Player) { - flights.add(new Flight((Player) entity, player)); + final Player ep = (Player) entity; + ProjectKorra.flightHandler.createInstance(ep, this.player, this.getName()); + this.flights.add(ep); } } } - for (Entity entity : affectedEntities) { - Vector force = GeneralMethods.getDirection(entity.getLocation(), currentLoc); - entity.setVelocity(force.clone().normalize().multiply(speed)); + for (final Entity entity : this.affectedEntities) { + final Vector force = GeneralMethods.getDirection(entity.getLocation(), this.currentLoc); + entity.setVelocity(force.clone().normalize().multiply(this.speed)); entity.setFallDistance(0F); } } - + @Override public void remove() { super.remove(); - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } - for (Flight flight : flights) { - flight.revert(); - flight.remove(); + for (final Player flyer : this.flights) { + ProjectKorra.flightHandler.removeInstance(flyer, this.getName()); } + this.flights.clear(); } @Override @@ -192,113 +196,122 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public Location getLocation() { - return currentLoc; + return this.currentLoc; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new AirStream(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList airStream = new ArrayList<>(); + airStream.add(new AbilityInformation("AirShield", ClickType.SHIFT_DOWN)); + airStream.add(new AbilityInformation("AirSuction", ClickType.LEFT_CLICK)); + airStream.add(new AbilityInformation("AirBlast", ClickType.LEFT_CLICK)); + return airStream; } - + public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Location getCurrentLoc() { - return currentLoc; + return this.currentLoc; } - public void setCurrentLoc(Location currentLoc) { + public void setCurrentLoc(final Location currentLoc) { this.currentLoc = currentLoc; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getAirStreamMaxEntityHeight() { - return airStreamMaxEntityHeight; + return this.airStreamMaxEntityHeight; } - public void setAirStreamMaxEntityHeight(double airStreamMaxEntityHeight) { + public void setAirStreamMaxEntityHeight(final double airStreamMaxEntityHeight) { this.airStreamMaxEntityHeight = airStreamMaxEntityHeight; } public double getAirStreamEntityCarryDuration() { - return airStreamEntityCarryDuration; + return this.airStreamEntityCarryDuration; } - public void setAirStreamEntityCarryDuration(double airStreamEntityCarryDuration) { + public void setAirStreamEntityCarryDuration(final double airStreamEntityCarryDuration) { this.airStreamEntityCarryDuration = airStreamEntityCarryDuration; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setTasks(ArrayList tasks) { + public void setTasks(final ArrayList tasks) { this.tasks = tasks; } - public ArrayList getFlights() { - return flights; + public Set getFlights() { + return this.flights; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } -} \ No newline at end of file + + @Override + public String getInstructions() { + return "AirShield (Hold Shift) > AirSuction (Left Click) > AirBlast (Left Click)"; + } +} diff --git a/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java b/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java index fbddbaf0f..6410d9b78 100644 --- a/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java +++ b/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java @@ -18,6 +18,7 @@ import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.firebending.combo.FireComboStream; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.DamageHandler; public class AirSweep extends AirAbility implements ComboAbility { @@ -38,37 +39,36 @@ public class AirSweep extends AirAbility implements ComboAbility { private Vector direction; private ArrayList affectedEntities; private ArrayList tasks; - - public AirSweep(Player player) { + + public AirSweep(final Player player) { super(player); this.affectedEntities = new ArrayList<>(); this.tasks = new ArrayList<>(); - - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } - + this.damage = getConfig().getDouble("Abilities.Air.AirSweep.Damage"); this.range = getConfig().getDouble("Abilities.Air.AirSweep.Range"); this.speed = getConfig().getDouble("Abilities.Air.AirSweep.Speed"); this.knockback = getConfig().getDouble("Abilities.Air.AirSweep.Knockback"); this.cooldown = getConfig().getLong("Abilities.Air.AirSweep.Cooldown"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSweep.Damage"); this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSweep.Range"); this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.AirSweep.Knockback"); } - - bPlayer.addCooldown(this); - start(); + + this.bPlayer.addCooldown(this); + this.start(); } @Override @@ -82,16 +82,15 @@ public boolean isCollidable() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { if (collision.isRemovingFirst()) { - ArrayList newTasks = new ArrayList<>(); - double collisionDistanceSquared = Math.pow(getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); + final ArrayList newTasks = new ArrayList<>(); + final double collisionDistanceSquared = Math.pow(this.getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); // Remove all of the streams that are by this specific ourLocation. - // Don't just do a single stream at a time or this algorithm becomes O(n^2) with - // Collision's detection algorithm. - for (BukkitRunnable task : getTasks()) { + // Don't just do a single stream at a time or this algorithm becomes O(n^2) with Collision's detection algorithm. + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; if (stream.getLocation().distanceSquared(collision.getLocationSecond()) > collisionDistanceSquared) { newTasks.add(stream); } else { @@ -101,16 +100,16 @@ public void handleCollision(Collision collision) { newTasks.add(task); } } - setTasks(newTasks); + this.setTasks(newTasks); } } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (BukkitRunnable task : getTasks()) { + final ArrayList locations = new ArrayList<>(); + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; locations.add(stream.getLocation()); } } @@ -119,85 +118,85 @@ public List getLocations() { @Override public void progress() { - progressCounter++; - if (player.isDead() || !player.isOnline()) { - remove(); + this.progressCounter++; + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) { - remove(); + } else if (this.currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, this.currentLoc)) { + this.remove(); return; } - - if (origin == null) { - direction = player.getEyeLocation().getDirection().normalize(); - origin = player.getLocation().add(direction.clone().multiply(10)); + + if (this.origin == null) { + this.direction = this.player.getEyeLocation().getDirection().normalize(); + this.origin = this.player.getLocation().add(this.direction.clone().multiply(10)); } - if (progressCounter < 8) { + if (this.progressCounter < 8) { return; } - if (destination == null) { - destination = player.getLocation().add(player.getEyeLocation().getDirection().normalize().multiply(10)); - Vector origToDest = GeneralMethods.getDirection(origin, destination); + if (this.destination == null) { + this.destination = this.player.getLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(10)); + final Vector origToDest = GeneralMethods.getDirection(this.origin, this.destination); for (double i = 0; i < 30; i++) { - Vector vec = GeneralMethods.getDirection(player.getLocation(), origin.clone().add(origToDest.clone().multiply(i / 30))); + final Vector vec = GeneralMethods.getDirection(this.player.getLocation(), this.origin.clone().add(origToDest.clone().multiply(i / 30))); - FireComboStream fs = new FireComboStream(player, this, vec, player.getLocation(), range, speed); + final FireComboStream fs = new FireComboStream(this.player, this, vec, this.player.getLocation(), this.range, this.speed); fs.setDensity(1); fs.setSpread(0F); fs.setUseNewParticles(true); fs.setParticleEffect(getAirbendingParticles()); fs.setCollides(false); fs.runTaskTimer(ProjectKorra.plugin, (long) (i / 2.5), 1L); - tasks.add(fs); + this.tasks.add(fs); } } - manageAirVectors(); + this.manageAirVectors(); } - + public void manageAirVectors() { - for (int i = 0; i < tasks.size(); i++) { - if (((FireComboStream) tasks.get(i)).isCancelled()) { - tasks.remove(i); + for (int i = 0; i < this.tasks.size(); i++) { + if (((FireComboStream) this.tasks.get(i)).isCancelled()) { + this.tasks.remove(i); i--; } } - if (tasks.size() == 0) { - remove(); + if (this.tasks.size() == 0) { + this.remove(); return; } - for (int i = 0; i < tasks.size(); i++) { - FireComboStream fstream = (FireComboStream) tasks.get(i); - Location loc = fstream.getLocation(); + for (int i = 0; i < this.tasks.size(); i++) { + final FireComboStream fstream = (FireComboStream) this.tasks.get(i); + final Location loc = fstream.getLocation(); if (GeneralMethods.isRegionProtectedFromBuild(this, loc)) { fstream.remove(); return; } - if (!isTransparent(loc.getBlock())) { - if (!isTransparent(loc.clone().add(0, 0.2, 0).getBlock())) { + if (!this.isTransparent(loc.getBlock())) { + if (!this.isTransparent(loc.clone().add(0, 0.2, 0).getBlock())) { fstream.remove(); return; } } if (i % 3 == 0) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 2.5)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 2.5)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { - remove(); + this.remove(); return; } - if (!entity.equals(player) && !affectedEntities.contains(entity)) { - affectedEntities.add(entity); - if (knockback != 0) { - Vector force = fstream.getDirection(); - entity.setVelocity(force.multiply(knockback)); + if (!entity.equals(this.player) && !this.affectedEntities.contains(entity)) { + this.affectedEntities.add(entity); + if (this.knockback != 0) { + final Vector force = fstream.getDirection(); + entity.setVelocity(force.multiply(this.knockback)); } - if (damage != 0) { + if (this.damage != 0) { if (entity instanceof LivingEntity) { if (fstream.getAbility().getName().equalsIgnoreCase("AirSweep")) { - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } else { - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } } } @@ -206,11 +205,11 @@ public void manageAirVectors() { } } } - + @Override public void remove() { super.remove(); - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } @@ -227,105 +226,115 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public Location getLocation() { - return origin; + return this.origin; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new AirSweep(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList airSweep = new ArrayList<>(); + airSweep.add(new AbilityInformation("AirSwipe", ClickType.LEFT_CLICK)); + airSweep.add(new AbilityInformation("AirSwipe", ClickType.LEFT_CLICK)); + airSweep.add(new AbilityInformation("AirBurst", ClickType.SHIFT_DOWN)); + airSweep.add(new AbilityInformation("AirBurst", ClickType.LEFT_CLICK)); + return airSweep; } - + public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Location getCurrentLoc() { - return currentLoc; + return this.currentLoc; } - public void setCurrentLoc(Location currentLoc) { + public void setCurrentLoc(final Location currentLoc) { this.currentLoc = currentLoc; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public int getProgressCounter() { - return progressCounter; + return this.progressCounter; } - public void setProgressCounter(int progressCounter) { + public void setProgressCounter(final int progressCounter) { this.progressCounter = progressCounter; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getKnockback() { - return knockback; + return this.knockback; } - public void setKnockback(double knockback) { + public void setKnockback(final double knockback) { this.knockback = knockback; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setTasks(ArrayList tasks) { + public void setTasks(final ArrayList tasks) { this.tasks = tasks; } -} \ No newline at end of file + + @Override + public String getInstructions() { + return "AirSwipe (Left Click) > AirSwipe (Left Click) > AirBurst (Hold Shift) > AirBurst (Left Click)"; + } +} diff --git a/src/com/projectkorra/projectkorra/airbending/combo/Twister.java b/src/com/projectkorra/projectkorra/airbending/combo/Twister.java index 79291bbae..869b03892 100644 --- a/src/com/projectkorra/projectkorra/airbending/combo/Twister.java +++ b/src/com/projectkorra/projectkorra/airbending/combo/Twister.java @@ -14,6 +14,7 @@ import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; +import com.projectkorra.projectkorra.util.ClickType; public class Twister extends AirAbility implements ComboAbility { @@ -42,17 +43,17 @@ public static enum AbilityState { private Location destination; private Vector direction; private ArrayList affectedEntities; - - public Twister(Player player) { + + public Twister(final Player player) { super(player); this.affectedEntities = new ArrayList<>(); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } @@ -65,14 +66,14 @@ public Twister(Player player) { this.twisterHeightParticles = getConfig().getDouble("Abilities.Air.Twister.HeightPerParticle"); this.twisterRemoveDelay = getConfig().getLong("Abilities.Air.Twister.RemoveDelay"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Twister.Damage"); this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Air.Twister.Range"); } - - bPlayer.addCooldown(this); - start(); + + this.bPlayer.addCooldown(this); + this.start(); } @Override @@ -82,65 +83,65 @@ public String getName() { @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) { - remove(); + } else if (this.currentLoc != null && GeneralMethods.isRegionProtectedFromBuild(this, this.currentLoc)) { + this.remove(); return; } - - if (destination == null) { - state = AbilityState.TWISTER_MOVING; - direction = player.getEyeLocation().getDirection().clone().normalize(); - direction.setY(0); - origin = player.getLocation().add(direction.clone().multiply(2)); - destination = player.getLocation().add(direction.clone().multiply(range)); - currentLoc = origin.clone(); + + if (this.destination == null) { + this.state = AbilityState.TWISTER_MOVING; + this.direction = this.player.getEyeLocation().getDirection().clone().normalize(); + this.direction.setY(0); + this.origin = this.player.getLocation().add(this.direction.clone().multiply(2)); + this.destination = this.player.getLocation().add(this.direction.clone().multiply(this.range)); + this.currentLoc = this.origin.clone(); } - if (origin.distanceSquared(currentLoc) < origin.distanceSquared(destination) && state == AbilityState.TWISTER_MOVING) { - currentLoc.add(direction.clone().multiply(speed)); - } else if (state == AbilityState.TWISTER_MOVING) { - state = AbilityState.TWISTER_STATIONARY; - time = System.currentTimeMillis(); - } else if (System.currentTimeMillis() - time >= twisterRemoveDelay) { - remove(); + if (this.origin.distanceSquared(this.currentLoc) < this.origin.distanceSquared(this.destination) && this.state == AbilityState.TWISTER_MOVING) { + this.currentLoc.add(this.direction.clone().multiply(this.speed)); + } else if (this.state == AbilityState.TWISTER_MOVING) { + this.state = AbilityState.TWISTER_STATIONARY; + this.time = System.currentTimeMillis(); + } else if (System.currentTimeMillis() - this.time >= this.twisterRemoveDelay) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, currentLoc)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.currentLoc)) { + this.remove(); return; } - Block topBlock = GeneralMethods.getTopBlock(currentLoc, 3, -3); + final Block topBlock = GeneralMethods.getTopBlock(this.currentLoc, 3, -3); if (topBlock == null) { - remove(); + this.remove(); return; } - currentLoc.setY(topBlock.getLocation().getY()); - - double height = twisterHeight; - double radius = twisterRadius; - for (double y = 0; y < height; y += twisterHeightParticles) { - double animRadius = ((radius / height) * y); - for (double i = -180; i <= 180; i += twisterDegreeParticles) { - Vector animDir = GeneralMethods.rotateXZ(new Vector(1, 0, 1), i); - Location animLoc = currentLoc.clone().add(animDir.multiply(animRadius)); + this.currentLoc.setY(topBlock.getLocation().getY()); + + final double height = this.twisterHeight; + final double radius = this.twisterRadius; + for (double y = 0; y < height; y += this.twisterHeightParticles) { + final double animRadius = ((radius / height) * y); + for (double i = -180; i <= 180; i += this.twisterDegreeParticles) { + final Vector animDir = GeneralMethods.rotateXZ(new Vector(1, 0, 1), i); + final Location animLoc = this.currentLoc.clone().add(animDir.multiply(animRadius)); animLoc.add(0, y, 0); playAirbendingParticles(animLoc, 1, 0, 0, 0); } } - playAirbendingSound(currentLoc); + playAirbendingSound(this.currentLoc); for (int i = 0; i < height; i += 3) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(currentLoc.clone().add(0, i, 0), radius * 0.75)) { - if (!affectedEntities.contains(entity) && !entity.equals(player)) { - affectedEntities.add(entity); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.currentLoc.clone().add(0, i, 0), radius * 0.75)) { + if (!this.affectedEntities.contains(entity) && !entity.equals(this.player)) { + this.affectedEntities.add(entity); } } } - for (Entity entity : affectedEntities) { - Vector forceDir = GeneralMethods.getDirection(entity.getLocation(), currentLoc.clone().add(0, height, 0)); + for (final Entity entity : this.affectedEntities) { + final Vector forceDir = GeneralMethods.getDirection(entity.getLocation(), this.currentLoc.clone().add(0, height, 0)); if (entity instanceof Player) { if (Commands.invincible.contains(((Player) entity).getName())) { break; @@ -162,29 +163,39 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } - - public void setCooldown(long cooldown) { + + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } @Override public Location getLocation() { - return origin; + return this.origin; } - - public void setLocation(Location location) { + + public void setLocation(final Location location) { this.origin = location; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new Twister(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList twister = new ArrayList<>(); + twister.add(new AbilityInformation("AirShield", ClickType.SHIFT_DOWN)); + twister.add(new AbilityInformation("AirShield", ClickType.SHIFT_UP)); + twister.add(new AbilityInformation("Tornado", ClickType.SHIFT_DOWN)); + twister.add(new AbilityInformation("AirBlast", ClickType.LEFT_CLICK)); + return twister; + } + + @Override + public String getInstructions() { + return "AirShield (Tap Shift) > Tornado (Hold Shift) > AirBlast (Left Click)"; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/airbending/flight/AirFlight.java b/src/com/projectkorra/projectkorra/airbending/flight/AirFlight.java deleted file mode 100644 index 07a07c57d..000000000 --- a/src/com/projectkorra/projectkorra/airbending/flight/AirFlight.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.projectkorra.projectkorra.airbending.flight; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import com.projectkorra.projectkorra.ability.FlightAbility; -import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.object.PlayerFlyData; -import com.projectkorra.projectkorra.util.Flight; - -public class AirFlight extends FlightAbility { - - private static final Map HITS = new ConcurrentHashMap<>(); - private static final Map HOVERING = new ConcurrentHashMap<>(); - - @Attribute(Attribute.COOLDOWN) - private long cooldown; - private boolean firstProgressIteration; - private int maxHitsBeforeRemoval; - @Attribute(Attribute.SPEED) - private double speed; - private Flight flight; - private double hoverY; - @Attribute(Attribute.DURATION) - private double maxDuration; - - public AirFlight(Player player) { - super(player); - - if (CoreAbility.getAbility(player, AirFlight.class) != null) - return; - - this.cooldown = getConfig().getInt("Abilities.Air.Flight.Cooldown"); - this.maxHitsBeforeRemoval = getConfig().getInt("Abilities.Air.Flight.MaxHits"); - this.speed = getConfig().getDouble("Abilities.Air.Flight.Speed"); - this.maxDuration = getConfig().getDouble("Abilities.Air.Flight.MaxDuration"); - this.firstProgressIteration = true; - hoverY = player.getLocation().getBlockY(); - start(); - } - - public static void addHit(Player player) { - AirFlight airFlight = getAbility(player, AirFlight.class); - if (airFlight != null) { - if (HITS.containsKey(player.getName())) { - if (HITS.get(player.getName()) >= airFlight.maxHitsBeforeRemoval) { - HITS.remove(player.getName()); - remove(player); - } - } else { - HITS.put(player.getName(), 1); - } - } - } - - public static boolean isFlying(Player player) { - return hasAbility(player, AirFlight.class); - } - - public static boolean isHovering(Player player) { - return HOVERING.containsKey(player.getName()); - } - - public static void remove(Player player) { - if (isFlying(player)) { - getAbility(player, AirFlight.class).remove(); - } - } - - public static void cleanup() { - HITS.clear(); - HOVERING.clear(); - } - - public static void setHovering(Player player, boolean bool) { - AirFlight flight = CoreAbility.getAbility(player, AirFlight.class); - flight.hoverY = player.getLocation().getBlockY(); - - String playername = player.getName(); - - if (bool) { - if (!HOVERING.containsKey(playername)) { - HOVERING.put(playername, new PlayerFlyData(player.getAllowFlight(), player.isFlying())); - player.setVelocity(new Vector(0, 0, 0)); - player.setAllowFlight(true); - player.setFlying(true); - } - } else { - if (HOVERING.containsKey(playername)) { - PlayerFlyData pfd = HOVERING.get(playername); - player.setAllowFlight(pfd.canFly()); - player.setFlying(pfd.isFlying()); - HOVERING.remove(playername); - } - } - } - - @Override - public void progress() { - boolean isHovering = isHovering(player); - if (!bPlayer.canBend(this)) { - remove(); - return; - } else if (!player.isSneaking() && !isHovering && !firstProgressIteration) { - bPlayer.addCooldown(this); - remove(); - return; - } else if (player.getLocation().subtract(0, 0.4, 0).getBlock().getType() != Material.AIR) { - if (!firstProgressIteration) { - bPlayer.addCooldown(this); - } - remove(); - return; - } else if (System.currentTimeMillis() - getStartTime() > maxDuration && maxDuration > 0) { - bPlayer.addCooldown(this); - remove(); - return; - } - - player.setAllowFlight(true); - - if (flight == null) { - flight = new Flight(player); - player.setFlying(true); - } - - if (isHovering) { - Vector vec = player.getVelocity().clone(); - vec.setY(0); - player.setVelocity(vec); - if (player.getLocation().getBlockY() != hoverY) { - Location loc = new Location(player.getWorld(), player.getLocation().getX(), hoverY + 0.5, player.getLocation().getZ(), player.getLocation().getYaw(), player.getLocation().getPitch()); - player.teleport(loc); - } - } else { - player.setVelocity(player.getEyeLocation().getDirection().normalize().multiply(speed)); - } - firstProgressIteration = false; - } - - @Override - public void remove() { - super.remove(); - HITS.remove(player.getName()); - HOVERING.remove(player.getName()); - if (flight != null) { - flight.revert(); - } - player.setFlying(false); - player.setAllowFlight(player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR); - } - - @Override - public String getName() { - return "Flight"; - } - - @Override - public Location getLocation() { - return player != null ? player.getLocation() : null; - } - - @Override - public long getCooldown() { - return cooldown; - } - - @Override - public boolean isSneakAbility() { - return true; - } - - @Override - public boolean isHarmlessAbility() { - return true; - } - -} diff --git a/src/com/projectkorra/projectkorra/airbending/flight/FlightMultiAbility.java b/src/com/projectkorra/projectkorra/airbending/flight/FlightMultiAbility.java new file mode 100644 index 000000000..f6a67a727 --- /dev/null +++ b/src/com/projectkorra/projectkorra/airbending/flight/FlightMultiAbility.java @@ -0,0 +1,386 @@ +package com.projectkorra.projectkorra.airbending.flight; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.FlightAbility; +import com.projectkorra.projectkorra.ability.MultiAbility; +import com.projectkorra.projectkorra.ability.util.MultiAbilityManager; +import com.projectkorra.projectkorra.ability.util.MultiAbilityManager.MultiAbilityInfoSub; +import com.projectkorra.projectkorra.airbending.AirScooter; +import com.projectkorra.projectkorra.airbending.AirSpout; +import com.projectkorra.projectkorra.firebending.FireJet; +import com.projectkorra.projectkorra.util.ActionBar; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.MovementHandler; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.waterbending.WaterSpout; + +public class FlightMultiAbility extends FlightAbility implements MultiAbility { + + public static final String ID = "FlightMultiAbility"; + public static Map requestedMap = new HashMap<>(); + public static Map requestTime = new HashMap<>(); + + private static Set flying = new HashSet<>(); + private boolean hadGlide; + + private static enum FlightMode { + SOAR, GLIDE, LEVITATE, ENDING; + } + + public double speed = 1, baseSpeed, slowSpeed, fastSpeed, multiplier; + public FlightMode mode = FlightMode.SOAR; + public long prevCheck = 0, duration; + public Vector prevDir; + + public FlightMultiAbility(final Player player) { + super(player); + + if (this.bPlayer.isOnCooldown(this)) { + return; + } + + final FlightMultiAbility f = getAbility(player, FlightMultiAbility.class); + if (f != null) { + if (player.isSneaking()) { + player.eject(); + return; + } + + switch (player.getInventory().getHeldItemSlot()) { + case 0: + f.manageSoarSpeed(); + break; + case 3: + f.remove(); + break; + } + return; + } + + if (player.isInsideVehicle()) { + return; + } + + if (isWater(player.getEyeLocation().getBlock())) { + return; + } + + if (player.isOnGround()) { + return; + } + + CoreAbility abil = null; + if (hasAbility(player, AirSpout.class)) { + abil = getAbility(player, AirSpout.class); + } else if (hasAbility(player, WaterSpout.class)) { + abil = getAbility(player, WaterSpout.class); + } else if (hasAbility(player, FireJet.class)) { + abil = getAbility(player, FireJet.class); + } else if (hasAbility(player, AirScooter.class)) { + abil = getAbility(player, AirScooter.class); + } + + if (abil != null) { + abil.remove(); + } + + MultiAbilityManager.bindMultiAbility(player, "Flight"); + ProjectKorra.flightHandler.createInstance(player, ID); + this.hadGlide = player.isGliding(); + flying.add(player.getUniqueId()); + this.prevDir = player.getEyeLocation().getDirection().clone(); + this.duration = getConfig().getLong("Abilities.Air.Flight.Duration"); + this.baseSpeed = getConfig().getDouble("Abilities.Air.Flight.BaseSpeed"); + this.slowSpeed = this.baseSpeed / 2; + this.fastSpeed = this.baseSpeed * 2; + this.multiplier = this.baseSpeed; + this.start(); + } + + @Override + public long getCooldown() { + return getConfig().getLong("Abilities.Air.Flight.Cooldown"); + } + + @Override + public Location getLocation() { + return this.player == null ? null : this.player.getLocation(); + } + + @Override + public String getName() { + return "Flight"; + } + + @Override + public boolean isHarmlessAbility() { + return true; + } + + @Override + public boolean isSneakAbility() { + return false; + } + + @Override + public void progress() { + if (!this.player.isOnline() || this.player.isDead()) { + this.remove(); + return; + } + + if (this.duration > 0) { + if (System.currentTimeMillis() >= this.duration + this.getStartTime()) { + this.remove(); + return; + } + } + + if (requestedMap.containsKey(this.player.getUniqueId())) { + final Player p2 = Bukkit.getPlayer(requestedMap.get(this.player.getUniqueId())); + if (p2 == null) { + requestedMap.remove(this.player.getUniqueId()); + requestTime.remove(this.player.getUniqueId()); + this.player.sendMessage(ChatColor.RED + "Requested player no longer found, cancelling request!"); + } else { + if (requestTime.get(this.player.getUniqueId()) + 15000 > System.currentTimeMillis()) { + final long start = System.currentTimeMillis(); + new BukkitRunnable() { + @Override + public void run() { + ActionBar.sendActionBar(ChatColor.WHITE + FlightMultiAbility.this.player.getName() + ChatColor.GREEN + " has requested to carry you, right-click them to accept!", p2); + if (System.currentTimeMillis() >= start + 300) { + this.cancel(); + } + } + }.runTaskTimer(ProjectKorra.plugin, 0, 1); + } else { + requestedMap.remove(this.player.getUniqueId()); + requestTime.remove(this.player.getUniqueId()); + } + } + } + + switch (this.player.getInventory().getHeldItemSlot()) { + case 0: + this.mode = FlightMode.SOAR; + break; + case 1: + this.mode = FlightMode.GLIDE; + this.checkMultiplier(); + break; + case 2: + this.mode = FlightMode.LEVITATE; + break; + case 3: + this.mode = FlightMode.ENDING; + break; + } + + this.speed = this.player.getVelocity().length(); + + if (this.mode == FlightMode.SOAR) { + this.player.setGliding(true); + this.player.setAllowFlight(false); + this.player.setFlying(false); + + if (this.speed > this.baseSpeed) { + if (this.prevDir.angle(this.player.getEyeLocation().getDirection()) > 45 || this.prevDir.angle(this.player.getEyeLocation().getDirection()) < -45) { + this.multiplier = 1; + } + + this.prevDir = this.player.getEyeLocation().getDirection().clone(); + } + + this.particles(); + + if (this.speed > this.baseSpeed) { + for (final Entity e : GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.speed)) { + if (e instanceof LivingEntity && e.getEntityId() != this.player.getEntityId() && !this.player.getPassengers().contains(e)) { + if (!GeneralMethods.isRegionProtectedFromBuild(this.player, e.getLocation())) { + final LivingEntity le = (LivingEntity) e; + DamageHandler.damageEntity(le, this.speed / 2, this); + le.setVelocity(this.player.getVelocity().clone().multiply(2 / 3)); + } + } + } + } + + this.player.setVelocity(this.player.getEyeLocation().getDirection().clone().multiply(this.multiplier)); + } else if (this.mode == FlightMode.GLIDE) { + this.player.setAllowFlight(false); + this.player.setFlying(false); + this.player.setGliding(true); + this.particles(); + } else if (this.mode == FlightMode.LEVITATE) { + this.player.setGliding(false); + this.player.setAllowFlight(true); + this.player.setFlying(true); + } else if (this.mode == FlightMode.ENDING) { + this.player.setGliding(false); + this.player.setAllowFlight(false); + this.player.setFlying(false); + } + + if (isWater(this.player.getEyeLocation().clone().getBlock().getType())) { + this.remove(); + } + + if (this.player.isOnGround()) { + this.remove(); + return; + } + } + + private void particles() { + ParticleEffect.CLOUD.display(GeneralMethods.getRightSide(this.player.getLocation(), 0.55).add(this.player.getVelocity().clone()), 0f, 0f, 0f, 0f, 1); + ParticleEffect.CLOUD.display(GeneralMethods.getLeftSide(this.player.getLocation(), 0.55).add(this.player.getVelocity().clone()), 0f, 0f, 0f, 0f, 1); + } + + private String speed() { + if (this.speed >= this.fastSpeed - 0.3) { + return ChatColor.RED + "FAST"; + } else if (this.speed >= this.baseSpeed - 0.3) { + return ChatColor.GREEN + "NORMAL"; + } else if (this.speed >= 0) { + return ChatColor.YELLOW + "SLOW"; + } else { + return ChatColor.WHITE + "ERROR"; + } + } + + private void checkMultiplier() { + if (this.speed >= this.fastSpeed - 0.1) { + this.multiplier = this.fastSpeed; + } else if (this.speed >= this.baseSpeed - 0.1) { + this.multiplier = this.baseSpeed; + } else if (this.speed >= 0) { + this.multiplier = this.slowSpeed; + } + } + + public void requestCarry(final Player p2) { + if (this.mode != FlightMode.LEVITATE) { + this.player.sendMessage(ChatColor.RED + "Can only request to carry when levitating!"); + return; + } + if (!this.player.getPassengers().isEmpty()) { + this.player.sendMessage(ChatColor.RED + "You already have a passenger!"); + return; + } + if (flying.contains(p2.getUniqueId())) { + this.player.sendMessage(ChatColor.RED + "Cannot request to carry an already flying player!"); + return; + } + if (requestedMap.containsKey(this.player.getUniqueId())) { + if (requestedMap.get(this.player.getUniqueId()).equals(p2.getUniqueId())) { + this.player.sendMessage(ChatColor.RED + "Already requested to carry that player!"); + return; + } + } + requestedMap.put(this.player.getUniqueId(), p2.getUniqueId()); + requestTime.put(this.player.getUniqueId(), System.currentTimeMillis()); + this.player.sendMessage(ChatColor.GREEN + "Requested to carry " + ChatColor.WHITE + p2.getName()); + } + + @Override + public void remove() { + super.remove(); + this.bPlayer.addCooldown(this); + MultiAbilityManager.unbindMultiAbility(this.player); + flying.remove(this.player.getUniqueId()); + if (this.player.isOnline() && !this.player.isDead()) { + this.player.eject(); + } + ProjectKorra.flightHandler.removeInstance(this.player, ID); + this.player.setGliding(this.hadGlide); + } + + @Override + public ArrayList getMultiAbilities() { + final ArrayList abils = new ArrayList<>(); + abils.add(new MultiAbilityInfoSub("Soar", Element.FLIGHT)); + abils.add(new MultiAbilityInfoSub("Glide", Element.FLIGHT)); + abils.add(new MultiAbilityInfoSub("Levitate", Element.FLIGHT)); + abils.add(new MultiAbilityInfoSub("Ending", Element.FLIGHT)); + return abils; + } + + public void manageSoarSpeed() { + if (this.speed >= this.fastSpeed - 0.3) { + this.multiplier = this.slowSpeed; + } else if (this.speed >= this.baseSpeed - 0.3) { + this.multiplier = this.fastSpeed; + } else if (this.speed >= 0) { + this.multiplier = this.baseSpeed; + } + + final long start = System.currentTimeMillis(); + new BukkitRunnable() { + @Override + public void run() { + ActionBar.sendActionBar(ChatColor.AQUA + "Flight speed: " + FlightMultiAbility.this.speed(), FlightMultiAbility.this.player); + if (System.currentTimeMillis() >= start + 1000) { + this.cancel(); + } + } + }.runTaskTimer(ProjectKorra.plugin, 0, 1); + } + + public void cancel(final String reason) { + if (!MovementHandler.isStopped(this.player) && !this.bPlayer.isChiBlocked()) { + final long start = System.currentTimeMillis(); + new BukkitRunnable() { + @Override + public void run() { + ActionBar.sendActionBar(ChatColor.RED + "* Flight cancelled due to " + reason + " *", FlightMultiAbility.this.player); + if (System.currentTimeMillis() >= start + 1000) { + this.cancel(); + } + } + }.runTaskTimer(ProjectKorra.plugin, 0, 1); + } + + this.remove(); + } + + public static Set getFlyingPlayers() { + return flying; + } + + public static void acceptCarryRequest(final Player requested, final Player requester) { + if (!requestedCarry(requested, requester)) { + return; + } + requester.sendMessage(ChatColor.WHITE + requested.getName() + ChatColor.GREEN + " has accepted your carry request!"); + requestedMap.remove(requester.getUniqueId()); + requestTime.remove(requester.getUniqueId()); + requester.addPassenger(requested); + } + + public static boolean requestedCarry(final Player requested, final Player requester) { + if (requestedMap.containsKey(requester.getUniqueId())) { + return requestedMap.get(requester.getUniqueId()).equals(requested.getUniqueId()); + } + return false; + } +} diff --git a/src/com/projectkorra/projectkorra/airbending/passive/AirAgility.java b/src/com/projectkorra/projectkorra/airbending/passive/AirAgility.java index b3482d184..82e303482 100644 --- a/src/com/projectkorra/projectkorra/airbending/passive/AirAgility.java +++ b/src/com/projectkorra/projectkorra/airbending/passive/AirAgility.java @@ -6,6 +6,7 @@ import org.bukkit.potion.PotionEffectType; import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; import com.projectkorra.projectkorra.chiblocking.passive.ChiAgility; @@ -13,17 +14,17 @@ public class AirAgility extends AirAbility implements PassiveAbility { - // Configurable variables + // Configurable variables. private int jumpPower; private int speedPower; - // Instance related variables + // Instance related variables. private boolean jumpActivate; private boolean speedActivate; - public AirAgility(Player player) { + public AirAgility(final Player player) { super(player); - setFields(); + this.setFields(); } public void setFields() { @@ -33,48 +34,46 @@ public void setFields() { @Override public void progress() { - if (!player.isSprinting()) { + if (!this.player.isSprinting() || !this.bPlayer.canUsePassive(this) || !this.bPlayer.canBendPassive(this)) { return; } - if (CoreAbility.hasAbility(player, ChiAgility.class)) { - ChiAgility chiAgility = CoreAbility.getAbility(player, ChiAgility.class); - if (chiAgility.getJumpPower() > jumpPower) { - jumpPower = chiAgility.getJumpPower(); + if (CoreAbility.hasAbility(this.player, ChiAgility.class) && this.bPlayer.canBendPassive(CoreAbility.getAbility(ChiAbility.class))) { + final ChiAgility chiAgility = CoreAbility.getAbility(this.player, ChiAgility.class); + if (chiAgility.getJumpPower() > this.jumpPower) { + this.jumpPower = chiAgility.getJumpPower(); } - if (chiAgility.getSpeedPower() > speedPower) { - speedPower = chiAgility.getSpeedPower(); + if (chiAgility.getSpeedPower() > this.speedPower) { + this.speedPower = chiAgility.getSpeedPower(); } } - // Jump Buff - jumpActivate = true; - if (player.hasPotionEffect(PotionEffectType.JUMP)) { - for (PotionEffect potion : player.getActivePotionEffects()) { - if (potion.getType() == PotionEffectType.JUMP) { - if (potion.getAmplifier() > jumpPower - 1) { - jumpActivate = false; - } - } + // Jump Buff. + this.jumpActivate = true; + if (this.player.hasPotionEffect(PotionEffectType.JUMP)) { + final PotionEffect potion = this.player.getPotionEffect(PotionEffectType.JUMP); + if (potion.getAmplifier() > this.jumpPower - 1) { + this.jumpActivate = false; + } else { + this.player.removePotionEffect(PotionEffectType.JUMP); } } - if (jumpActivate) { - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, jumpPower - 1, true, false), false); + if (this.jumpActivate) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, this.jumpPower - 1, true, false), false); } - // Speed Buff - speedActivate = true; - if (player.hasPotionEffect(PotionEffectType.SPEED)) { - for (PotionEffect potion : player.getActivePotionEffects()) { - if (potion.getType() == PotionEffectType.SPEED) { - if (potion.getAmplifier() > speedPower - 1) { - speedActivate = false; - } - } + // Speed Buff. + this.speedActivate = true; + if (this.player.hasPotionEffect(PotionEffectType.SPEED)) { + final PotionEffect potion = this.player.getPotionEffect(PotionEffectType.SPEED); + if (potion.getAmplifier() > this.speedPower - 1) { + this.speedActivate = false; + } else { + this.player.removePotionEffect(PotionEffectType.SPEED); } } - if (speedActivate) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20, speedPower - 1, true, false), false); + if (this.speedActivate) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20, this.speedPower - 1, true, false), false); } } @@ -100,7 +99,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player != null ? this.player.getLocation() : null; } @Override @@ -108,12 +107,17 @@ public boolean isInstantiable() { return true; } + @Override + public boolean isProgressable() { + return true; + } + public int getJumpPower() { - return jumpPower; + return this.jumpPower; } public int getSpeedPower() { - return speedPower; + return this.speedPower; } } diff --git a/src/com/projectkorra/projectkorra/airbending/passive/AirPassive.java b/src/com/projectkorra/projectkorra/airbending/passive/AirPassive.java deleted file mode 100644 index aa8e82676..000000000 --- a/src/com/projectkorra/projectkorra/airbending/passive/AirPassive.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.projectkorra.projectkorra.airbending.passive; - -import com.projectkorra.projectkorra.configuration.ConfigManager; - -public class AirPassive { - - public static double getExhaustionFactor() { - return getFactor(); - } - - public static double getFactor() { - return ConfigManager.getConfig().getDouble("Abilities.Air.Passive.Factor"); - } - - public static int getJumpPower() { - return ConfigManager.getConfig().getInt("Abilities.Air.Passive.AirAgility.JumpPower"); - } - - public static int getSpeedPower() { - return ConfigManager.getConfig().getInt("Abilities.Air.Passive.AirAgility.SpeedPower"); - } -} diff --git a/src/com/projectkorra/projectkorra/airbending/passive/AirSaturation.java b/src/com/projectkorra/projectkorra/airbending/passive/AirSaturation.java index ea0e9afad..434ce514f 100644 --- a/src/com/projectkorra/projectkorra/airbending/passive/AirSaturation.java +++ b/src/com/projectkorra/projectkorra/airbending/passive/AirSaturation.java @@ -5,16 +5,19 @@ import com.projectkorra.projectkorra.ability.AirAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class AirSaturation extends AirAbility implements PassiveAbility { - - public AirSaturation(Player player) { + public AirSaturation(final Player player) { super(player); } + public static double getExhaustionFactor() { + return ConfigManager.getConfig().getDouble("Abilities.Air.Passive.Factor"); + } + @Override public void progress() { - } @Override @@ -39,7 +42,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player.getLocation(); } @Override @@ -47,4 +50,8 @@ public boolean isInstantiable() { return false; } + @Override + public boolean isProgressable() { + return false; + } } diff --git a/src/com/projectkorra/projectkorra/airbending/passive/GracefulDescent.java b/src/com/projectkorra/projectkorra/airbending/passive/GracefulDescent.java index 1ee5e1bd5..8a9cac002 100644 --- a/src/com/projectkorra/projectkorra/airbending/passive/GracefulDescent.java +++ b/src/com/projectkorra/projectkorra/airbending/passive/GracefulDescent.java @@ -8,7 +8,7 @@ public class GracefulDescent extends AirAbility implements PassiveAbility { - public GracefulDescent(Player player) { + public GracefulDescent(final Player player) { super(player); } @@ -47,4 +47,8 @@ public boolean isInstantiable() { return false; } + @Override + public boolean isProgressable() { + return false; + } } diff --git a/src/com/projectkorra/projectkorra/airbending/util/AirbendingManager.java b/src/com/projectkorra/projectkorra/airbending/util/AirbendingManager.java index 925e91b23..28b23bf9b 100644 --- a/src/com/projectkorra/projectkorra/airbending/util/AirbendingManager.java +++ b/src/com/projectkorra/projectkorra/airbending/util/AirbendingManager.java @@ -8,7 +8,7 @@ public class AirbendingManager implements Runnable { public ProjectKorra plugin; - public AirbendingManager(ProjectKorra plugin) { + public AirbendingManager(final ProjectKorra plugin) { this.plugin = plugin; } diff --git a/src/com/projectkorra/projectkorra/attribute/Attribute.java b/src/com/projectkorra/projectkorra/attribute/Attribute.java index 976c55cd3..80c69ed01 100644 --- a/src/com/projectkorra/projectkorra/attribute/Attribute.java +++ b/src/com/projectkorra/projectkorra/attribute/Attribute.java @@ -6,20 +6,23 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) -@Target(value = { ElementType.FIELD}) +@Target(value = { ElementType.FIELD }) public @interface Attribute { - /**This is the attribute name that is added to the CoreAbility name. E.g. - * Returning "Damage" on a FireBlast ability would make the attribute - * "FireBlastDamage"*/ - String value() default ""; - - - /**This is for overriding the attribute name if the name you want should - * not come from the CoreAbility name. E.g. Returning "FastSwimSpeed" would - * make the Attribute name "FastSwimSpeed", instead of ability + "FastSwimSpeed"*/ + /** + * This is the attribute name that is added to the CoreAbility name. E.g. + * Returning "Damage" on a FireBlast ability would make the attribute + * "FireBlastDamage" + */ + String value() default ""; + + /** + * This is for overriding the attribute name if the name you want should not + * come from the CoreAbility name. E.g. Returning "FastSwimSpeed" would make + * the Attribute name "FastSwimSpeed", instead of ability + "FastSwimSpeed" + */ String attribute() default ""; - + public static final String SPEED = "Speed"; public static final String RANGE = "Range"; public static final String SELECT_RANGE = "SelectRange"; @@ -32,5 +35,3 @@ public static final String WIDTH = "Width"; public static final String HEIGHT = "Height"; } - - diff --git a/src/com/projectkorra/projectkorra/attribute/AttributeModifier.java b/src/com/projectkorra/projectkorra/attribute/AttributeModifier.java index ed0cb8b24..f9fcb4845 100644 --- a/src/com/projectkorra/projectkorra/attribute/AttributeModifier.java +++ b/src/com/projectkorra/projectkorra/attribute/AttributeModifier.java @@ -8,58 +8,56 @@ import com.projectkorra.projectkorra.ability.WaterAbility; public class AttributeModifier { - - private String name; + private double modifier = 1.0D; - private Plugin plugin; - private AttributeModifierType type; - - public enum AttributeModifierType {MULTIPLY, ADDITION}; - - public AttributeModifier(String name, double modifier, AttributeModifierType type, Plugin plugin) { - this.name = name; + private final AttributeModifierType type; + + public enum AttributeModifierType { + MULTIPLY, ADDITION + }; + + public AttributeModifier(final String name, final double modifier, final AttributeModifierType type, final Plugin plugin) { this.modifier = modifier; - this.plugin = plugin; this.type = type; } - - public AttributeModifier(String name, AttributeModifierType type, Plugin plugin) { + + public AttributeModifier(final String name, final AttributeModifierType type, final Plugin plugin) { this(name, 1.0D, type, plugin); } - - protected AttributeModifier(String name, AttributeModifierType type, double modifier) { + + protected AttributeModifier(final String name, final AttributeModifierType type, final double modifier) { this(name, modifier, type, ProjectKorra.plugin); } - + /** - * Should return the modifier that should be applied to - * the Attribute. Is called every time it is applied, so - * the value doesn't have to be final. + * Should return the modifier that should be applied to the Attribute. Is + * called every time it is applied, so the value doesn't have to be final. + * * @return The modifier */ - public double getModifier(CoreAbility ability) { - return modifier; + public double getModifier(final CoreAbility ability) { + return this.modifier; } - + /** - * Returns what type of math should be done with the - * modifier. + * Returns what type of math should be done with the modifier. + * * @return The modifier type */ public AttributeModifierType getType() { - return type; + return this.type; } public static AttributeModifier WATERBENDING_NIGHT = new AttributeModifier("WaterbendingNightModifier", AttributeModifierType.MULTIPLY, 1.0) { @Override - public double getModifier(CoreAbility ability) { + public double getModifier(final CoreAbility ability) { return WaterAbility.getNightFactor(ability.getPlayer().getWorld()); } }; - + public static AttributeModifier FIREBENDING_DAY = new AttributeModifier("FirebendingDayModifier", AttributeModifierType.MULTIPLY, 1.0) { @Override - public double getModifier(CoreAbility ability) { + public double getModifier(final CoreAbility ability) { return FireAbility.getDayFactor(1.0, ability.getPlayer().getWorld()); } }; diff --git a/src/com/projectkorra/projectkorra/attribute/Attributes.java b/src/com/projectkorra/projectkorra/attribute/Attributes.java index c6cef5a8c..aac52eb46 100644 --- a/src/com/projectkorra/projectkorra/attribute/Attributes.java +++ b/src/com/projectkorra/projectkorra/attribute/Attributes.java @@ -11,92 +11,94 @@ public class Attributes { /** - * Modifies all abilities of the provided element for the given - * attribute and modifier + * Modifies all abilities of the provided element for the given attribute + * and modifier + * * @param element The type of abilities being changed. Can be a subelement. * @param attribute What attribute to modify * @param modifier The modifier */ - public static void modify(Element element, String attribute, AttributeModifier modifier) { - for (CoreAbility ability : CoreAbility.getAbilitiesByElement(element)) { + public static void modify(final Element element, final String attribute, final AttributeModifier modifier) { + for (final CoreAbility ability : CoreAbility.getAbilitiesByElement(element)) { modify(ability, attribute, modifier); } }; - + /** - * Modifies all the attribute of the provided ability from the - * given attribute and modifier + * Modifies all the attribute of the provided ability from the given + * attribute and modifier + * * @param ability The ability to change * @param attribute What attribute to modify * @param modifier The modifier */ - public static void modify(CoreAbility ability, String attribute, AttributeModifier modifier) { + public static void modify(final CoreAbility ability, final String attribute, final AttributeModifier modifier) { if (ability.getPlayer() == null) { - for (CoreAbility ability2 : CoreAbility.getAbilities(ability.getClass())) { + for (final CoreAbility ability2 : CoreAbility.getAbilities(ability.getClass())) { modify(ability2, attribute, modifier); } return; } - - for (Field field : ability.getClass().getDeclaredFields()) { - if (field.isAnnotationPresent(Attribute.class)) { - Attribute annotation = field.getAnnotation(Attribute.class); - String attrToTest = ability.getName() + annotation.value(); - if (!annotation.attribute().equals("")) { - attrToTest = annotation.attribute(); - } - - if (attrToTest.equalsIgnoreCase(attribute)) { - boolean flag = field.isAccessible(); - - if (!flag) { - field.setAccessible(true); - } - - try { - if (field.getDeclaringClass().equals(Double.TYPE.getClass())) { - double oldValue = field.getDouble(ability); - double newValue = modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability); - - AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); - Bukkit.getPluginManager().callEvent(event); - newValue = event.getNewValue(); - + + for (final Field field : ability.getClass().getDeclaredFields()) { + if (field.isAnnotationPresent(Attribute.class)) { + final Attribute annotation = field.getAnnotation(Attribute.class); + String attrToTest = ability.getName() + annotation.value(); + if (!annotation.attribute().equals("")) { + attrToTest = annotation.attribute(); + } + + if (attrToTest.equalsIgnoreCase(attribute)) { + final boolean flag = field.isAccessible(); + + if (!flag) { + field.setAccessible(true); + } + + try { + if (field.getDeclaringClass().equals(Double.TYPE.getClass())) { + final double oldValue = field.getDouble(ability); + double newValue = modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability); + + final AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); + Bukkit.getPluginManager().callEvent(event); + newValue = event.getNewValue(); + field.setDouble(ability, newValue); - } else if (field.getDeclaringClass().equals(Long.TYPE.getClass())) { - long oldValue = field.getLong(ability); - long newValue = (long) (modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability)); - - AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); - Bukkit.getPluginManager().callEvent(event); - newValue = (long) event.getNewValue(); - + } else if (field.getDeclaringClass().equals(Long.TYPE.getClass())) { + final long oldValue = field.getLong(ability); + long newValue = (long) (modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability)); + + final AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); + Bukkit.getPluginManager().callEvent(event); + newValue = (long) event.getNewValue(); + field.setLong(ability, newValue); - } else if (field.getDeclaringClass().equals(Integer.TYPE.getClass())) { - int oldValue = field.getInt(ability); - int newValue = (int) (modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability)); - - AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); - Bukkit.getPluginManager().callEvent(event); - newValue = (int) event.getNewValue(); - + } else if (field.getDeclaringClass().equals(Integer.TYPE.getClass())) { + final int oldValue = field.getInt(ability); + int newValue = (int) (modifier.getType() == AttributeModifierType.MULTIPLY ? oldValue * modifier.getModifier(ability) : oldValue + modifier.getModifier(ability)); + + final AttributeModifyEvent event = new AttributeModifyEvent(ability, attribute, oldValue, newValue, modifier); + Bukkit.getPluginManager().callEvent(event); + newValue = (int) event.getNewValue(); + field.setInt(ability, newValue); - } - - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block + } + + } + catch (final IllegalArgumentException e) { e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block + } + catch (final IllegalAccessException e) { e.printStackTrace(); } - - if (!flag) { - field.setAccessible(false); - } - } - } + + if (!flag) { + field.setAccessible(false); + } + } + } } } - + } diff --git a/src/com/projectkorra/projectkorra/avatar/AvatarState.java b/src/com/projectkorra/projectkorra/avatar/AvatarState.java index beb33623c..9dde2e74b 100644 --- a/src/com/projectkorra/projectkorra/avatar/AvatarState.java +++ b/src/com/projectkorra/projectkorra/avatar/AvatarState.java @@ -1,23 +1,18 @@ package com.projectkorra.projectkorra.avatar; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.ability.AvatarAbility; -import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.util.Flight; +import java.util.HashMap; -import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import java.util.HashMap; -import java.util.UUID; +import com.projectkorra.projectkorra.ability.AvatarAbility; +import com.projectkorra.projectkorra.attribute.Attribute; public class AvatarState extends AvatarAbility { private static final HashMap START_TIMES = new HashMap<>(); - private static final HashMap GLOBAL_COOLDOWNS = new HashMap(); private boolean regenEnabled; private boolean speedEnabled; @@ -33,16 +28,14 @@ public class AvatarState extends AvatarAbility { private long cooldown; private double factor; - public AvatarState(Player player) { + public AvatarState(final Player player) { super(player); - AvatarState oldAbil = getAbility(player, AvatarState.class); + final AvatarState oldAbil = getAbility(player, AvatarState.class); if (oldAbil != null) { oldAbil.remove(); return; - } else if (bPlayer.isOnCooldown(this)) { - return; - } else if (GLOBAL_COOLDOWNS.containsKey(player.getUniqueId())) { + } else if (this.bPlayer.isOnCooldown(this)) { return; } @@ -58,74 +51,66 @@ public AvatarState(Player player) { this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Cooldown"); this.factor = getConfig().getDouble("Abilities.Avatar.AvatarState.PowerMultiplier"); - new Flight(player); playAvatarSound(player.getLocation()); - start(); - bPlayer.addCooldown(this); - if (duration != 0) { + this.start(); + this.bPlayer.addCooldown(this, true); + if (this.duration != 0) { START_TIMES.put(player.getName(), System.currentTimeMillis()); - GLOBAL_COOLDOWNS.put(player.getUniqueId(), System.currentTimeMillis() + cooldown); - final UUID id = player.getUniqueId(); - Bukkit.getScheduler().runTaskLaterAsynchronously(ProjectKorra.plugin, new Runnable() { - @Override - public void run() { - GLOBAL_COOLDOWNS.remove(id); - } - }, cooldown / 50); + player.getUniqueId(); } } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - if (player != null) { - if (bPlayer.isOnCooldown(this)) { - bPlayer.removeCooldown(this); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (this.player != null) { + if (this.bPlayer.isOnCooldown(this)) { + this.bPlayer.removeCooldown(this); } } - remove(); + this.remove(); return; } - if (START_TIMES.containsKey(player.getName())) { - if (START_TIMES.get(player.getName()) + duration < System.currentTimeMillis()) { - START_TIMES.remove(player.getName()); - remove(); + if (START_TIMES.containsKey(this.player.getName())) { + if (START_TIMES.get(this.player.getName()) + this.duration < System.currentTimeMillis()) { + START_TIMES.remove(this.player.getName()); + this.remove(); return; } } - addPotionEffects(); + this.addPotionEffects(); } private void addPotionEffects() { - int duration = 70; - if (regenEnabled) { - player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, duration, regenPower)); + final int duration = 70; + if (this.regenEnabled) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, duration, this.regenPower)); } - if (speedEnabled) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, duration, speedPower)); + if (this.speedEnabled) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, duration, this.speedPower)); } - if (resistanceEnabled) { - player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, duration, resistancePower)); + if (this.resistanceEnabled) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, duration, this.resistancePower)); } - if (fireResistanceEnabled) { - player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, duration, fireResistancePower)); + if (this.fireResistanceEnabled) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, duration, this.fireResistancePower)); } } - public static double getValue(double value) { - double factor = getConfig().getDouble("Abilities.Avatar.AvatarState.PowerMultiplier"); + public static double getValue(final double value) { + final double factor = getConfig().getDouble("Abilities.Avatar.AvatarState.PowerMultiplier"); return factor * value; } - public static int getValue(int value) { + public static int getValue(final int value) { return (int) getValue((double) value); } - public static double getValue(double value, Player player) { - AvatarState astate = getAbility(player, AvatarState.class); + public static double getValue(final double value, final Player player) { + final AvatarState astate = getAbility(player, AvatarState.class); if (astate != null) { return astate.getFactor() * value; } @@ -139,12 +124,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -158,82 +143,82 @@ public boolean isHarmlessAbility() { } public boolean isRegenEnabled() { - return regenEnabled; + return this.regenEnabled; } - public void setRegenEnabled(boolean regenEnabled) { + public void setRegenEnabled(final boolean regenEnabled) { this.regenEnabled = regenEnabled; } public boolean isSpeedEnabled() { - return speedEnabled; + return this.speedEnabled; } - public void setSpeedEnabled(boolean speedEnabled) { + public void setSpeedEnabled(final boolean speedEnabled) { this.speedEnabled = speedEnabled; } public boolean isResistanceEnabled() { - return resistanceEnabled; + return this.resistanceEnabled; } - public void setResistanceEnabled(boolean resistanceEnabled) { + public void setResistanceEnabled(final boolean resistanceEnabled) { this.resistanceEnabled = resistanceEnabled; } public boolean isFireResistanceEnabled() { - return fireResistanceEnabled; + return this.fireResistanceEnabled; } - public void setFireResistanceEnabled(boolean fireResistanceEnabled) { + public void setFireResistanceEnabled(final boolean fireResistanceEnabled) { this.fireResistanceEnabled = fireResistanceEnabled; } public int getRegenPower() { - return regenPower; + return this.regenPower; } - public void setRegenPower(int regenPower) { + public void setRegenPower(final int regenPower) { this.regenPower = regenPower; } public int getSpeedPower() { - return speedPower; + return this.speedPower; } - public void setSpeedPower(int speedPower) { + public void setSpeedPower(final int speedPower) { this.speedPower = speedPower; } public int getResistancePower() { - return resistancePower; + return this.resistancePower; } - public void setResistancePower(int resistancePower) { + public void setResistancePower(final int resistancePower) { this.resistancePower = resistancePower; } public int getFireResistancePower() { - return fireResistancePower; + return this.fireResistancePower; } - public void setFireResistancePower(int fireResistancePower) { + public void setFireResistancePower(final int fireResistancePower) { this.fireResistancePower = fireResistancePower; } public long getDuration() { - return duration; + return this.duration; } - public void setDuration(long duration) { + public void setDuration(final long duration) { this.duration = duration; } public double getFactor() { - return factor; + return this.factor; } - public void setFactor(double factor) { + public void setFactor(final double factor) { this.factor = factor; } @@ -241,7 +226,7 @@ public static HashMap getStartTimes() { return START_TIMES; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/AcrobatStance.java b/src/com/projectkorra/projectkorra/chiblocking/AcrobatStance.java index 54266f52a..63b7f3b35 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/AcrobatStance.java +++ b/src/com/projectkorra/projectkorra/chiblocking/AcrobatStance.java @@ -18,9 +18,9 @@ public class AcrobatStance extends ChiAbility { private double chiBlockBoost; private double paralyzeDodgeBoost; - public AcrobatStance(Player player) { + public AcrobatStance(final Player player) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.cooldown = getConfig().getLong("Abilities.Chi.AcrobatStance.Cooldown"); @@ -29,46 +29,44 @@ public AcrobatStance(Player player) { this.chiBlockBoost = getConfig().getDouble("Abilities.Chi.AcrobatStance.ChiBlockBoost"); this.paralyzeDodgeBoost = getConfig().getDouble("Abilities.Chi.AcrobatStance.ParalyzeChanceDecrease"); - ChiAbility stance = bPlayer.getStance(); + final ChiAbility stance = this.bPlayer.getStance(); if (stance != null) { + stance.remove(); if (stance instanceof AcrobatStance) { - stance.remove(); + this.bPlayer.setStance(null); return; } - if (stance instanceof WarriorStance) { - stance.remove(); - } } - start(); - bPlayer.setStance(this); + this.start(); + this.bPlayer.setStance(this); GeneralMethods.displayMovePreview(player); player.playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 0.5F, 2F); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBinds(this) || !bPlayer.hasElement(Element.CHI)) { - remove(); + if (!this.bPlayer.canBendIgnoreBinds(this) || !this.bPlayer.hasElement(Element.CHI)) { + this.remove(); return; } - if (!player.hasPotionEffect(PotionEffectType.SPEED)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 60, speed, true)); + if (!this.player.hasPotionEffect(PotionEffectType.SPEED)) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 60, this.speed, true)); } - if (!player.hasPotionEffect(PotionEffectType.JUMP)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 60, jump, true)); + if (!this.player.hasPotionEffect(PotionEffectType.JUMP)) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 60, this.jump, true)); } } @Override public void remove() { super.remove(); - bPlayer.addCooldown(this); - bPlayer.setStance(null); - GeneralMethods.displayMovePreview(player); - player.playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_SHOOT, 0.5F, 2F); - player.removePotionEffect(PotionEffectType.SPEED); - player.removePotionEffect(PotionEffectType.JUMP); + this.bPlayer.addCooldown(this); + this.bPlayer.setStance(null); + GeneralMethods.displayMovePreview(this.player); + this.player.playSound(this.player.getLocation(), Sound.ENTITY_ENDERDRAGON_SHOOT, 0.5F, 2F); + this.player.removePotionEffect(PotionEffectType.SPEED); + this.player.removePotionEffect(PotionEffectType.JUMP); } @Override @@ -78,12 +76,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -97,34 +95,34 @@ public boolean isHarmlessAbility() { } public int getSpeed() { - return speed; + return this.speed; } - public void setSpeed(int speed) { + public void setSpeed(final int speed) { this.speed = speed; } public int getJump() { - return jump; + return this.jump; } - public void setJump(int jump) { + public void setJump(final int jump) { this.jump = jump; } public double getChiBlockBoost() { - return chiBlockBoost; + return this.chiBlockBoost; } - public void setChiBlockBoost(double chiBlockBoost) { + public void setChiBlockBoost(final double chiBlockBoost) { this.chiBlockBoost = chiBlockBoost; } public double getParalyzeDodgeBoost() { - return paralyzeDodgeBoost; + return this.paralyzeDodgeBoost; } - public void setParalyzeDodgeBoost(double paralyzeDodgeBoost) { + public void setParalyzeDodgeBoost(final double paralyzeDodgeBoost) { this.paralyzeDodgeBoost = paralyzeDodgeBoost; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/HighJump.java b/src/com/projectkorra/projectkorra/chiblocking/HighJump.java index 89d737540..d4992cf1f 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/HighJump.java +++ b/src/com/projectkorra/projectkorra/chiblocking/HighJump.java @@ -1,16 +1,16 @@ package com.projectkorra.projectkorra.chiblocking; +import org.bukkit.Location; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.waterbending.multiabilities.WaterArmsWhip; -import org.bukkit.Location; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - public class HighJump extends ChiAbility { @Attribute(Attribute.HEIGHT) @@ -18,36 +18,36 @@ public class HighJump extends ChiAbility { @Attribute(Attribute.COOLDOWN) private long cooldown; - public HighJump(Player player) { + public HighJump(final Player player) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.height = ProjectKorra.plugin.getConfig().getInt("Abilities.Chi.HighJump.Height"); this.cooldown = ProjectKorra.plugin.getConfig().getInt("Abilities.Chi.HighJump.Cooldown"); - start(); + this.start(); } - private void jump(Player p) { + private void jump(final Player p) { if (!GeneralMethods.isSolid(p.getLocation().getBlock().getRelative(BlockFace.DOWN))) { - remove(); + this.remove(); return; } - Vector vec = p.getVelocity(); - vec.setY(height); + final Vector vec = p.getVelocity(); + vec.setY(this.height); p.setVelocity(vec); - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); return; } @Override public void progress() { - if (bPlayer.isOnCooldown(this)) { - remove(); + if (this.bPlayer.isOnCooldown(this)) { + this.remove(); return; } - jump(player); - WaterArmsWhip waw = WaterArmsWhip.getGrabbedEntities().get(player); + this.jump(this.player); + final WaterArmsWhip waw = WaterArmsWhip.getGrabbedEntities().get(this.player); if (waw != null) { waw.setGrabbed(false); } @@ -61,12 +61,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -80,14 +80,14 @@ public boolean isHarmlessAbility() { } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/Paralyze.java b/src/com/projectkorra/projectkorra/chiblocking/Paralyze.java index 352a046e3..007b14bd5 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/Paralyze.java +++ b/src/com/projectkorra/projectkorra/chiblocking/Paralyze.java @@ -9,6 +9,7 @@ import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.ability.ChiAbility; +import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.airbending.Suffocate; import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.command.Commands; @@ -20,44 +21,43 @@ public class Paralyze extends ChiAbility { private long cooldown; private Entity target; - public Paralyze(Player sourceplayer, Entity targetentity) { + public Paralyze(final Player sourceplayer, final Entity targetentity) { super(sourceplayer); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.target = targetentity; this.cooldown = getConfig().getLong("Abilities.Chi.Paralyze.Cooldown"); - start(); + this.start(); } @Override public void progress() { - if (bPlayer.canBend(this)) { - if (target instanceof Player) { - if (Commands.invincible.contains(((Player) target).getName())) { - remove(); + if (this.bPlayer.canBend(this)) { + if (this.target instanceof Player) { + if (Commands.invincible.contains(((Player) this.target).getName())) { + this.remove(); return; } } - paralyze(target); - bPlayer.addCooldown(this); - } else { - remove(); + paralyze(this.target); + this.bPlayer.addCooldown(this); } + this.remove(); } - private static void paralyze(Entity entity) { + private static void paralyze(final Entity entity) { if (entity instanceof Creature) { ((Creature) entity).setTarget(null); } - + if (entity instanceof Player) { if (Suffocate.isChannelingSphere((Player) entity)) { Suffocate.remove((Player) entity); } - } - MovementHandler mh = new MovementHandler((LivingEntity) entity); - mh.stop(getDuration()/1000*20, Element.CHI.getColor() + "* Paralyzed *"); + } + final MovementHandler mh = new MovementHandler((LivingEntity) entity, CoreAbility.getAbility(Paralyze.class)); + mh.stopWithDuration(getDuration() / 1000 * 20, Element.CHI.getColor() + "* Paralyzed *"); entity.getWorld().playSound(entity.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 2, 0); } @@ -68,12 +68,12 @@ public String getName() { @Override public Location getLocation() { - return target != null ? target.getLocation() : null; + return this.target != null ? this.target.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -91,10 +91,10 @@ public static long getDuration() { } public Entity getTarget() { - return target; + return this.target; } - public void setTarget(Entity target) { + public void setTarget(final Entity target) { this.target = target; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/QuickStrike.java b/src/com/projectkorra/projectkorra/chiblocking/QuickStrike.java index f921232c5..5e416c51c 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/QuickStrike.java +++ b/src/com/projectkorra/projectkorra/chiblocking/QuickStrike.java @@ -18,37 +18,41 @@ public class QuickStrike extends ChiAbility { @Attribute(Attribute.COOLDOWN) private long cooldown; - public QuickStrike(Player sourceplayer, Entity targetentity) { + public QuickStrike(final Player sourceplayer, final Entity targetentity) { super(sourceplayer); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.damage = getConfig().getDouble("Abilities.Chi.QuickStrike.Damage"); this.cooldown = getConfig().getLong("Abilities.Chi.QuickStrike.Cooldown"); this.blockChance = getConfig().getInt("Abilities.Chi.QuickStrike.ChiBlockChance"); - target = targetentity; - if (target == null) { + this.target = targetentity; + if (this.target == null) { return; } - start(); + this.start(); } @Override public void progress() { - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { + this.remove(); return; } - if (target == null) { - remove(); + + if (this.target == null) { + this.remove(); return; } - DamageHandler.damageEntity(target, damage, this); - bPlayer.addCooldown(this); - if (target instanceof Player && ChiPassive.willChiBlock(player, (Player) target)) { - ChiPassive.blockChi((Player) target); + + this.bPlayer.addCooldown(this); + DamageHandler.damageEntity(this.target, this.damage, this); + + if (this.target instanceof Player && ChiPassive.willChiBlock(this.player, (Player) this.target)) { + ChiPassive.blockChi((Player) this.target); } - remove(); + this.remove(); } @Override @@ -58,12 +62,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -77,26 +81,26 @@ public boolean isHarmlessAbility() { } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public int getBlockChance() { - return blockChance; + return this.blockChance; } - public void setBlockChance(int blockChance) { + public void setBlockChance(final int blockChance) { this.blockChance = blockChance; } public Entity getTarget() { - return target; + return this.target; } - public void setTarget(Entity target) { + public void setTarget(final Entity target) { this.target = target; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/chiblocking/RapidPunch.java b/src/com/projectkorra/projectkorra/chiblocking/RapidPunch.java index 0c2f3cd25..7fd154d50 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/RapidPunch.java +++ b/src/com/projectkorra/projectkorra/chiblocking/RapidPunch.java @@ -20,46 +20,47 @@ public class RapidPunch extends ChiAbility { @Attribute(Attribute.COOLDOWN) private long cooldown; private int numPunches; - private long interval, last = 0; + private long interval; + private final long last = 0; private Entity target; - public RapidPunch(Player sourceplayer, Entity targetentity) { + public RapidPunch(final Player sourceplayer, final Entity targetentity) { super(sourceplayer); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } - + this.damage = getConfig().getDouble("Abilities.Chi.RapidPunch.Damage"); this.punches = getConfig().getInt("Abilities.Chi.RapidPunch.Punches"); this.cooldown = getConfig().getLong("Abilities.Chi.RapidPunch.Cooldown"); this.interval = getConfig().getLong("Abilities.Chi.RapidPunch.Interval"); this.target = targetentity; - bPlayer.addCooldown(this); - start(); + this.bPlayer.addCooldown(this); + this.start(); } @Override public void progress() { - if (numPunches >= punches || target == null || !(target instanceof LivingEntity)) { - remove(); + if (this.numPunches >= this.punches || this.target == null || !(this.target instanceof LivingEntity)) { + this.remove(); return; } - if (System.currentTimeMillis() >= last + interval) { - LivingEntity lt = (LivingEntity) target; - DamageHandler.damageEntity(target, damage, this); - - if (target instanceof Player) { - if (ChiPassive.willChiBlock(player, (Player) target)) { - ChiPassive.blockChi((Player) target); + if (System.currentTimeMillis() >= this.last + this.interval) { + final LivingEntity lt = (LivingEntity) this.target; + DamageHandler.damageEntity(this.target, this.damage, this); + + if (this.target instanceof Player) { + if (ChiPassive.willChiBlock(this.player, (Player) this.target)) { + ChiPassive.blockChi((Player) this.target); } - if (Suffocate.isChannelingSphere((Player) target)) { - Suffocate.remove((Player) target); + if (Suffocate.isChannelingSphere((Player) this.target)) { + Suffocate.remove((Player) this.target); } } - + lt.setNoDamageTicks(0); - numPunches++; + this.numPunches++; } } @@ -70,12 +71,12 @@ public String getName() { @Override public Location getLocation() { - return target != null ? target.getLocation() : null; + return this.target != null ? this.target.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -89,38 +90,38 @@ public boolean isHarmlessAbility() { } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public int getPunches() { - return punches; + return this.punches; } - public void setPunches(int punches) { + public void setPunches(final int punches) { this.punches = punches; } public int getNumPunches() { - return numPunches; + return this.numPunches; } - public void setNumPunches(int numPunches) { + public void setNumPunches(final int numPunches) { this.numPunches = numPunches; } public Entity getTarget() { - return target; + return this.target; } - public void setTarget(Entity target) { + public void setTarget(final Entity target) { this.target = target; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/Smokescreen.java b/src/com/projectkorra/projectkorra/chiblocking/Smokescreen.java index e89046352..e94c33eca 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/Smokescreen.java +++ b/src/com/projectkorra/projectkorra/chiblocking/Smokescreen.java @@ -1,9 +1,7 @@ package com.projectkorra.projectkorra.chiblocking; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.ChiAbility; -import com.projectkorra.projectkorra.attribute.Attribute; -import com.projectkorra.projectkorra.command.Commands; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; @@ -13,8 +11,10 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.ChiAbility; +import com.projectkorra.projectkorra.attribute.Attribute; +import com.projectkorra.projectkorra.command.Commands; public class Smokescreen extends ChiAbility { @@ -29,31 +29,31 @@ public class Smokescreen extends ChiAbility { @Attribute(Attribute.RADIUS) private double radius; - public Smokescreen(Player player) { + public Smokescreen(final Player player) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.cooldown = getConfig().getLong("Abilities.Chi.Smokescreen.Cooldown"); this.duration = getConfig().getInt("Abilities.Chi.Smokescreen.Duration"); this.radius = getConfig().getDouble("Abilities.Chi.Smokescreen.Radius"); - start(); + this.start(); } @Override public void progress() { - SNOWBALLS.put(player.launchProjectile(Snowball.class).getEntityId(), this); - bPlayer.addCooldown(this); - remove(); + SNOWBALLS.put(this.player.launchProjectile(Snowball.class).getEntityId(), this); + this.bPlayer.addCooldown(this); + this.remove(); } - public static void playEffect(Location loc) { + public static void playEffect(final Location loc) { int z = -2; int x = -2; - int y = 0; + final int y = 0; for (int i = 0; i < 125; i++) { - Location newLoc = new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y, loc.getZ() + z); + final Location newLoc = new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y, loc.getZ() + z); for (int direction = 0; direction < 8; direction++) { loc.getWorld().playEffect(newLoc, Effect.SMOKE, direction); } @@ -68,25 +68,25 @@ public static void playEffect(Location loc) { } } - public void applyBlindness(Entity entity) { + public void applyBlindness(final Entity entity) { if (entity instanceof Player) { if (Commands.invincible.contains(((Player) entity).getName())) { return; } else if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { return; } - Player p = (Player) entity; - p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, duration * 20, 2)); + final Player p = (Player) entity; + p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, this.duration * 20, 2)); BLINDED_TIMES.put(p.getName(), System.currentTimeMillis()); BLINDED_TO_ABILITY.put(p.getName(), this); } } - public static void removeFromHashMap(Entity entity) { + public static void removeFromHashMap(final Entity entity) { if (entity instanceof Player) { - Player p = (Player) entity; + final Player p = (Player) entity; if (BLINDED_TIMES.containsKey(p.getName())) { - Smokescreen smokescreen = BLINDED_TO_ABILITY.get(p.getName()); + final Smokescreen smokescreen = BLINDED_TO_ABILITY.get(p.getName()); if (BLINDED_TIMES.get(p.getName()) + smokescreen.duration >= System.currentTimeMillis()) { BLINDED_TIMES.remove(p.getName()); BLINDED_TO_ABILITY.remove(p.getName()); @@ -102,12 +102,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -120,23 +120,23 @@ public boolean isHarmlessAbility() { return false; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } public int getDuration() { - return duration; + return this.duration; } - public void setDuration(int duration) { + public void setDuration(final int duration) { this.duration = duration; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/SwiftKick.java b/src/com/projectkorra/projectkorra/chiblocking/SwiftKick.java index ff0c288dd..7e924db9f 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/SwiftKick.java +++ b/src/com/projectkorra/projectkorra/chiblocking/SwiftKick.java @@ -19,34 +19,34 @@ public class SwiftKick extends ChiAbility { private long cooldown; private Entity target; - public SwiftKick(Player sourceplayer, Entity targetentity) { + public SwiftKick(final Player sourceplayer, final Entity targetentity) { super(sourceplayer); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.damage = getConfig().getDouble("Abilities.Chi.SwiftKick.Damage"); this.blockChance = getConfig().getInt("Abilities.Chi.SwiftKick.ChiBlockChance"); this.cooldown = getConfig().getInt("Abilities.Chi.SwiftKick.Cooldown"); this.target = targetentity; - start(); + this.start(); } @Override public void progress() { - if (target == null) { - remove(); + if (this.target == null) { + this.remove(); return; } - if (player.getLocation().subtract(0, 0.5, 0).getBlock().getType() != Material.AIR) { - remove(); + if (this.player.getLocation().subtract(0, 0.5, 0).getBlock().getType() != Material.AIR) { + this.remove(); return; } - DamageHandler.damageEntity(target, damage, this); - if (target instanceof Player && ChiPassive.willChiBlock(player, (Player) target)) { - ChiPassive.blockChi((Player) target); + DamageHandler.damageEntity(this.target, this.damage, this); + if (this.target instanceof Player && ChiPassive.willChiBlock(this.player, (Player) this.target)) { + ChiPassive.blockChi((Player) this.target); } - bPlayer.addCooldown(this); - remove(); + this.bPlayer.addCooldown(this); + this.remove(); } @Override @@ -56,12 +56,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -75,30 +75,30 @@ public boolean isHarmlessAbility() { } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public int getBlockChance() { - return blockChance; + return this.blockChance; } - public void setBlockChance(int blockChance) { + public void setBlockChance(final int blockChance) { this.blockChance = blockChance; } public Entity getTarget() { - return target; + return this.target; } - public void setTarget(Entity target) { + public void setTarget(final Entity target) { this.target = target; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/WarriorStance.java b/src/com/projectkorra/projectkorra/chiblocking/WarriorStance.java index 76c016762..6f16daba0 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/WarriorStance.java +++ b/src/com/projectkorra/projectkorra/chiblocking/WarriorStance.java @@ -16,55 +16,55 @@ public class WarriorStance extends ChiAbility { private int strength; private int resistance; - public WarriorStance(Player player) { + public WarriorStance(final Player player) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.cooldown = getConfig().getLong("Abilities.Chi.WarriorStance.Cooldown"); this.strength = getConfig().getInt("Abilities.Chi.WarriorStance.Strength") - 1; this.resistance = getConfig().getInt("Abilities.Chi.WarriorStance.Resistance"); - ChiAbility stance = bPlayer.getStance(); + final ChiAbility stance = this.bPlayer.getStance(); if (stance != null) { + stance.remove(); if (stance instanceof WarriorStance) { - stance.remove(); + this.bPlayer.setStance(null); return; } - if (stance instanceof AcrobatStance) { - stance.remove(); - } } - start(); - bPlayer.setStance(this); + this.start(); + this.bPlayer.setStance(this); GeneralMethods.displayMovePreview(player); player.playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 0.5F, 2F); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBinds(this) || !bPlayer.hasElement(Element.CHI)) { - remove(); + if (!this.bPlayer.canBendIgnoreBinds(this) || !this.bPlayer.hasElement(Element.CHI)) { + this.remove(); return; } - if (!player.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 60, resistance, true)); + if (!this.player.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 60, this.resistance, true)); } - if (!player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 60, strength, true)); + if (!this.player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 60, this.strength, true)); } } @Override public void remove() { super.remove(); - bPlayer.addCooldown(this); - bPlayer.setStance(null); - GeneralMethods.displayMovePreview(player); - player.playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_SHOOT, 0.5F, 2F); - player.removePotionEffect(PotionEffectType.DAMAGE_RESISTANCE); - player.removePotionEffect(PotionEffectType.INCREASE_DAMAGE); + this.bPlayer.addCooldown(this); + this.bPlayer.setStance(null); + if (this.player != null) { + GeneralMethods.displayMovePreview(this.player); + this.player.playSound(this.player.getLocation(), Sound.ENTITY_ENDERDRAGON_SHOOT, 0.5F, 2F); + this.player.removePotionEffect(PotionEffectType.DAMAGE_RESISTANCE); + this.player.removePotionEffect(PotionEffectType.INCREASE_DAMAGE); + } } @Override @@ -74,12 +74,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -93,18 +93,18 @@ public boolean isHarmlessAbility() { } public int getStrength() { - return strength; + return this.strength; } - public void setStrength(int strength) { + public void setStrength(final int strength) { this.strength = strength; } public int getResistance() { - return resistance; + return this.resistance; } - public void setResistance(int resistance) { + public void setResistance(final int resistance) { this.resistance = resistance; } diff --git a/src/com/projectkorra/projectkorra/chiblocking/combo/Immobilize.java b/src/com/projectkorra/projectkorra/chiblocking/combo/Immobilize.java index 2b2b9a55b..ad0197ae6 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/combo/Immobilize.java +++ b/src/com/projectkorra/projectkorra/chiblocking/combo/Immobilize.java @@ -11,7 +11,9 @@ import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.ComboAbility; +import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.MovementHandler; public class Immobilize extends ChiAbility implements ComboAbility { @@ -19,35 +21,35 @@ public class Immobilize extends ChiAbility implements ComboAbility { private long duration; private long cooldown; private Entity target; - - public Immobilize(Player player) { + + public Immobilize(final Player player) { super(player); - + this.cooldown = getConfig().getLong("Abilities.Chi.Immobilize.Cooldown"); this.duration = getConfig().getLong("Abilities.Chi.Immobilize.ParalyzeDuration"); - target = GeneralMethods.getTargetedEntity(player, 5); - if (!bPlayer.canBendIgnoreBinds(this)) { + this.target = GeneralMethods.getTargetedEntity(player, 5); + if (!this.bPlayer.canBendIgnoreBinds(this)) { return; } - if (target == null) { - remove(); + if (this.target == null) { + this.remove(); return; } else { - paralyze(target, duration); - bPlayer.addCooldown(this); + paralyze(this.target, this.duration); + this.bPlayer.addCooldown(this); } } - + /** * Paralyzes the target for the given duration. The player will be unable to * move or interact for the duration. - * + * * @param target The Entity to be paralyzed * @param duration The time in milliseconds the target will be paralyzed */ - private static void paralyze(Entity target, Long duration) { - MovementHandler mh = new MovementHandler((LivingEntity) target); - mh.stop(duration/1000*20, Element.CHI.getColor() + "* Immobilized *"); + private static void paralyze(final Entity target, final Long duration) { + final MovementHandler mh = new MovementHandler((LivingEntity) target, CoreAbility.getAbility(Immobilize.class)); + mh.stopWithDuration(duration / 1000 * 20, Element.CHI.getColor() + "* Immobilized *"); } @Override @@ -61,7 +63,6 @@ public void progress() { @Override public boolean isSneakAbility() { - // TODO Auto-generated method stub return true; } @@ -72,41 +73,51 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public Location getLocation() { - return target != null ? target.getLocation() : null; + return this.target != null ? this.target.getLocation() : null; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new Immobilize(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList immobilize = new ArrayList<>(); + immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); + immobilize.add(new AbilityInformation("SwiftKick", ClickType.LEFT_CLICK_ENTITY)); + immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); + immobilize.add(new AbilityInformation("QuickStrike", ClickType.LEFT_CLICK_ENTITY)); + return immobilize; } - + public long getDuration() { - return duration; + return this.duration; } - public void setDuration(long duration) { + public void setDuration(final long duration) { this.duration = duration; } public Entity getTarget() { - return target; + return this.target; } - public void setTarget(Entity target) { + public void setTarget(final Entity target) { this.target = target; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } + + @Override + public String getInstructions() { + return "QuickStrike > SwiftKick > QuickStrike > QuickStrike"; + } } diff --git a/src/com/projectkorra/projectkorra/chiblocking/passive/Acrobatics.java b/src/com/projectkorra/projectkorra/chiblocking/passive/Acrobatics.java index 2da78062e..02bfdaa2e 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/passive/Acrobatics.java +++ b/src/com/projectkorra/projectkorra/chiblocking/passive/Acrobatics.java @@ -5,16 +5,19 @@ import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class Acrobatics extends ChiAbility implements PassiveAbility { - - public Acrobatics(Player player) { + public Acrobatics(final Player player) { super(player); } + public static double getFallReductionFactor() { + return ConfigManager.getConfig().getDouble("Abilities.Chi.Passive.Acrobatics.FallReductionFactor"); + } + @Override public void progress() { - } @Override @@ -39,7 +42,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player.getLocation(); } @Override @@ -47,4 +50,8 @@ public boolean isInstantiable() { return false; } + @Override + public boolean isProgressable() { + return false; + } } diff --git a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiAgility.java b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiAgility.java index e45349e64..c32655211 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiAgility.java +++ b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiAgility.java @@ -5,6 +5,7 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import com.projectkorra.projectkorra.ability.AirAbility; import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; @@ -14,17 +15,17 @@ public class ChiAgility extends ChiAbility implements PassiveAbility { - // Configurable variables + // Configurable variables. private int jumpPower; private int speedPower; - // Instance related variables + // Instance related variables. private boolean jumpActivate; private boolean speedActivate; - public ChiAgility(Player player) { + public ChiAgility(final Player player) { super(player); - setFields(); + this.setFields(); } public void setFields() { @@ -34,58 +35,51 @@ public void setFields() { @Override public void progress() { - if (!player.isSprinting()) { + if (!this.player.isSprinting() || !this.bPlayer.canUsePassive(this) || !this.bPlayer.canBendPassive(this)) { return; } - if (CoreAbility.hasAbility(player, AirAgility.class)) { - AirAgility airAgility = CoreAbility.getAbility(player, AirAgility.class); - if (airAgility.getJumpPower() > jumpPower) { - jumpPower = airAgility.getJumpPower(); + if (CoreAbility.hasAbility(this.player, AirAgility.class) && this.bPlayer.canBendPassive(CoreAbility.getAbility(AirAbility.class))) { + final AirAgility airAgility = CoreAbility.getAbility(this.player, AirAgility.class); + if (airAgility.getJumpPower() > this.jumpPower) { + this.jumpPower = airAgility.getJumpPower(); } - if (airAgility.getSpeedPower() > speedPower) { - speedPower = airAgility.getSpeedPower(); + if (airAgility.getSpeedPower() > this.speedPower) { + this.speedPower = airAgility.getSpeedPower(); } } - // Jump Buff - int jMax = jumpPower; - if (hasAbility(player, AcrobatStance.class)) { - AcrobatStance stance = getAbility(player, AcrobatStance.class); - jMax = Math.max(jMax, stance.getJump()); + if (hasAbility(this.player, AcrobatStance.class)) { + final AcrobatStance stance = getAbility(this.player, AcrobatStance.class); + this.jumpPower = Math.max(this.jumpPower, stance.getJump()); + this.speedPower = Math.max(this.speedPower, stance.getSpeed()); } - jumpActivate = true; - if (player.hasPotionEffect(PotionEffectType.JUMP)) { - for (PotionEffect potion : player.getActivePotionEffects()) { - if (potion.getType() == PotionEffectType.JUMP) { - if (potion.getAmplifier() > jMax - 1) { - jumpActivate = false; - } - } + // Jump Buff. + this.jumpActivate = true; + if (this.player.hasPotionEffect(PotionEffectType.JUMP)) { + final PotionEffect potion = this.player.getPotionEffect(PotionEffectType.JUMP); + if (potion.getAmplifier() > this.jumpPower - 1) { + this.jumpActivate = false; + } else { + this.player.removePotionEffect(PotionEffectType.JUMP); } } - if (jumpActivate) { - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, jMax - 1, true, false), false); + if (this.jumpActivate) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 20, this.jumpPower - 1, true, false), false); } - // Speed Buff - int sMax = speedPower; - if (hasAbility(player, AcrobatStance.class)) { - AcrobatStance stance = getAbility(player, AcrobatStance.class); - sMax = Math.max(sMax, stance.getJump()); - } - speedActivate = true; - if (player.hasPotionEffect(PotionEffectType.SPEED)) { - for (PotionEffect potion : player.getActivePotionEffects()) { - if (potion.getType() == PotionEffectType.SPEED) { - if (potion.getAmplifier() > sMax - 1) { - speedActivate = false; - } - } + // Speed Buff. + this.speedActivate = true; + if (this.player.hasPotionEffect(PotionEffectType.SPEED)) { + final PotionEffect potion = this.player.getPotionEffect(PotionEffectType.SPEED); + if (potion.getAmplifier() > this.speedPower - 1) { + this.speedActivate = false; + } else { + this.player.removePotionEffect(PotionEffectType.SPEED); } } - if (speedActivate) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20, sMax - 1, true, false), false); + if (this.speedActivate) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20, this.speedPower - 1, true, false), false); } } @@ -119,12 +113,17 @@ public boolean isInstantiable() { return true; } + @Override + public boolean isProgressable() { + return true; + } + public int getJumpPower() { - return jumpPower; + return this.jumpPower; } public int getSpeedPower() { - return speedPower; + return this.speedPower; } } diff --git a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiPassive.java b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiPassive.java index 8e098bd82..fd34dafc3 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiPassive.java +++ b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiPassive.java @@ -17,16 +17,15 @@ import com.projectkorra.projectkorra.util.ActionBar; public class ChiPassive { - - public static boolean willChiBlock(Player attacker, Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean willChiBlock(final Player attacker, final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return false; } - ChiAbility stance = bPlayer.getStance(); - QuickStrike quickStrike = CoreAbility.getAbility(player, QuickStrike.class); - SwiftKick swiftKick = CoreAbility.getAbility(player, SwiftKick.class); + final ChiAbility stance = bPlayer.getStance(); + final QuickStrike quickStrike = CoreAbility.getAbility(player, QuickStrike.class); + final SwiftKick swiftKick = CoreAbility.getAbility(player, SwiftKick.class); double newChance = getChance(); if (stance != null && stance instanceof AcrobatStance) { @@ -44,6 +43,7 @@ public static boolean willChiBlock(Player attacker, Player player) { } else if (bPlayer.isChiBlocked()) { return false; } + return true; } @@ -56,38 +56,23 @@ public static void blockChi(final Player player) { if (bPlayer == null) { return; } + bPlayer.blockChi(); player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ENDERDRAGON_HURT, 2, 0); - - long start = System.currentTimeMillis(); + + final long start = System.currentTimeMillis(); new BukkitRunnable() { @Override public void run() { ActionBar.sendActionBar(Element.CHI.getColor() + "* Chiblocked *", player); if (System.currentTimeMillis() >= start + getDuration()) { bPlayer.unblockChi(); - cancel(); + this.cancel(); } } }.runTaskTimer(ProjectKorra.plugin, 0, 1); } - public static double getExhaustionFactor() { - return ConfigManager.getConfig().getDouble("Abilities.Chi.Passive.ChiSaturation.ExhaustionFactor"); - } - - public static double getFallReductionFactor() { - return ConfigManager.getConfig().getDouble("Abilities.Chi.Passive.Acrobatics.FallReductionFactor"); - } - - public static int getJumpPower() { - return ConfigManager.getConfig().getInt("Abilities.Chi.Passive.ChiAgility.JumpPower"); - } - - public static int getSpeedPower() { - return ConfigManager.getConfig().getInt("Abilities.Chi.Passive.ChiAgility.SpeedPower"); - } - public static double getChance() { return ConfigManager.getConfig().getDouble("Abilities.Chi.Passive.BlockChi.Chance"); } @@ -99,5 +84,4 @@ public static int getDuration() { public static long getTicks() { return (getDuration() / 1000) * 20; } - } diff --git a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiSaturation.java b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiSaturation.java index a32e48aa0..24b2f46b1 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/passive/ChiSaturation.java +++ b/src/com/projectkorra/projectkorra/chiblocking/passive/ChiSaturation.java @@ -5,16 +5,19 @@ import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class ChiSaturation extends ChiAbility implements PassiveAbility { - - public ChiSaturation(Player player) { + public ChiSaturation(final Player player) { super(player); } + public static double getExhaustionFactor() { + return ConfigManager.getConfig().getDouble("Abilities.Chi.Passive.ChiSaturation.ExhaustionFactor"); + } + @Override public void progress() { - } @Override @@ -39,7 +42,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player.getLocation(); } @Override @@ -47,4 +50,8 @@ public boolean isInstantiable() { return false; } + @Override + public boolean isProgressable() { + return false; + } } diff --git a/src/com/projectkorra/projectkorra/chiblocking/util/ChiblockingManager.java b/src/com/projectkorra/projectkorra/chiblocking/util/ChiblockingManager.java index 37c5d1fa2..674f667d4 100644 --- a/src/com/projectkorra/projectkorra/chiblocking/util/ChiblockingManager.java +++ b/src/com/projectkorra/projectkorra/chiblocking/util/ChiblockingManager.java @@ -9,13 +9,13 @@ public class ChiblockingManager implements Runnable { public ProjectKorra plugin; - public ChiblockingManager(ProjectKorra plugin) { + public ChiblockingManager(final ProjectKorra plugin) { this.plugin = plugin; } @Override public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { + for (final Player player : Bukkit.getOnlinePlayers()) { Smokescreen.removeFromHashMap(player); } } diff --git a/src/com/projectkorra/projectkorra/command/AddCommand.java b/src/com/projectkorra/projectkorra/command/AddCommand.java index ea0a22d56..edd03fe34 100644 --- a/src/com/projectkorra/projectkorra/command/AddCommand.java +++ b/src/com/projectkorra/projectkorra/command/AddCommand.java @@ -1,5 +1,14 @@ package com.projectkorra.projectkorra.command; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.Element.SubElement; @@ -9,34 +18,25 @@ import com.projectkorra.projectkorra.event.PlayerChangeElementEvent.Result; import com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - /** * Executor for /bending add. Extends {@link PKCommand}. */ public class AddCommand extends PKCommand { - private String playerNotFound; - private String invalidElement; - private String addedOtherCFW; - private String addedOtherAE; - private String addedCFW; - private String addedAE; - private String alreadyHasElementOther; - private String alreadyHasElement; - private String alreadyHasSubElementOther; - private String alreadyHasSubElement; - private String addedOtherAll; - private String addedAll; - private String alreadyHasAllElementsOther; - private String alreadyHasAllElements; + private final String playerNotFound; + private final String invalidElement; + private final String addedOtherCFW; + private final String addedOtherAE; + private final String addedCFW; + private final String addedAE; + private final String alreadyHasElementOther; + private final String alreadyHasElement; + private final String alreadyHasSubElementOther; + private final String alreadyHasSubElement; + private final String addedOtherAll; + private final String addedAll; + private final String alreadyHasAllElementsOther; + private final String alreadyHasAllElements; public AddCommand() { super("add", "/bending add [Player]", ConfigManager.languageConfig.get().getString("Commands.Add.Description"), new String[] { "add", "a" }); @@ -57,66 +57,67 @@ public AddCommand() { this.alreadyHasAllElements = ConfigManager.languageConfig.get().getString("Commands.Add.AlreadyHasAllElements"); } - public void execute(CommandSender sender, List args) { - if (!correctLength(sender, args.size(), 1, 2)) { + @Override + public void execute(final CommandSender sender, final List args) { + if (!this.correctLength(sender, args.size(), 1, 2)) { return; - } else if (args.size() == 1) { //bending add element - if (!hasPermission(sender) || !isPlayer(sender)) { + } else if (args.size() == 1) { // bending add element. + if (!this.hasPermission(sender) || !this.isPlayer(sender)) { return; } - add(sender, (Player) sender, args.get(0).toLowerCase()); - } else if (args.size() == 2) { //bending add element combo - if (!hasPermission(sender, "others")) { + this.add(sender, (Player) sender, args.get(0).toLowerCase()); + } else if (args.size() == 2) { // bending add element combo. + if (!this.hasPermission(sender, "others")) { return; } - Player player = Bukkit.getPlayer(args.get(1)); + final Player player = Bukkit.getPlayer(args.get(1)); if (player == null) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playerNotFound); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerNotFound); return; } - add(sender, player, args.get(0).toLowerCase()); + this.add(sender, player, args.get(0).toLowerCase()); } } /** * Adds the ability to bend an element to a player. - * + * * @param sender The CommandSender who issued the add command * @param target The player to add the element to * @param element The element to add */ - private void add(CommandSender sender, Player target, String element) { - - // if they aren't a BendingPlayer, create them + private void add(final CommandSender sender, final Player target, final String element) { + + // if they aren't a BendingPlayer, create them. BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target); if (bPlayer == null) { GeneralMethods.createBendingPlayer(target.getUniqueId(), target.getName()); bPlayer = BendingPlayer.getBendingPlayer(target); - } else if (bPlayer.isPermaRemoved()) { //ignore permabanned users + } else if (bPlayer.isPermaRemoved()) { // ignore permabanned users. GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + ConfigManager.languageConfig.get().getString("Commands.Preset.Other.BendingPermanentlyRemoved")); return; } - - + if (element.toLowerCase().equals("all")) { - StringBuilder elements = new StringBuilder(""); + final StringBuilder elements = new StringBuilder(""); boolean elementFound = false; - for (Element e : Element.getAllElements()) { + for (final Element e : Element.getAllElements()) { if (!bPlayer.hasElement(e) && e != Element.AVATAR) { elementFound = true; bPlayer.addElement(e); - - if (elements.length() > 1) + + if (elements.length() > 1) { elements.append(ChatColor.YELLOW + ", "); + } elements.append(e.getColor() + e.getName()); - + bPlayer.getSubElements().clear(); - for (SubElement sub : Element.getAllSubElements()) { + for (final SubElement sub : Element.getAllSubElements()) { if (bPlayer.hasElement(sub.getParentElement()) && bPlayer.hasSubElementPermission(sub)) { bPlayer.addSubElement(sub); } } - + GeneralMethods.saveElements(bPlayer); GeneralMethods.saveSubElements(bPlayer); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeElementEvent(sender, target, e, Result.ADD)); @@ -124,125 +125,127 @@ private void add(CommandSender sender, Player target, String element) { } if (elementFound) { if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + addedOtherAll.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.YELLOW) + elements); - GeneralMethods.sendBrandingMessage(target, ChatColor.YELLOW + addedAll + elements); + GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + this.addedOtherAll.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.YELLOW) + elements); + GeneralMethods.sendBrandingMessage(target, ChatColor.YELLOW + this.addedAll + elements); } else { - GeneralMethods.sendBrandingMessage(target, ChatColor.YELLOW + addedAll + elements); + GeneralMethods.sendBrandingMessage(target, ChatColor.YELLOW + this.addedAll + elements); } } else { if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasAllElementsOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasAllElementsOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasAllElements); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasAllElements); } - } + } return; - } - else { - - // get the [sub]element + } else { + + // get the [sub]element. Element e = Element.fromString(element); if (e == null) { - e = SubElement.fromString(element); + e = Element.fromString(element); } - + if (e == Element.AVATAR) { - add(sender, target, Element.AIR.getName()); - add(sender, target, Element.EARTH.getName()); - add(sender, target, Element.FIRE.getName()); - add(sender, target, Element.WATER.getName()); + this.add(sender, target, Element.AIR.getName()); + this.add(sender, target, Element.EARTH.getName()); + this.add(sender, target, Element.FIRE.getName()); + this.add(sender, target, Element.WATER.getName()); return; } - - //if it's an element: + + // if it's an element: if (Arrays.asList(Element.getAllElements()).contains(e)) { - if (bPlayer.hasElement(e)) { // if already had, determine who to send the error message to + if (bPlayer.hasElement(e)) { // if already had, determine who to send the error message to. if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasElement); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasElement); } return; } - - //add all allowed subelements + + // add all allowed subelements. bPlayer.addElement(e); bPlayer.getSubElements().clear(); - for (SubElement sub : Element.getAllSubElements()) { + for (final SubElement sub : Element.getAllSubElements()) { if (bPlayer.hasElement(sub.getParentElement()) && bPlayer.hasSubElementPermission(sub)) { bPlayer.addSubElement(sub); } } - //send the message - ChatColor color = e.getColor(); + // send the message. + final ChatColor color = e.getColor(); if (!(sender instanceof Player) || !((Player) sender).equals(target)) { if (e != Element.AIR && e != Element.EARTH) { - GeneralMethods.sendBrandingMessage(sender, color + addedOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", e.getName() + e.getType().getBender())); - GeneralMethods.sendBrandingMessage(target, color + addedCFW.replace("{element}", e.getName() + e.getType().getBender())); + GeneralMethods.sendBrandingMessage(sender, color + this.addedOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", e.getName() + e.getType().getBender())); + GeneralMethods.sendBrandingMessage(target, color + this.addedCFW.replace("{element}", e.getName() + e.getType().getBender())); } else { - GeneralMethods.sendBrandingMessage(sender, color + addedOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", e.getName() + e.getType().getBender())); - GeneralMethods.sendBrandingMessage(target, color + addedAE.replace("{element}", e.getName() + e.getType().getBender())); + GeneralMethods.sendBrandingMessage(sender, color + this.addedOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", e.getName() + e.getType().getBender())); + GeneralMethods.sendBrandingMessage(target, color + this.addedAE.replace("{element}", e.getName() + e.getType().getBender())); } } else { - if (e != Element.AIR && e != Element.EARTH) - GeneralMethods.sendBrandingMessage(target, color + addedCFW.replace("{element}", e.getName() + e.getType().getBender())); - else - GeneralMethods.sendBrandingMessage(target, color + addedAE.replace("{element}", e.getName() + e.getType().getBender())); + if (e != Element.AIR && e != Element.EARTH) { + GeneralMethods.sendBrandingMessage(target, color + this.addedCFW.replace("{element}", e.getName() + e.getType().getBender())); + } else { + GeneralMethods.sendBrandingMessage(target, color + this.addedAE.replace("{element}", e.getName() + e.getType().getBender())); + } } GeneralMethods.saveElements(bPlayer); GeneralMethods.saveSubElements(bPlayer); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeElementEvent(sender, target, e, Result.ADD)); return; - - //if it's a sub element: - } else if (Arrays.asList(Element.getAllSubElements()).contains(e)) { - SubElement sub = (SubElement) e; - if (bPlayer.hasSubElement(sub)) { // if already had, determine who to send the error message to + + // if it's a sub element: + } else if (Arrays.asList(Element.getAllSubElements()).contains(e)) { + final SubElement sub = (SubElement) e; + if (bPlayer.hasSubElement(sub)) { // if already had, determine who to send the error message to. if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasSubElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasSubElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + alreadyHasSubElement); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.alreadyHasSubElement); } return; } bPlayer.addSubElement(sub); - ChatColor color = e.getColor(); + final ChatColor color = e.getColor(); if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - if (e != Element.AIR && e != Element.EARTH) - GeneralMethods.sendBrandingMessage(sender, color + addedOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); - else - GeneralMethods.sendBrandingMessage(sender, color + addedOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); + if (e != Element.AIR && e != Element.EARTH) { + GeneralMethods.sendBrandingMessage(sender, color + this.addedOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); + } else { + GeneralMethods.sendBrandingMessage(sender, color + this.addedOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); + } } else { - if (e != Element.AIR && e != Element.EARTH) - GeneralMethods.sendBrandingMessage(target, color + addedCFW.replace("{element}", sub.getName() + sub.getType().getBender())); - else - GeneralMethods.sendBrandingMessage(target, color + addedAE.replace("{element}", sub.getName() + sub.getType().getBender())); + if (e != Element.AIR && e != Element.EARTH) { + GeneralMethods.sendBrandingMessage(target, color + this.addedCFW.replace("{element}", sub.getName() + sub.getType().getBender())); + } else { + GeneralMethods.sendBrandingMessage(target, color + this.addedAE.replace("{element}", sub.getName() + sub.getType().getBender())); + } } GeneralMethods.saveSubElements(bPlayer); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeSubElementEvent(sender, target, sub, com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent.Result.ADD)); return; - + } else { // bad element. - sender.sendMessage(ChatColor.RED + invalidElement); + sender.sendMessage(ChatColor.RED + this.invalidElement); } - + } } - - public static boolean isVowel(char c) { + public static boolean isVowel(final char c) { return "AEIOUaeiou".indexOf(c) != -1; } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 2 || !sender.hasPermission("bending.command.add")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 2 || !sender.hasPermission("bending.command.add")) { return new ArrayList(); - List l = new ArrayList(); + } + final List l = new ArrayList(); if (args.size() == 0) { l.add("Air"); @@ -250,7 +253,7 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("Fire"); l.add("Water"); l.add("Chi"); - for (Element e : Element.getAddonElements()) { + for (final Element e : Element.getAddonElements()) { l.add(e.getName()); } @@ -265,14 +268,14 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("Plant"); l.add("Sand"); l.add("Spiritual"); - for (SubElement e : Element.getAddonSubElements()) { + for (final SubElement e : Element.getAddonSubElements()) { l.add(e.getName()); } } else { - for (Player p : Bukkit.getOnlinePlayers()) { + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } } return l; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/command/BendingTabComplete.java b/src/com/projectkorra/projectkorra/command/BendingTabComplete.java index e95a28683..f9a7d558a 100644 --- a/src/com/projectkorra/projectkorra/command/BendingTabComplete.java +++ b/src/com/projectkorra/projectkorra/command/BendingTabComplete.java @@ -1,32 +1,33 @@ package com.projectkorra.projectkorra.command; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; + /** * Completes tabbing for the bending command/subcommands. - * + * * @author StrangeOne101 */ public class BendingTabComplete implements TabCompleter { @Override - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - if (args.length == 0 || args.length == 1) + public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { + if (args.length == 0 || args.length == 1) { return getPossibleCompletions(args, getCommandsForUser(sender)); - else if (args.length > 1) { - for (PKCommand cmd : PKCommand.instances.values()) { + } else if (args.length > 1) { + for (final PKCommand cmd : PKCommand.instances.values()) { if (Arrays.asList(cmd.getAliases()).contains(args[0].toLowerCase()) && sender.hasPermission("bending.command." + cmd.getName())) { - List newargs = new ArrayList(); + final List newargs = new ArrayList(); for (int i = 1; i < args.length - 1; i++) { - if (!(args[i].equals("") || args[i].equals(" ")) && args.length >= 1) + if (!(args[i].equals("") || args[i].equals(" ")) && args.length >= 1) { newargs.add(args[i]); + } } return getPossibleCompletions(args, cmd.getTabCompletion(sender, newargs)); } @@ -39,7 +40,7 @@ else if (args.length > 1) { /** * Breaks down the possible list and returns what is applicble depending on * what the user has currently typed. - * + * * @author D4rKDeagle
*
* (Found at @@ -48,12 +49,12 @@ else if (args.length > 1) { * @param args Args of the command. Provide all of them. * @param possibilitiesOfCompletion List of things that can be given */ - public static List getPossibleCompletions(String[] args, List possibilitiesOfCompletion) { - String argumentToFindCompletionFor = args[args.length - 1]; + public static List getPossibleCompletions(final String[] args, final List possibilitiesOfCompletion) { + final String argumentToFindCompletionFor = args[args.length - 1]; - List listOfPossibleCompletions = new ArrayList(); + final List listOfPossibleCompletions = new ArrayList(); - for (String foundString : possibilitiesOfCompletion) { + for (final String foundString : possibilitiesOfCompletion) { if (foundString.regionMatches(true, 0, argumentToFindCompletionFor, 0, argumentToFindCompletionFor.length())) { listOfPossibleCompletions.add(foundString); } @@ -61,16 +62,17 @@ public static List getPossibleCompletions(String[] args, List po return listOfPossibleCompletions; } - public static List getPossibleCompletions(String[] args, String[] possibilitiesOfCompletion) { + public static List getPossibleCompletions(final String[] args, final String[] possibilitiesOfCompletion) { return getPossibleCompletions(args, Arrays.asList(possibilitiesOfCompletion)); } /** Returns a list of subcommands the sender can use. */ - public static List getCommandsForUser(CommandSender sender) { - List list = new ArrayList(); - for (String cmd : PKCommand.instances.keySet()) { - if (sender.hasPermission("bending.command." + cmd.toLowerCase())) + public static List getCommandsForUser(final CommandSender sender) { + final List list = new ArrayList(); + for (final String cmd : PKCommand.instances.keySet()) { + if (sender.hasPermission("bending.command." + cmd.toLowerCase())) { list.add(cmd); + } } Collections.sort(list); return list; diff --git a/src/com/projectkorra/projectkorra/command/BindCommand.java b/src/com/projectkorra/projectkorra/command/BindCommand.java index c442b60f9..c71ebed61 100644 --- a/src/com/projectkorra/projectkorra/command/BindCommand.java +++ b/src/com/projectkorra/projectkorra/command/BindCommand.java @@ -1,5 +1,14 @@ package com.projectkorra.projectkorra.command; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.Element.SubElement; @@ -9,28 +18,19 @@ import com.projectkorra.projectkorra.ability.PassiveAbility; import com.projectkorra.projectkorra.configuration.ConfigManager; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - /** * Executor for /bending bind. Extends {@link PKCommand}. */ public class BindCommand extends PKCommand { - private String abilityDoesntExist; - private String wrongNumber; - private String loadingInfo; - private String toggledElementOff; - private String noElement; - private String noElementAE; - private String noSubElement; - private String unbindable; + private final String abilityDoesntExist; + private final String wrongNumber; + private final String loadingInfo; + private final String toggledElementOff; + private final String noElement; + private final String noElementAE; + private final String noSubElement; + private final String unbindable; public BindCommand() { super("bind", "/bending bind [Slot]", ConfigManager.languageConfig.get().getString("Commands.Bind.Description"), new String[] { "bind", "b" }); @@ -46,53 +46,53 @@ public BindCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 1, 2) || !isPlayer(sender)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 1, 2) || !this.isPlayer(sender)) { return; } - CoreAbility coreAbil = CoreAbility.getAbility(args.get(0)); + final CoreAbility coreAbil = CoreAbility.getAbility(args.get(0)); if (coreAbil == null || !coreAbil.isEnabled()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + abilityDoesntExist.replace("{ability}", args.get(0))); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.abilityDoesntExist.replace("{ability}", args.get(0))); return; } else if (coreAbil instanceof PassiveAbility || coreAbil instanceof ComboAbility || coreAbil.isHiddenAbility()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + unbindable.replace("{ability}", args.get(0))); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.unbindable.replace("{ability}", args.get(0))); return; - } + } - // bending bind [Ability] + // bending bind [Ability]. if (args.size() == 1) { - bind(sender, args.get(0), ((Player) sender).getInventory().getHeldItemSlot() + 1); + this.bind(sender, args.get(0), ((Player) sender).getInventory().getHeldItemSlot() + 1); } - // bending bind [ability] [#] + // bending bind [ability] [#]. if (args.size() == 2) { try { - bind(sender, args.get(0), Integer.parseInt(args.get(1))); + this.bind(sender, args.get(0), Integer.parseInt(args.get(1))); } - catch (NumberFormatException ex) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongNumber); + catch (final NumberFormatException ex) { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongNumber); } } } - private void bind(CommandSender sender, String ability, int slot) { + private void bind(final CommandSender sender, final String ability, final int slot) { if (!(sender instanceof Player)) { return; } else if (slot < 1 || slot > 9) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongNumber); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongNumber); return; } - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer((Player) sender); - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer((Player) sender); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (bPlayer == null) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + loadingInfo); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.loadingInfo); return; } else if (coreAbil == null || !bPlayer.canBind(coreAbil)) { if (coreAbil != null && coreAbil.getElement() != Element.AVATAR && !bPlayer.hasElement(coreAbil.getElement())) { if (coreAbil.getElement() instanceof SubElement) { - SubElement sub = (SubElement) coreAbil.getElement(); + final SubElement sub = (SubElement) coreAbil.getElement(); if (!bPlayer.hasElement(sub.getParentElement())) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + ("AEIOUaeiou".indexOf(sub.getParentElement().getName().charAt(0)) > -1 ? this.noElementAE : this.noElement).replace("{element}", sub.getParentElement().getName() + sub.getParentElement().getType().getBender())); } else { @@ -106,24 +106,25 @@ private void bind(CommandSender sender, String ability, int slot) { } return; } else if (!bPlayer.isElementToggled(coreAbil.getElement())) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + toggledElementOff); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.toggledElementOff); } - String name = coreAbil != null ? coreAbil.getName() : null; + final String name = coreAbil != null ? coreAbil.getName() : null; GeneralMethods.bindAbility((Player) sender, name, slot); } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 2 || !sender.hasPermission("bending.command.bind") || !(sender instanceof Player)) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 2 || !sender.hasPermission("bending.command.bind") || !(sender instanceof Player)) { return new ArrayList(); + } List abilities = new ArrayList(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); if (args.size() == 0) { if (bPlayer != null) { - for (CoreAbility coreAbil : CoreAbility.getAbilities()) { - if (!coreAbil.isHiddenAbility() && bPlayer.canBind(coreAbil) && !(coreAbil instanceof PassiveAbility || coreAbil instanceof ComboAbility) && !abilities.contains(coreAbil.getName())) { + for (final CoreAbility coreAbil : CoreAbility.getAbilities()) { + if (!coreAbil.isHiddenAbility() && bPlayer.canBind(coreAbil) && !(coreAbil instanceof PassiveAbility || coreAbil instanceof ComboAbility) && !abilities.contains(coreAbil.getName())) { abilities.add(coreAbil.getName()); } } @@ -135,4 +136,4 @@ protected List getTabCompletion(CommandSender sender, List args) Collections.sort(abilities); return abilities; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/command/CheckCommand.java b/src/com/projectkorra/projectkorra/command/CheckCommand.java index daa033879..e2595bf79 100644 --- a/src/com/projectkorra/projectkorra/command/CheckCommand.java +++ b/src/com/projectkorra/projectkorra/command/CheckCommand.java @@ -1,22 +1,22 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import java.util.List; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * Executor for /bending check. Extends {@link PKCommand}. */ public class CheckCommand extends PKCommand { - private String newVersionAvailable; - private String curVersion; - private String newVersion; - private String upToDate; + private final String newVersionAvailable; + private final String curVersion; + private final String newVersion; + private final String upToDate; public CheckCommand() { super("check", "/bending check", ConfigManager.languageConfig.get().getString("Commands.Check.Description"), new String[] { "check", "chk" }); @@ -28,14 +28,16 @@ public CheckCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender)) { return; } else if (args.size() > 0) { - help(sender, false); + this.help(sender, false); return; } - if (ProjectKorra.plugin.updater.updateAvailable()) { + if (!ProjectKorra.plugin.updater.isEnabled()) { + sender.sendMessage(ChatColor.YELLOW + "The update checker has been disabled in the config. Please enable it in order to use this command."); + } else if (ProjectKorra.plugin.updater.updateAvailable()) { sender.sendMessage(ChatColor.GREEN + this.newVersionAvailable.replace("ProjectKorra", ChatColor.GOLD + "ProjectKorra" + ChatColor.GREEN)); sender.sendMessage(ChatColor.YELLOW + this.curVersion.replace("{version}", ChatColor.RED + ProjectKorra.plugin.updater.getCurrentVersion() + ChatColor.YELLOW)); sender.sendMessage(ChatColor.YELLOW + this.newVersion.replace("{version}", ChatColor.GOLD + ProjectKorra.plugin.updater.getUpdateVersion() + ChatColor.YELLOW)); diff --git a/src/com/projectkorra/projectkorra/command/ChooseCommand.java b/src/com/projectkorra/projectkorra/command/ChooseCommand.java index a45530930..feee50ef8 100644 --- a/src/com/projectkorra/projectkorra/command/ChooseCommand.java +++ b/src/com/projectkorra/projectkorra/command/ChooseCommand.java @@ -1,5 +1,14 @@ package com.projectkorra.projectkorra.command; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.Element.SubElement; @@ -9,45 +18,41 @@ import com.projectkorra.projectkorra.event.PlayerChangeElementEvent; import com.projectkorra.projectkorra.event.PlayerChangeElementEvent.Result; import com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import com.projectkorra.projectkorra.util.TimeUtil; /** * Executor for /bending choose. Extends {@link PKCommand}. */ public class ChooseCommand extends PKCommand { - private String invalidElement; - private String playerNotFound; - private String chosenCFW; - private String chosenAE; - private String chosenOtherCFW; - private String chosenOtherAE; + private final String invalidElement; + private final String playerNotFound; + private final String onCooldown; + private final String chosenCFW; + private final String chosenAE; + private final String chosenOtherCFW; + private final String chosenOtherAE; + private final long cooldown; public ChooseCommand() { super("choose", "/bending choose [Player]", ConfigManager.languageConfig.get().getString("Commands.Choose.Description"), new String[] { "choose", "ch" }); this.playerNotFound = ConfigManager.languageConfig.get().getString("Commands.Choose.PlayerNotFound"); this.invalidElement = ConfigManager.languageConfig.get().getString("Commands.Choose.InvalidElement"); + this.onCooldown = ConfigManager.languageConfig.get().getString("Commands.Choose.OnCooldown"); this.chosenCFW = ConfigManager.languageConfig.get().getString("Commands.Choose.SuccessfullyChosenCFW"); this.chosenAE = ConfigManager.languageConfig.get().getString("Commands.Choose.SuccessfullyChosenAE"); this.chosenOtherCFW = ConfigManager.languageConfig.get().getString("Commands.Choose.Other.SuccessfullyChosenCFW"); this.chosenOtherAE = ConfigManager.languageConfig.get().getString("Commands.Choose.Other.SuccessfullyChosenAE"); + this.cooldown = ConfigManager.defaultConfig.get().getLong("Properties.ChooseCooldown"); } @Override - public void execute(CommandSender sender, List args) { - if (!correctLength(sender, args.size(), 1, 2)) { + public void execute(final CommandSender sender, final List args) { + if (!this.correctLength(sender, args.size(), 1, 2)) { return; } else if (args.size() == 1) { - if (!hasPermission(sender) || !isPlayer(sender)) { + if (!this.hasPermission(sender) || !this.isPlayer(sender)) { return; } @@ -60,31 +65,46 @@ public void execute(CommandSender sender, List args) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + ConfigManager.languageConfig.get().getString("Commands.Preset.BendingPermanentlyRemoved")); return; } - if (!bPlayer.getElements().isEmpty() && !sender.hasPermission("bending.command.rechoose")) { GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); return; } String element = args.get(0).toLowerCase(); - if (element.equalsIgnoreCase("a")) + if (element.equalsIgnoreCase("a")) { element = "air"; - else if (element.equalsIgnoreCase("e")) + } else if (element.equalsIgnoreCase("e")) { element = "earth"; - else if (element.equalsIgnoreCase("f")) + } else if (element.equalsIgnoreCase("f")) { element = "fire"; - else if (element.equalsIgnoreCase("w")) + } else if (element.equalsIgnoreCase("w")) { element = "water"; - else if (element.equalsIgnoreCase("c")) + } else if (element.equalsIgnoreCase("c")) { element = "chi"; - Element targetElement = Element.getElement(element); + } + final Element targetElement = Element.getElement(element); if (Arrays.asList(Element.getAllElements()).contains(targetElement)) { - if (!hasPermission(sender, element)) { + if (!this.hasPermission(sender, element)) { return; } - add(sender, (Player) sender, targetElement); + if (bPlayer.isOnCooldown("ChooseElement")) { + if (sender.hasPermission("bending.choose.ignorecooldown") || sender.hasPermission("bending.admin.choose")) { + bPlayer.removeCooldown("ChooseElement"); + } else { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.onCooldown.replace("%cooldown%", TimeUtil.formatTime(bPlayer.getCooldown("ChooseElement") - System.currentTimeMillis()))); + return; + } + } + + this.add(sender, (Player) sender, targetElement); + + if (sender.hasPermission("bending.choose.ignorecooldown") || sender.hasPermission("bending.admin.choose")) { + return; + } + + bPlayer.addCooldown("ChooseElement", this.cooldown, true); return; } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + invalidElement); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.invalidElement); return; } } else if (args.size() == 2) { @@ -92,76 +112,87 @@ else if (element.equalsIgnoreCase("c")) GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); return; } - Player target = ProjectKorra.plugin.getServer().getPlayer(args.get(1)); + final Player target = ProjectKorra.plugin.getServer().getPlayer(args.get(1)); if (target == null || !target.isOnline()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playerNotFound); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerNotFound); return; } String element = args.get(0).toLowerCase(); - if (element.equalsIgnoreCase("a")) + if (element.equalsIgnoreCase("a")) { element = "air"; - else if (element.equalsIgnoreCase("e")) + } else if (element.equalsIgnoreCase("e")) { element = "earth"; - else if (element.equalsIgnoreCase("f")) + } else if (element.equalsIgnoreCase("f")) { element = "fire"; - else if (element.equalsIgnoreCase("w")) + } else if (element.equalsIgnoreCase("w")) { element = "water"; - else if (element.equalsIgnoreCase("c")) + } else if (element.equalsIgnoreCase("c")) { element = "chi"; - Element targetElement = Element.getElement(element); + } + final Element targetElement = Element.getElement(element); if (Arrays.asList(Element.getAllElements()).contains(targetElement) && targetElement != Element.AVATAR) { - add(sender, target, targetElement); + this.add(sender, target, targetElement); + + if (target.hasPermission("bending.choose.ignorecooldown") || target.hasPermission("bending.admin.choose")) { + return; + } + + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target); + bPlayer.addCooldown("ChooseElement", this.cooldown, true); + return; } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + invalidElement); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.invalidElement); } } } /** * Adds the ability to bend the given element to the specified Player. - * + * * @param sender The CommandSender who issued the command * @param target The Player to add the element to * @param element The element to add to the Player */ - private void add(CommandSender sender, Player target, Element element) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target); + private void add(final CommandSender sender, final Player target, final Element element) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target); if (bPlayer == null) { return; } if (element instanceof SubElement) { - SubElement sub = (SubElement) element; + final SubElement sub = (SubElement) element; bPlayer.addSubElement(sub); - ChatColor color = sub != null ? sub.getColor() : ChatColor.WHITE; + final ChatColor color = sub != null ? sub.getColor() : ChatColor.WHITE; if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - GeneralMethods.sendBrandingMessage(sender, color + chosenOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); + GeneralMethods.sendBrandingMessage(sender, color + this.chosenOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", sub.getName() + sub.getType().getBender())); } else { - GeneralMethods.sendBrandingMessage(target, color + chosenCFW.replace("{element}", sub.getName() + sub.getType().getBender())); + GeneralMethods.sendBrandingMessage(target, color + this.chosenCFW.replace("{element}", sub.getName() + sub.getType().getBender())); } GeneralMethods.saveSubElements(bPlayer); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeSubElementEvent(sender, target, sub, com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent.Result.CHOOSE)); } else { bPlayer.setElement(element); bPlayer.getSubElements().clear(); - for (SubElement sub : Element.getAllSubElements()) { + for (final SubElement sub : Element.getAllSubElements()) { if (bPlayer.hasElement(sub.getParentElement()) && bPlayer.hasSubElementPermission(sub)) { bPlayer.addSubElement(sub); } } - ChatColor color = element != null ? element.getColor() : ChatColor.WHITE; + final ChatColor color = element != null ? element.getColor() : ChatColor.WHITE; if (!(sender instanceof Player) || !((Player) sender).equals(target)) { - if (element != Element.AIR && element != Element.EARTH) - GeneralMethods.sendBrandingMessage(sender, color + chosenOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", element.getName() + element.getType().getBender())); - else - GeneralMethods.sendBrandingMessage(sender, color + chosenOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", element.getName() + element.getType().getBender())); + if (element != Element.AIR && element != Element.EARTH) { + GeneralMethods.sendBrandingMessage(sender, color + this.chosenOtherCFW.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", element.getName() + element.getType().getBender())); + } else { + GeneralMethods.sendBrandingMessage(sender, color + this.chosenOtherAE.replace("{target}", ChatColor.DARK_AQUA + target.getName() + color).replace("{element}", element.getName() + element.getType().getBender())); + } } else { - if (element != Element.AIR && element != Element.EARTH) - GeneralMethods.sendBrandingMessage(target, color + chosenCFW.replace("{element}", element.getName() + element.getType().getBender())); - else - GeneralMethods.sendBrandingMessage(target, color + chosenAE.replace("{element}", element.getName() + element.getType().getBender())); + if (element != Element.AIR && element != Element.EARTH) { + GeneralMethods.sendBrandingMessage(target, color + this.chosenCFW.replace("{element}", element.getName() + element.getType().getBender())); + } else { + GeneralMethods.sendBrandingMessage(target, color + this.chosenAE.replace("{element}", element.getName() + element.getType().getBender())); + } } GeneralMethods.saveElements(bPlayer); GeneralMethods.saveSubElements(bPlayer); @@ -172,16 +203,17 @@ private void add(CommandSender sender, Player target, Element element) { } - public static boolean isVowel(char c) { + public static boolean isVowel(final char c) { return "AEIOUaeiou".indexOf(c) != -1; } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 2 || !sender.hasPermission("bending.command.choose")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 2 || !sender.hasPermission("bending.command.choose")) { return new ArrayList(); + } - List l = new ArrayList(); + final List l = new ArrayList(); if (args.size() == 0) { l.add("Air"); @@ -189,11 +221,11 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("Fire"); l.add("Water"); l.add("Chi"); - for (Element e : Element.getAddonElements()) { + for (final Element e : Element.getAddonElements()) { l.add(e.getName()); } } else { - for (Player p : Bukkit.getOnlinePlayers()) { + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } } diff --git a/src/com/projectkorra/projectkorra/command/ClearCommand.java b/src/com/projectkorra/projectkorra/command/ClearCommand.java index 1ac07ce35..98d4ad1e4 100644 --- a/src/com/projectkorra/projectkorra/command/ClearCommand.java +++ b/src/com/projectkorra/projectkorra/command/ClearCommand.java @@ -1,28 +1,28 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.util.MultiAbilityManager; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.util.MultiAbilityManager; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * Executor for /bending clear. Extends {@link PKCommand}. */ public class ClearCommand extends PKCommand { - private String cantEditBinds; - private String cleared; - private String wrongNumber; - private String clearedSlot; - private String alreadyEmpty; + private final String cantEditBinds; + private final String cleared; + private final String wrongNumber; + private final String clearedSlot; + private final String alreadyEmpty; public ClearCommand() { super("clear", "/bending clear [Slot]", ConfigManager.languageConfig.get().getString("Commands.Clear.Description"), new String[] { "clear", "cl", "c" }); @@ -35,11 +35,11 @@ public ClearCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 1) || !isPlayer(sender)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 1) || !this.isPlayer(sender)) { return; } else if (MultiAbilityManager.hasMultiAbilityBound((Player) sender)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + cantEditBinds); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.cantEditBinds); return; } @@ -53,31 +53,32 @@ public void execute(CommandSender sender, List args) { for (int i = 1; i <= 9; i++) { GeneralMethods.saveAbility(bPlayer, i, null); } - GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + cleared); + GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + this.cleared); } else if (args.size() == 1) { try { - int slot = Integer.parseInt(args.get(0)); + final int slot = Integer.parseInt(args.get(0)); if (slot < 1 || slot > 9) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongNumber); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongNumber); } if (bPlayer.getAbilities().get(slot) != null) { bPlayer.getAbilities().remove(slot); GeneralMethods.saveAbility(bPlayer, slot, null); - GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + clearedSlot.replace("{slot}", String.valueOf(slot))); + GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + this.clearedSlot.replace("{slot}", String.valueOf(slot))); } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + alreadyEmpty); + GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + this.alreadyEmpty); } } - catch (NumberFormatException e) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongNumber); + catch (final NumberFormatException e) { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongNumber); } } } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 1 || !sender.hasPermission("bending.command.clear")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 1 || !sender.hasPermission("bending.command.clear")) { return new ArrayList(); + } return Arrays.asList("123456789".split("")); } diff --git a/src/com/projectkorra/projectkorra/command/Commands.java b/src/com/projectkorra/projectkorra/command/Commands.java index 589618b16..ae2fd2fdf 100644 --- a/src/com/projectkorra/projectkorra/command/Commands.java +++ b/src/com/projectkorra/projectkorra/command/Commands.java @@ -1,36 +1,33 @@ package com.projectkorra.projectkorra.command; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.configuration.ConfigManager; public class Commands { - private ProjectKorra plugin; + private final ProjectKorra plugin; public static Set invincible = new HashSet(); public static boolean debugEnabled = false; public static boolean isToggledForAll = false; - public Commands(ProjectKorra plugin) { + public Commands(final ProjectKorra plugin) { this.plugin = plugin; debugEnabled = ProjectKorra.plugin.getConfig().getBoolean("debug"); - init(); + this.init(); } - /* - * Element Aliases - */ + // Element Aliases. public static String[] airaliases = { "air", "a", "airbending", "airbender" }; public static String[] chialiases = { "chi", "c", "chiblocking", "chiblocker" }; public static String[] earthaliases = { "earth", "e", "earthbending", "earthbender" }; @@ -39,9 +36,7 @@ public Commands(ProjectKorra plugin) { public static String[] elementaliases = { "air", "a", "airbending", "airbender", "chi", "c", "chiblocking", "chiblocker", "earth", "e", "earthbending", "earthbender", "fire", "f", "firebending", "firebender", "water", "w", "waterbending", "waterbender" }; public static String[] avataraliases = { "avatar", "av", "avy", "aang", "korra" }; - /* - * Combo Aliases - */ + // Combo Aliases. public static String[] aircomboaliases = { "aircombo", "ac", "aircombos", "airbendingcombos" }; public static String[] chicomboaliases = { "chicombo", "cc", "chicombos", "chiblockingcombos", "chiblockercombos" }; public static String[] earthcomboaliases = { "earthcombo", "ec", "earthcombos", "earthbendingcombos" }; @@ -50,43 +45,40 @@ public Commands(ProjectKorra plugin) { public static String[] comboaliases = { "aircombo", "ac", "aircombos", "airbendingcombos", "chicombo", "cc", "chicombos", "chiblockingcombos", "chiblockercombos", "earthcombo", "ec", "earthcombos", "earthbendingcombos", "firecombo", "fc", "firecombos", "firebendingcombos", "watercombo", "wc", "watercombos", "waterbendingcombos" }; - /* - * Passive Aliases - */ - + // Passive Aliases. public static String[] passivealiases = { "airpassive", "ap", "airpassives", "airbendingpassives", "chipassive", "cp", "chipassives", "chiblockingpassives", "chiblockerpassives", "earthpassive", "ep", "earthpassives", "earthbendingpassives", "firepassive", "fp", "firepassives", "firebendingpassives", "waterpassive", "wp", "waterpassives", "waterbendingpassives" }; - /* - * Subelement Aliases - */ - + // Subelement Aliases. public static String[] subelementaliases = { "flight", "fl", "spiritualprojection", "sp", "spiritual", "bloodbending", "bb", "healing", "heal", "icebending", "ice", "ib", "plantbending", "plant", "metalbending", "mb", "metal", "lavabending", "lb", "lava", "sandbending", "sb", "sand", "combustionbending", "combustion", "cb", "lightningbending", "lightning" }; - //Air + + // Air. public static String[] flightaliases = { "flight", "fl" }; public static String[] spiritualprojectionaliases = { "spiritualprojection", "sp", "spiritual" }; - //Water + // Water. public static String[] bloodaliases = { "bloodbending", "bb" }; public static String[] healingaliases = { "healing", "heal" }; public static String[] icealiases = { "icebending", "ice", "ib" }; public static String[] plantaliases = { "plantbending", "plant" }; - //Earth + // Earth. public static String[] metalbendingaliases = { "metalbending", "mb", "metal" }; public static String[] lavabendingaliases = { "lavabending", "lb", "lava" }; public static String[] sandbendingaliases = { "sandbending", "sb", "sand" }; - //Firebending + // Fire. public static String[] combustionaliases = { "combustionbending", "combustion", "cb" }; public static String[] lightningaliases = { "lightningbending", "lightning" }; - //Miscellaneous + // Miscellaneous. public static String[] commandaliases = { "b", "pk", "projectkorra", "bending", "mtla", "tla", "korra", "bend" }; - private List help; - private void init() { - PluginCommand projectkorra = plugin.getCommand("projectkorra"); + final PluginCommand projectkorra = this.plugin.getCommand("projectkorra"); + + /** + * Set of all of the Classes which extend Command + */ new AddCommand(); new BindCommand(); new CheckCommand(); @@ -96,46 +88,35 @@ private void init() { new DebugCommand(); new DisplayCommand(); new HelpCommand(); - new ImportCommand(); new InvincibleCommand(); new PermaremoveCommand(); new PresetCommand(); new ReloadCommand(); new RemoveCommand(); + new StatsCommand(); new ToggleCommand(); new VersionCommand(); new WhoCommand(); - help = ConfigManager.languageConfig.get().getStringList("Commands.GeneralHelpLines"); - - /** - * Set of all of the Classes which extend Command - */ - - CommandExecutor exe; - - exe = new CommandExecutor() { + final CommandExecutor exe = new CommandExecutor() { @Override - public boolean onCommand(CommandSender s, Command c, String label, String[] args) { + public boolean onCommand(final CommandSender s, final Command c, final String label, final String[] args) { + if (Arrays.asList(commandaliases).contains(label.toLowerCase())) { + if (args.length > 0) { + final List sendingArgs = Arrays.asList(args).subList(1, args.length); + for (final PKCommand command : PKCommand.instances.values()) { + if (Arrays.asList(command.getAliases()).contains(args[0].toLowerCase())) { + command.execute(s, sendingArgs); + return true; + } + } + } - if (args.length == 0 && Arrays.asList(commandaliases).contains(label.toLowerCase())) { - for (String line : help) - s.sendMessage(ChatColor.translateAlternateColorCodes('&', line)); + PKCommand.instances.get("help").execute(s, new ArrayList()); return true; } - List sendingArgs = Arrays.asList(args).subList(1, args.length); - for (PKCommand command : PKCommand.instances.values()) { - if (Arrays.asList(command.getAliases()).contains(args[0].toLowerCase())) { - command.execute(s, sendingArgs); - return true; - } - } - - for (String line : help) - s.sendMessage(ChatColor.translateAlternateColorCodes('&', line)); - - return true; + return false; } }; projectkorra.setExecutor(exe); diff --git a/src/com/projectkorra/projectkorra/command/CopyCommand.java b/src/com/projectkorra/projectkorra/command/CopyCommand.java index 7015d432e..4e4e7b057 100644 --- a/src/com/projectkorra/projectkorra/command/CopyCommand.java +++ b/src/com/projectkorra/projectkorra/command/CopyCommand.java @@ -1,26 +1,26 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class CopyCommand extends PKCommand { - private String playerNotFound; - private String copied; - private String failedToBindAll; - private String copiedOther; + private final String playerNotFound; + private final String copied; + private final String failedToBindAll; + private final String copiedOther; public CopyCommand() { super("copy", "/bending copy [Player]", ConfigManager.languageConfig.get().getString("Commands.Copy.Description"), new String[] { "copy", "co" }); @@ -32,61 +32,60 @@ public CopyCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!correctLength(sender, args.size(), 1, 2)) { + public void execute(final CommandSender sender, final List args) { + if (!this.correctLength(sender, args.size(), 1, 2)) { return; } else if (args.size() == 1) { - if (!hasPermission(sender) || !isPlayer(sender)) { + if (!this.hasPermission(sender) || !this.isPlayer(sender)) { return; } - Player orig = Bukkit.getPlayer(args.get(0)); + final Player orig = Bukkit.getPlayer(args.get(0)); if (orig == null || !orig.isOnline()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playerNotFound); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerNotFound); return; } - boolean boundAll = assignAbilities(sender, orig, (Player) sender, true); - GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + copied.replace("{target}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); + final boolean boundAll = this.assignAbilities(sender, orig, (Player) sender, true); + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.copied.replace("{target}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); if (!boundAll) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + failedToBindAll); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.failedToBindAll); } } else if (args.size() == 2) { - if (!hasPermission(sender, "assign")) { + if (!this.hasPermission(sender, "assign")) { GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); return; } - Player orig = ProjectKorra.plugin.getServer().getPlayer(args.get(0)); - Player target = ProjectKorra.plugin.getServer().getPlayer(args.get(1)); + final Player orig = ProjectKorra.plugin.getServer().getPlayer(args.get(0)); + final Player target = ProjectKorra.plugin.getServer().getPlayer(args.get(1)); if ((orig == null || !orig.isOnline()) || (target == null || !target.isOnline())) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playerNotFound); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerNotFound); return; } - boolean boundAll = assignAbilities(sender, orig, target, false); - GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + copiedOther.replace("{target1}", ChatColor.YELLOW + target.getName() + ChatColor.GREEN).replace("{target2}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); - GeneralMethods.sendBrandingMessage(target, ChatColor.GREEN + copied.replace("{target}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); + final boolean boundAll = this.assignAbilities(sender, orig, target, false); + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.copiedOther.replace("{target1}", ChatColor.YELLOW + target.getName() + ChatColor.GREEN).replace("{target2}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); + GeneralMethods.sendBrandingMessage(target, ChatColor.GREEN + this.copied.replace("{target}", ChatColor.YELLOW + orig.getName() + ChatColor.GREEN)); if (!boundAll) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + failedToBindAll); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.failedToBindAll); } } } - @SuppressWarnings("unchecked") - private boolean assignAbilities(CommandSender sender, Player player, Player player2, boolean self) { + private boolean assignAbilities(final CommandSender sender, final Player player, final Player player2, final boolean self) { BendingPlayer orig = BendingPlayer.getBendingPlayer(player); BendingPlayer target = BendingPlayer.getBendingPlayer(player2); if (orig == null) { - GeneralMethods.createBendingPlayer(((Player) player).getUniqueId(), player.getName()); + GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); orig = BendingPlayer.getBendingPlayer(player); } if (target == null) { - GeneralMethods.createBendingPlayer(((Player) player2).getUniqueId(), player2.getName()); + GeneralMethods.createBendingPlayer(player2.getUniqueId(), player2.getName()); target = BendingPlayer.getBendingPlayer(player2); } if (orig.isPermaRemoved()) { @@ -98,10 +97,10 @@ private boolean assignAbilities(CommandSender sender, Player player, Player play return false; } - HashMap abilities = (HashMap) orig.getAbilities().clone(); + final HashMap abilities = (HashMap) orig.getAbilities().clone(); boolean boundAll = true; for (int i = 1; i <= 9; i++) { - CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); + final CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); if (coreAbil != null && !target.canBind(coreAbil)) { abilities.remove(i); boundAll = false; @@ -112,11 +111,12 @@ private boolean assignAbilities(CommandSender sender, Player player, Player play } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (!sender.hasPermission("bending.command.copy") || args.size() >= 2 || (args.size() >= 1 && !sender.hasPermission("bending.command.copy.assign"))) - return new ArrayList(); //Return nothing - List l = new ArrayList(); - for (Player p : Bukkit.getOnlinePlayers()) { + protected List getTabCompletion(final CommandSender sender, final List args) { + if (!sender.hasPermission("bending.command.copy") || args.size() >= 2 || (args.size() >= 1 && !sender.hasPermission("bending.command.copy.assign"))) { + return new ArrayList(); // Return nothing. + } + final List l = new ArrayList(); + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } return l; diff --git a/src/com/projectkorra/projectkorra/command/DebugCommand.java b/src/com/projectkorra/projectkorra/command/DebugCommand.java index 82290058a..de96272f6 100644 --- a/src/com/projectkorra/projectkorra/command/DebugCommand.java +++ b/src/com/projectkorra/projectkorra/command/DebugCommand.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import java.util.List; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * Executor for /bending debug. Extends {@link PKCommand}. @@ -18,11 +18,11 @@ public DebugCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender)) { return; } else if (args.size() != 0) { - help(sender, false); + this.help(sender, false); return; } @@ -33,12 +33,12 @@ public void execute(CommandSender sender, List args) { /** * Checks if the CommandSender has the permission 'bending.admin.debug'. If * not, it tells them they don't have permission. - * + * * @return True if they have permission, false otherwise. */ @Override - public boolean hasPermission(CommandSender sender) { - if (!sender.hasPermission("bending.admin." + getName())) { + public boolean hasPermission(final CommandSender sender) { + if (!sender.hasPermission("bending.admin." + this.getName())) { sender.sendMessage(super.noPermissionMessage); return false; } diff --git a/src/com/projectkorra/projectkorra/command/DisplayCommand.java b/src/com/projectkorra/projectkorra/command/DisplayCommand.java index b595da002..4038ca98c 100644 --- a/src/com/projectkorra/projectkorra/command/DisplayCommand.java +++ b/src/com/projectkorra/projectkorra/command/DisplayCommand.java @@ -27,12 +27,12 @@ */ public class DisplayCommand extends PKCommand { - private String noCombosAvailable; - private String noPassivesAvailable; - private String invalidArgument; - private String playersOnly; - private String noAbilitiesAvailable; - private String noBinds; + private final String noCombosAvailable; + private final String noPassivesAvailable; + private final String invalidArgument; + private final String playersOnly; + private final String noAbilitiesAvailable; + private final String noBinds; public DisplayCommand() { super("display", "/bending display ", ConfigManager.languageConfig.get().getString("Commands.Display.Description"), new String[] { "display", "dis", "d" }); @@ -46,147 +46,148 @@ public DisplayCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 1)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 1)) { return; } - //bending display [Element] + // bending display [Element]. if (args.size() == 1) { String elementName = args.get(0).toLowerCase().replace("bending", ""); - if (elementName.equalsIgnoreCase("wc")) + if (elementName.equalsIgnoreCase("wc")) { elementName = "watercombo"; - else if (elementName.equalsIgnoreCase("ac")) + } else if (elementName.equalsIgnoreCase("ac")) { elementName = "aircombo"; - else if (elementName.equalsIgnoreCase("ec")) + } else if (elementName.equalsIgnoreCase("ec")) { elementName = "earthcombo"; - else if (elementName.equalsIgnoreCase("fc")) + } else if (elementName.equalsIgnoreCase("fc")) { elementName = "firecombo"; - else if (elementName.equalsIgnoreCase("cc")) + } else if (elementName.equalsIgnoreCase("cc")) { elementName = "chicombo"; - else if (elementName.equalsIgnoreCase("avc")) + } else if (elementName.equalsIgnoreCase("avc")) { elementName = "avatarcombo"; - else if (elementName.equalsIgnoreCase("wp")) + } else if (elementName.equalsIgnoreCase("wp")) { elementName = "waterpassive"; - else if (elementName.equalsIgnoreCase("ap")) + } else if (elementName.equalsIgnoreCase("ap")) { elementName = "airpassive"; - else if (elementName.equalsIgnoreCase("ep")) + } else if (elementName.equalsIgnoreCase("ep")) { elementName = "earthpassive"; - else if (elementName.equalsIgnoreCase("fp")) + } else if (elementName.equalsIgnoreCase("fp")) { elementName = "firepassive"; - else if (elementName.equalsIgnoreCase("cp")) + } else if (elementName.equalsIgnoreCase("cp")) { elementName = "chipassive"; - else if (elementName.equalsIgnoreCase("avp")) + } else if (elementName.equalsIgnoreCase("avp")) { elementName = "avatarpassive"; - Element element = Element.fromString(elementName.replace("combos", "").replace("combo", "").replace("passives", "").replace("passive", "")); - //combos + } + final Element element = Element.fromString(elementName.replace("combos", "").replace("combo", "").replace("passives", "").replace("passive", "")); + // combos. if (elementName.contains("combo")) { if (element == null) { sender.sendMessage(ChatColor.BOLD + "Combos"); - - for (Element e : Element.getAllElements()) { - ChatColor color = e != null ? e.getColor() : null; - ArrayList combos = ComboManager.getCombosForElement(e); - for (String comboAbil : combos) { + for (final Element e : Element.getAllElements()) { + final ChatColor color = e != null ? e.getColor() : null; + final ArrayList combos = ComboManager.getCombosForElement(e); + + for (final String comboAbil : combos) { ChatColor comboColor = color; if (!sender.hasPermission("bending.ability." + comboAbil)) { continue; } - CoreAbility coreAbil = CoreAbility.getAbility(comboAbil); + final CoreAbility coreAbil = CoreAbility.getAbility(comboAbil); if (coreAbil != null) { comboColor = coreAbil.getElement().getColor(); } String message = (comboColor + comboAbil); - + if (coreAbil instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); } } return; } else { - ChatColor color = element != null ? element.getColor() : null; - ArrayList combos = ComboManager.getCombosForElement(element); + final ChatColor color = element != null ? element.getColor() : null; + final ArrayList combos = ComboManager.getCombosForElement(element); if (combos.isEmpty()) { - GeneralMethods.sendBrandingMessage(sender, color + noCombosAvailable.replace("{element}", element.getName())); + GeneralMethods.sendBrandingMessage(sender, color + this.noCombosAvailable.replace("{element}", element.getName())); return; } - + sender.sendMessage(element.getColor() + (ChatColor.BOLD + element.getName()) + element.getType().getBending() + ChatColor.WHITE + (ChatColor.BOLD + " Combos")); - - for (String comboMove : combos) { + + for (final String comboMove : combos) { ChatColor comboColor = color; if (!sender.hasPermission("bending.ability." + comboMove)) { continue; } - CoreAbility coreAbil = CoreAbility.getAbility(comboMove); + final CoreAbility coreAbil = CoreAbility.getAbility(comboMove); if (coreAbil != null) { comboColor = coreAbil.getElement().getColor(); } - + String message = (comboColor + comboMove); - + if (coreAbil instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); } return; } - //passives + // passives. } else if (elementName.contains("passive")) { if (element == null) { sender.sendMessage(ChatColor.BOLD + "Passives"); - - for (Element e : Element.getAllElements()) { - ChatColor color = e != null ? e.getColor() : null; - Set passives = PassiveManager.getPassivesForElement(e); - for (String passiveAbil : passives) { + for (final Element e : Element.getAllElements()) { + final ChatColor color = e != null ? e.getColor() : null; + final Set passives = PassiveManager.getPassivesForElement(e); + + for (final String passiveAbil : passives) { ChatColor passiveColor = color; if (!sender.hasPermission("bending.ability." + passiveAbil)) { continue; } - CoreAbility coreAbil = CoreAbility.getAbility(passiveAbil); + final CoreAbility coreAbil = CoreAbility.getAbility(passiveAbil); if (coreAbil != null) { passiveColor = coreAbil.getElement().getColor(); } String message = (passiveColor + passiveAbil); - + if (coreAbil instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); } } return; } - ChatColor color = element != null ? element.getColor() : null; - Set passives = PassiveManager.getPassivesForElement(element); + final ChatColor color = element != null ? element.getColor() : null; + final Set passives = PassiveManager.getPassivesForElement(element); if (passives.isEmpty()) { - GeneralMethods.sendBrandingMessage(sender, color + noPassivesAvailable.replace("{element}", element.getName())); + GeneralMethods.sendBrandingMessage(sender, color + this.noPassivesAvailable.replace("{element}", element.getName())); return; } - + sender.sendMessage(element.getColor() + (ChatColor.BOLD + element.getName()) + element.getType().getBending() + ChatColor.WHITE + (ChatColor.BOLD + " Passives")); - - for (String passiveAbil : passives) { + + for (final String passiveAbil : passives) { ChatColor passiveColor = color; if (!sender.hasPermission("bending.ability." + passiveAbil)) { continue; } - CoreAbility coreAbil = CoreAbility.getAbility(passiveAbil); + final CoreAbility coreAbil = CoreAbility.getAbility(passiveAbil); if (coreAbil != null) { passiveColor = coreAbil.getElement().getColor(); } @@ -195,66 +196,66 @@ else if (elementName.equalsIgnoreCase("avp")) return; } else if (element != null) { if (!(element instanceof SubElement)) { - displayElement(sender, element); + this.displayElement(sender, element); } else { - displaySubElement(sender, (SubElement) element); + this.displaySubElement(sender, (SubElement) element); } } else { - StringBuilder elements = new StringBuilder(ChatColor.RED + invalidArgument); + final StringBuilder elements = new StringBuilder(ChatColor.RED + this.invalidArgument); elements.append(ChatColor.WHITE + "\nElements: "); - for (Element e : Element.getAllElements()) { + for (final Element e : Element.getAllElements()) { if (!(e instanceof SubElement)) { elements.append(e.getColor() + e.getName() + ChatColor.WHITE + " | "); } } sender.sendMessage(elements.toString()); - StringBuilder subelements = new StringBuilder(ChatColor.WHITE + "SubElements: "); - for (SubElement e : Element.getAllSubElements()) { + final StringBuilder subelements = new StringBuilder(ChatColor.WHITE + "SubElements: "); + for (final SubElement e : Element.getAllSubElements()) { subelements.append(ChatColor.WHITE + "\n- " + e.getColor() + e.getName()); } sender.sendMessage(subelements.toString()); } } if (args.size() == 0) { - //bending display + // bending display. if (!(sender instanceof Player)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playersOnly); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playersOnly); return; } - displayBinds(sender); + this.displayBinds(sender); } } /** * Displays the enabled moves for the given element to the CommandSender. - * + * * @param sender The CommandSender to show the moves to * @param element The element to show the moves for */ - private void displayElement(CommandSender sender, Element element) { - List abilities = CoreAbility.getAbilitiesByElement(element); + private void displayElement(final CommandSender sender, final Element element) { + final List abilities = CoreAbility.getAbilitiesByElement(element); if (abilities.isEmpty()) { - sender.sendMessage(ChatColor.YELLOW + noAbilitiesAvailable.replace("{element}", element.getColor() + element.getName() + ChatColor.YELLOW)); + sender.sendMessage(ChatColor.YELLOW + this.noAbilitiesAvailable.replace("{element}", element.getColor() + element.getName() + ChatColor.YELLOW)); return; } sender.sendMessage(element.getColor() + (ChatColor.BOLD + element.getName()) + element.getType().getBending()); - - HashSet abilitiesSent = new HashSet(); //Some abilities have the same name. This prevents this from showing anything. - for (CoreAbility ability : abilities) { + + final HashSet abilitiesSent = new HashSet(); // Some abilities have the same name. This prevents this from showing anything. + for (final CoreAbility ability : abilities) { if (ability instanceof SubAbility || ability instanceof ComboAbility || ability.isHiddenAbility() || abilitiesSent.contains(ability.getName())) { continue; } - + if (!(sender instanceof Player) || GeneralMethods.canView((Player) sender, ability.getName())) { - String message = ability.getElement().getColor()+ ability.getName(); + String message = ability.getElement().getColor() + ability.getName(); if (ability instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); abilitiesSent.add(ability.getName()); } @@ -266,7 +267,7 @@ private void displayElement(CommandSender sender, Element element) { } else { sender.sendMessage(element.getSubColor() + "Combos: " + element.getColor() + "/bending display " + element.getName() + "Combos"); sender.sendMessage(element.getSubColor() + "Passives: " + element.getColor() + "/bending display " + element.getName() + "Passives"); - for (SubElement sub : Element.getSubElements(element)) { + for (final SubElement sub : Element.getSubElements(element)) { if (sender.hasPermission("bending." + element.getName().toLowerCase() + "." + sub.getName().toLowerCase())) { sender.sendMessage(sub.getColor() + sub.getName() + " abilities: " + element.getColor() + "/bending display " + sub.getName()); } @@ -276,22 +277,22 @@ private void displayElement(CommandSender sender, Element element) { /** * Displays the enabled moves for the given subelement to the CommandSender. - * + * * @param sender The CommandSender to show the moves to * @param element The subelement to show the moves for */ - private void displaySubElement(CommandSender sender, SubElement element) { - List abilities = CoreAbility.getAbilitiesByElement(element); + private void displaySubElement(final CommandSender sender, final SubElement element) { + final List abilities = CoreAbility.getAbilitiesByElement(element); if (abilities.isEmpty() && element != null) { - sender.sendMessage(ChatColor.YELLOW + noAbilitiesAvailable.replace("{element}", element.getColor() + element.getName() + ChatColor.YELLOW)); + sender.sendMessage(ChatColor.YELLOW + this.noAbilitiesAvailable.replace("{element}", element.getColor() + element.getName() + ChatColor.YELLOW)); return; } sender.sendMessage(element.getColor() + (ChatColor.BOLD + element.getName()) + element.getType().getBending()); - - HashSet abilitiesSent = new HashSet(); - for (CoreAbility ability : abilities) { + + final HashSet abilitiesSent = new HashSet(); + for (final CoreAbility ability : abilities) { if (ability.isHiddenAbility() || abilitiesSent.contains(ability.getName())) { continue; } else if (!(sender instanceof Player) || GeneralMethods.canView((Player) sender, ability.getName())) { @@ -299,7 +300,7 @@ private void displaySubElement(CommandSender sender, SubElement element) { if (ability instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); abilitiesSent.add(ability.getName()); } @@ -309,16 +310,16 @@ private void displaySubElement(CommandSender sender, SubElement element) { /** * Displays a Player's bound abilities. - * + * * @param sender The CommandSender to output the bound abilities to */ - private void displayBinds(CommandSender sender) { + private void displayBinds(final CommandSender sender) { BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); if (bPlayer == null) { GeneralMethods.createBendingPlayer(((Player) sender).getUniqueId(), sender.getName()); bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); } - HashMap abilities = bPlayer.getAbilities(); + final HashMap abilities = bPlayer.getAbilities(); if (abilities.isEmpty()) { sender.sendMessage(ChatColor.RED + this.noBinds); @@ -326,34 +327,35 @@ private void displayBinds(CommandSender sender) { } sender.sendMessage(ChatColor.WHITE + (ChatColor.BOLD + "Abilities")); - + for (int i = 1; i <= 9; i++) { - String ability = abilities.get(i); - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final String ability = abilities.get(i); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (coreAbil != null && !ability.equalsIgnoreCase("null")) { String message = i + ". " + coreAbil.getElement().getColor() + ability; - + if (coreAbil instanceof AddonAbility) { message += ChatColor.WHITE + (ChatColor.BOLD + "*"); } - + sender.sendMessage(message); } } } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 1 || !sender.hasPermission("bending.command.display")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 1 || !sender.hasPermission("bending.command.display")) { return new ArrayList(); - List list = new ArrayList(); + } + final List list = new ArrayList(); list.add("Air"); list.add("Earth"); list.add("Fire"); list.add("Water"); list.add("Chi"); - for (Element e : Element.getAddonElements()) { + for (final Element e : Element.getAddonElements()) { list.add(e.getName()); } @@ -369,7 +371,7 @@ protected List getTabCompletion(CommandSender sender, List args) list.add("Sand"); list.add("Spiritual"); - for (SubElement se : Element.getAddonSubElements()) { + for (final SubElement se : Element.getAddonSubElements()) { list.add(se.getName()); } @@ -388,4 +390,4 @@ protected List getTabCompletion(CommandSender sender, List args) return list; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/command/HelpCommand.java b/src/com/projectkorra/projectkorra/command/HelpCommand.java index f9021ac4f..d09c9c4ba 100644 --- a/src/com/projectkorra/projectkorra/command/HelpCommand.java +++ b/src/com/projectkorra/projectkorra/command/HelpCommand.java @@ -25,17 +25,18 @@ */ public class HelpCommand extends PKCommand { - private String required; - private String optional; - private String properUsage; - private String learnMore; - private String air; - private String water; - private String earth; - private String fire; - private String chi; - private String invalidTopic; - private String usage; + private final String required; + private final String optional; + private final String properUsage; + private final String learnMore; + private final String air; + private final String water; + private final String earth; + private final String fire; + private final String chi; + private final String avatar; + private final String invalidTopic; + private final String usage; public HelpCommand() { super("help", "/bending help ", ConfigManager.languageConfig.get().getString("Commands.Help.Description"), new String[] { "help", "h" }); @@ -49,44 +50,47 @@ public HelpCommand() { this.earth = ConfigManager.languageConfig.get().getString("Commands.Help.Elements.Earth"); this.fire = ConfigManager.languageConfig.get().getString("Commands.Help.Elements.Fire"); this.chi = ConfigManager.languageConfig.get().getString("Commands.Help.Elements.Chi"); + this.avatar = ConfigManager.languageConfig.get().getString("Commands.Help.Elements.Avatar"); this.invalidTopic = ConfigManager.languageConfig.get().getString("Commands.Help.InvalidTopic"); this.usage = ConfigManager.languageConfig.get().getString("Commands.Help.Usage"); } @Override - public void execute(CommandSender sender, List args) { + public void execute(final CommandSender sender, final List args) { boolean firstMessage = true; - - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 1)) + + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 1)) { return; - else if (args.size() == 0) { - List strings = new ArrayList(); - for (PKCommand command : instances.values()) { + } else if (args.size() == 0) { + final List strings = new ArrayList(); + for (final PKCommand command : instances.values()) { if (!command.getName().equalsIgnoreCase("help") && sender.hasPermission("bending.command." + command.getName())) { strings.add(command.getProperUse()); } } if (GeneralMethods.hasItems()) { - for (PKICommand command : PKICommand.instances.values()) { - if (sender.hasPermission("bendingitems.command." + command.getName())) + for (final PKICommand command : PKICommand.instances.values()) { + if (sender.hasPermission("bendingitems.command." + command.getName())) { strings.add(command.getProperUse()); + } } } if (GeneralMethods.hasRPG()) { - for (RPGCommand command : RPGCommand.instances.values()) { - if (sender.hasPermission("bending.command.rpg." + command.getName())) + for (final RPGCommand command : RPGCommand.instances.values()) { + if (sender.hasPermission("bending.command.rpg." + command.getName())) { strings.add(command.getProperUse()); + } } } if (GeneralMethods.hasSpirits()) { - //spirits commands being added (if needed) + // spirits commands being added (if needed). } Collections.sort(strings); Collections.reverse(strings); strings.add(instances.get("help").getProperUse()); Collections.reverse(strings); - - for (String s : getPage(strings, ChatColor.GOLD + "Commands: <" + required + "> [" + optional + "]", 1, false)) { + + for (final String s : this.getPage(strings, ChatColor.GOLD + "Commands: <" + this.required + "> [" + this.optional + "]", 1, false)) { if (firstMessage) { GeneralMethods.sendBrandingMessage(sender, s); firstMessage = false; @@ -97,29 +101,31 @@ else if (args.size() == 0) { return; } - String arg = args.get(0).toLowerCase(); - - if (isNumeric(arg)) { - List strings = new ArrayList(); - for (PKCommand command : instances.values()) { + final String arg = args.get(0).toLowerCase(); + + if (this.isNumeric(arg)) { + final List strings = new ArrayList(); + for (final PKCommand command : instances.values()) { strings.add(command.getProperUse()); } if (GeneralMethods.hasItems()) { - for (PKICommand command : PKICommand.instances.values()) { - if (sender.hasPermission("bendingitems.command." + command.getName())) + for (final PKICommand command : PKICommand.instances.values()) { + if (sender.hasPermission("bendingitems.command." + command.getName())) { strings.add(command.getProperUse()); + } } } if (GeneralMethods.hasRPG()) { - for (RPGCommand command : RPGCommand.instances.values()) { - if (sender.hasPermission("bending.command.rpg." + command.getName())) + for (final RPGCommand command : RPGCommand.instances.values()) { + if (sender.hasPermission("bending.command.rpg." + command.getName())) { strings.add(command.getProperUse()); + } } } if (GeneralMethods.hasSpirits()) { - //spirits commands being added (if needed) + // spirits commands being added (if needed). } - for (String s : getPage(strings, ChatColor.GOLD + "Commands: <" + required + "> [" + optional + "]", Integer.valueOf(arg), true)) { + for (final String s : this.getPage(strings, ChatColor.GOLD + "Commands: <" + this.required + "> [" + this.optional + "]", Integer.valueOf(arg), true)) { if (firstMessage) { GeneralMethods.sendBrandingMessage(sender, s); firstMessage = false; @@ -127,30 +133,30 @@ else if (args.size() == 0) { sender.sendMessage(ChatColor.YELLOW + s); } } - } else if (instances.keySet().contains(arg)) {//bending help command + } else if (instances.keySet().contains(arg)) {// bending help command. instances.get(arg).help(sender, true); - } else if (Arrays.asList(Commands.comboaliases).contains(arg)) { //bending help elementcombo - sender.sendMessage(ChatColor.GOLD + properUsage.replace("{command1}", ChatColor.RED + "/bending display " + arg + ChatColor.GOLD).replace("{command2}", ChatColor.RED + "/bending help " + ChatColor.GOLD)); - } else if (Arrays.asList(Commands.passivealiases).contains(arg)) { //bending help elementpassive - sender.sendMessage(ChatColor.GOLD + properUsage.replace("{command1}", ChatColor.RED + "/bending display " + arg + ChatColor.GOLD).replace("{command2}", ChatColor.RED + "/bending help " + ChatColor.RED)); - } else if (CoreAbility.getAbility(arg) != null && !(CoreAbility.getAbility(arg) instanceof ComboAbility) && CoreAbility.getAbility(arg).isEnabled() && !CoreAbility.getAbility(arg).isHiddenAbility() || CoreAbility.getAbility(arg) instanceof PassiveAbility) { //bending help ability - CoreAbility ability = CoreAbility.getAbility(arg); - ChatColor color = ability.getElement().getColor(); - + } else if (Arrays.asList(Commands.comboaliases).contains(arg)) { // bending help elementcombo. + sender.sendMessage(ChatColor.GOLD + this.properUsage.replace("{command1}", ChatColor.RED + "/bending display " + arg + ChatColor.GOLD).replace("{command2}", ChatColor.RED + "/bending help " + ChatColor.GOLD)); + } else if (Arrays.asList(Commands.passivealiases).contains(arg)) { // bending help elementpassive. + sender.sendMessage(ChatColor.GOLD + this.properUsage.replace("{command1}", ChatColor.RED + "/bending display " + arg + ChatColor.GOLD).replace("{command2}", ChatColor.RED + "/bending help " + ChatColor.RED)); + } else if (CoreAbility.getAbility(arg) != null && !(CoreAbility.getAbility(arg) instanceof ComboAbility) && CoreAbility.getAbility(arg).isEnabled() && !CoreAbility.getAbility(arg).isHiddenAbility() || CoreAbility.getAbility(arg) instanceof PassiveAbility) { // bending help ability. + final CoreAbility ability = CoreAbility.getAbility(arg); + final ChatColor color = ability.getElement().getColor(); + if (ability instanceof AddonAbility) { if (ability instanceof PassiveAbility) { sender.sendMessage(color + (ChatColor.BOLD + ability.getName()) + ChatColor.WHITE + " (Addon Passive)"); } else { sender.sendMessage(color + (ChatColor.BOLD + ability.getName()) + ChatColor.WHITE + " (Addon)"); } - + sender.sendMessage(color + ability.getDescription()); - + if (!ability.getInstructions().isEmpty()) { - sender.sendMessage(ChatColor.GOLD + usage + ability.getInstructions()); + sender.sendMessage(ChatColor.WHITE + this.usage + ability.getInstructions()); } - - AddonAbility abil = (AddonAbility) CoreAbility.getAbility(arg); + + final AddonAbility abil = (AddonAbility) CoreAbility.getAbility(arg); sender.sendMessage(color + "- By: " + ChatColor.WHITE + abil.getAuthor()); sender.sendMessage(color + "- Version: " + ChatColor.WHITE + abil.getVersion()); } else { @@ -159,73 +165,76 @@ else if (args.size() == 0) { } else { sender.sendMessage(color + (ChatColor.BOLD + ability.getName())); } - + sender.sendMessage(color + ability.getDescription()); - + if (!ability.getInstructions().isEmpty()) { - sender.sendMessage(ChatColor.GOLD + usage + ability.getInstructions()); + sender.sendMessage(ChatColor.WHITE + this.usage + ability.getInstructions()); } } } else if (Arrays.asList(Commands.airaliases).contains(arg)) { - sender.sendMessage(Element.AIR.getColor() + air.replace("/b help AirCombos", Element.AIR.getSubColor() + "/b help AirCombos" + Element.AIR.getColor())); - sender.sendMessage(ChatColor.YELLOW + learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + sender.sendMessage(Element.AIR.getColor() + this.air.replace("/b display Air", Element.AIR.getSubColor() + "/b display Air" + Element.AIR.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); } else if (Arrays.asList(Commands.wateraliases).contains(arg)) { - sender.sendMessage(Element.WATER.getColor() + water.replace("/b help WaterCombos", Element.WATER.getSubColor() + "/b h WaterCombos" + Element.WATER.getColor())); - sender.sendMessage(ChatColor.YELLOW + learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + sender.sendMessage(Element.WATER.getColor() + this.water.replace("/b display Water", Element.WATER.getSubColor() + "/b display Water" + Element.WATER.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); } else if (Arrays.asList(Commands.earthaliases).contains(arg)) { - sender.sendMessage(Element.EARTH.getColor() + earth); - sender.sendMessage(ChatColor.YELLOW + learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + sender.sendMessage(Element.EARTH.getColor() + this.earth.replace("/b display Earth", Element.EARTH.getSubColor() + "/b display Earth" + Element.EARTH.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); } else if (Arrays.asList(Commands.firealiases).contains(arg)) { - sender.sendMessage(Element.FIRE.getColor() + fire.replace("/b h FireCombos", Element.FIRE.getSubColor() + "/b h FireCombos" + Element.FIRE.getColor())); - sender.sendMessage(ChatColor.YELLOW + learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + sender.sendMessage(Element.FIRE.getColor() + this.fire.replace("/b display Fire", Element.FIRE.getSubColor() + "/b display Fire" + Element.FIRE.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); } else if (Arrays.asList(Commands.chialiases).contains(arg)) { - sender.sendMessage(Element.CHI.getColor() + chi.replace("/b h ChiCombos", Element.CHI.getSubColor() + "/b h ChiCombos" + Element.CHI.getColor())); - sender.sendMessage(ChatColor.YELLOW + learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + sender.sendMessage(Element.CHI.getColor() + this.chi.replace("/b display Chi", Element.CHI.getSubColor() + "/b display Chi" + Element.CHI.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); + } else if (Arrays.asList(Commands.avataraliases).contains(arg)) { + sender.sendMessage(Element.AVATAR.getColor() + this.avatar.replace("/b display Avatar", Element.AVATAR.getSubColor() + "/b display Avatar" + Element.AVATAR.getColor())); + sender.sendMessage(ChatColor.YELLOW + this.learnMore + ChatColor.DARK_AQUA + "http://projectkorra.com/"); } else { - //combos - handled differently because they're stored in CamelCase in ComboManager - for (String combo : ComboManager.getDescriptions().keySet()) { - if (combo.equalsIgnoreCase(arg)) { - CoreAbility ability = CoreAbility.getAbility(combo); - ChatColor color = ability != null ? ability.getElement().getColor() : null; - + // combos - handled differently because they're stored in CamelCase in ComboManager. + for (final String combo : ComboManager.getDescriptions().keySet()) { + if (combo.equalsIgnoreCase(arg)) { + final CoreAbility ability = CoreAbility.getAbility(combo); + final ChatColor color = ability != null ? ability.getElement().getColor() : null; + if (ability instanceof AddonAbility) { sender.sendMessage(color + (ChatColor.BOLD + ability.getName()) + ChatColor.WHITE + " (Addon Combo)"); sender.sendMessage(color + ability.getDescription()); - + if (!ability.getInstructions().isEmpty()) { - sender.sendMessage(ChatColor.GOLD + usage + ability.getInstructions()); + sender.sendMessage(ChatColor.WHITE + this.usage + ability.getInstructions()); } - - AddonAbility abil = (AddonAbility) CoreAbility.getAbility(arg); + + final AddonAbility abil = (AddonAbility) CoreAbility.getAbility(arg); sender.sendMessage(color + "- By: " + ChatColor.WHITE + abil.getAuthor()); sender.sendMessage(color + "- Version: " + ChatColor.WHITE + abil.getVersion()); } else { sender.sendMessage(color + (ChatColor.BOLD + ability.getName()) + ChatColor.WHITE + " (Combo)"); sender.sendMessage(color + ComboManager.getDescriptions().get(combo)); - sender.sendMessage(ChatColor.GOLD + usage + ComboManager.getInstructions().get(combo)); + sender.sendMessage(ChatColor.WHITE + this.usage + ComboManager.getInstructions().get(combo)); } return; } } - - sender.sendMessage(ChatColor.RED + invalidTopic); + + sender.sendMessage(ChatColor.RED + this.invalidTopic); } } @Override - protected List getTabCompletion(CommandSender sender, List args) { + protected List getTabCompletion(final CommandSender sender, final List args) { if (args.size() >= 1 || !sender.hasPermission("bending.command.help")) { return new ArrayList(); } - - List list = new ArrayList(); - for (Element e : Element.getAllElements()) { + + final List list = new ArrayList(); + for (final Element e : Element.getAllElements()) { list.add(e.getName()); } - - List abils = new ArrayList(); - for (CoreAbility coreAbil : CoreAbility.getAbilities()) { + + final List abils = new ArrayList(); + for (final CoreAbility coreAbil : CoreAbility.getAbilities()) { if (!(sender instanceof Player) && (!coreAbil.isHiddenAbility()) && coreAbil.isEnabled() && !abils.contains(coreAbil.getName())) { abils.add(coreAbil.getName()); } else if (sender instanceof Player) { diff --git a/src/com/projectkorra/projectkorra/command/ImportCommand.java b/src/com/projectkorra/projectkorra/command/ImportCommand.java deleted file mode 100644 index dc389aa9f..000000000 --- a/src/com/projectkorra/projectkorra/command/ImportCommand.java +++ /dev/null @@ -1,163 +0,0 @@ -package com.projectkorra.projectkorra.command; - -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.Element; -import com.projectkorra.projectkorra.Element.SubElement; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.configuration.ConfigManager; -import com.projectkorra.projectkorra.storage.DBConnection; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitTask; - -import java.io.File; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -/** - * Executor for /bending import. Extends {@link PKCommand}. - */ -public class ImportCommand extends PKCommand { - - boolean debugEnabled = ProjectKorra.plugin.getConfig().getBoolean("debug"); - BukkitTask importTask; - private String disabled; - private String preparingData; - private String importStarted; - private String debugWarning; - private String queuedUp; - - public ImportCommand() { - super("import", "/bending import", ConfigManager.languageConfig.get().getString("Commands.Import.Description"), new String[] { "import", "i" }); - - this.disabled = ConfigManager.languageConfig.get().getString("Commands.Import.Description"); - this.preparingData = ConfigManager.languageConfig.get().getString("Commands.Import.PreparingData"); - this.importStarted = ConfigManager.languageConfig.get().getString("Commands.Import.ImportStarted"); - this.debugWarning = ConfigManager.languageConfig.get().getString("Commands.Import.DebugWarning"); - this.queuedUp = ConfigManager.languageConfig.get().getString("Commands.Import.DataQueuedUp"); - } - - @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 0)) { - return; - } else if (!GeneralMethods.isImportEnabled()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.disabled); - return; - } - - sender.sendMessage(ChatColor.GREEN + this.preparingData); - File bendingPlayersFile = new File(".", "converted.yml"); - FileConfiguration bendingPlayers = YamlConfiguration.loadConfiguration(bendingPlayersFile); - - final LinkedList bPlayers = new LinkedList(); - for (String string : bendingPlayers.getConfigurationSection("").getKeys(false)) { - if (string.equalsIgnoreCase("version")) - continue; - String playername = string; - @SuppressWarnings("deprecation") - UUID uuid = ProjectKorra.plugin.getServer().getOfflinePlayer(playername).getUniqueId(); - ArrayList elements = new ArrayList(); - ArrayList subs = new ArrayList(); - List bendingTypes = bendingPlayers.getIntegerList(string + ".BendingTypes"); - boolean permaremoved = bendingPlayers.getBoolean(string + ".Permaremoved"); - Element[] mainElements = Element.getMainElements(); - Element[] allElements = Element.getAllElements(); - - for (int i : bendingTypes) { - if (i < mainElements.length) { - elements.add(mainElements[i]); - } - } - - for (Element e : allElements) { - if (e instanceof SubElement) { - SubElement s = (SubElement) e; - subs.add(s); - } - } - - BendingPlayer bPlayer = new BendingPlayer(uuid, playername, elements, subs, new HashMap(), permaremoved); - bPlayers.add(bPlayer); - } - - final CommandSender s = sender; - final int total = bPlayers.size(); - sender.sendMessage(ChatColor.GREEN + this.importStarted); - if (debugEnabled) { - sender.sendMessage(ChatColor.RED + this.debugWarning); - } - importTask = Bukkit.getServer().getScheduler().runTaskTimerAsynchronously(ProjectKorra.plugin, new Runnable() { - public void run() { - int i = 0; - if (i >= 10) { - s.sendMessage(ChatColor.GREEN + "10 / " + total + "!"); - return; - } - - while (i < 10) { - if (bPlayers.isEmpty()) { - s.sendMessage(ChatColor.GREEN + queuedUp); - Bukkit.getServer().getScheduler().cancelTask(importTask.getTaskId()); - ProjectKorra.plugin.getConfig().set("Properties.ImportEnabled", false); - ProjectKorra.plugin.saveConfig(); - for (Player player : Bukkit.getOnlinePlayers()) { - GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); - } - return; - } - StringBuilder elements = new StringBuilder(); - BendingPlayer bPlayer = bPlayers.pop(); - if (bPlayer.hasElement(Element.AIR)) - elements.append("a"); - if (bPlayer.hasElement(Element.WATER)) - elements.append("w"); - if (bPlayer.hasElement(Element.EARTH)) - elements.append("e"); - if (bPlayer.hasElement(Element.FIRE)) - elements.append("f"); - if (bPlayer.hasElement(Element.CHI)) - elements.append("c"); - - HashMap abilities = bPlayer.getAbilities(); - - ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM pk_players WHERE uuid = '" + bPlayer.getUUIDString() + "'"); - - try { - if (rs2.next()) { // SQL Data already exists for player. - DBConnection.sql.modifyQuery("UPDATE pk_players SET player = '" + bPlayer.getName() + "' WHERE uuid = '" + bPlayer.getUUIDString()); - DBConnection.sql.modifyQuery("UPDATE pk_players SET element = '" + elements + "' WHERE uuid = '" + bPlayer.getUUIDString()); - DBConnection.sql.modifyQuery("UPDATE pk_players SET permaremoved = '" + bPlayer.isPermaRemoved() + "' WHERE uuid = '" + bPlayer.getUUIDString()); - for (int slot = 1; slot < 10; slot++) { - DBConnection.sql.modifyQuery("UPDATE pk_players SET slot" + slot + " = '" + abilities.get(slot) + "' WHERE player = '" + bPlayer.getName() + "'"); - } - } else { - DBConnection.sql.modifyQuery("INSERT INTO pk_players (uuid, player, element, permaremoved) VALUES ('" + bPlayer.getUUIDString() + "', '" + bPlayer.getName() + "', '" + elements + "', '" + bPlayer.isPermaRemoved() + "')"); - for (int slot = 1; slot < 10; slot++) { - DBConnection.sql.modifyQuery("UPDATE pk_players SET slot" + slot + " = '" + abilities.get(slot) + "' WHERE player = '" + bPlayer.getName() + "'"); - } - } - } - catch (SQLException ex) { - ex.printStackTrace(); - } - i++; - if (debugEnabled) { - System.out.println("[ProjectKorra] Successfully imported " + bPlayer.getName() + ". " + bPlayers.size() + " players left to import."); // not configurable because it's internal - } - } - } - }, 0, 40); - } -} diff --git a/src/com/projectkorra/projectkorra/command/InvincibleCommand.java b/src/com/projectkorra/projectkorra/command/InvincibleCommand.java index 56c91df0a..104b654a9 100644 --- a/src/com/projectkorra/projectkorra/command/InvincibleCommand.java +++ b/src/com/projectkorra/projectkorra/command/InvincibleCommand.java @@ -1,26 +1,26 @@ package com.projectkorra.projectkorra.command; +import java.util.List; + import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.configuration.ConfigManager; -import java.util.List; - /** * Executor for /bending invincible. Extends {@link PKCommand}. */ public class InvincibleCommand extends PKCommand { public InvincibleCommand() { - super("invincible", "/bending invincible", ConfigManager.languageConfig.get().getString("Commands.Invincible.Description"), new String[] { "invincible", "inv" }); + super("invincible", "/bending invincible", ConfigManager.languageConfig.get().getString("Commands.Invincible.Description"), new String[] { "invincible", "inv", "i" }); } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !isPlayer(sender) || !correctLength(sender, args.size(), 0, 0)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.isPlayer(sender) || !this.correctLength(sender, args.size(), 0, 0)) { return; } diff --git a/src/com/projectkorra/projectkorra/command/PKCommand.java b/src/com/projectkorra/projectkorra/command/PKCommand.java index ec856449d..f07a11f3a 100644 --- a/src/com/projectkorra/projectkorra/command/PKCommand.java +++ b/src/com/projectkorra/projectkorra/command/PKCommand.java @@ -18,7 +18,7 @@ /** * Abstract representation of a command executor. Implements {@link SubCommand}. - * + * * @author kingbirdy * */ @@ -48,7 +48,7 @@ public abstract class PKCommand implements SubCommand { */ public static Map instances = new HashMap(); - public PKCommand(String name, String properUse, String description, String[] aliases) { + public PKCommand(final String name, final String properUse, final String description, final String[] aliases) { this.name = name; this.properUse = properUse; this.description = description; @@ -60,24 +60,29 @@ public PKCommand(String name, String properUse, String description, String[] ali instances.put(name, this); } + @Override public String getName() { - return name; + return this.name; } + @Override public String getProperUse() { - return properUse; + return this.properUse; } + @Override public String getDescription() { - return description; + return this.description; } + @Override public String[] getAliases() { - return aliases; + return this.aliases; } - public void help(CommandSender sender, boolean description) { - sender.sendMessage(ChatColor.GOLD + "Proper Usage: " + ChatColor.DARK_AQUA + properUse); + @Override + public void help(final CommandSender sender, final boolean description) { + sender.sendMessage(ChatColor.GOLD + "Proper Usage: " + ChatColor.DARK_AQUA + this.properUse); if (description) { sender.sendMessage(ChatColor.YELLOW + this.description); } @@ -87,12 +92,12 @@ public void help(CommandSender sender, boolean description) { * Checks if the {@link CommandSender} has permission to execute the * command. The permission is in the format 'bending.command. * {@link PKCommand#name name}'. If not, they are told so. - * + * * @param sender The CommandSender to check * @return True if they have permission, false otherwise */ - protected boolean hasPermission(CommandSender sender) { - if (sender.hasPermission("bending.command." + name)) { + protected boolean hasPermission(final CommandSender sender) { + if (sender.hasPermission("bending.command." + this.name)) { return true; } else { sender.sendMessage(this.noPermissionMessage); @@ -104,13 +109,13 @@ protected boolean hasPermission(CommandSender sender) { * Checks if the {@link CommandSender} has permission to execute the * command. The permission is in the format 'bending.command. * {@link PKCommand#name name}.extra'. If not, they are told so. - * + * * @param sender The CommandSender to check * @param extra The additional node to check * @return True if they have permission, false otherwise */ - protected boolean hasPermission(CommandSender sender, String extra) { - if (sender.hasPermission("bending.command." + name + "." + extra)) { + protected boolean hasPermission(final CommandSender sender, final String extra) { + if (sender.hasPermission("bending.command." + this.name + "." + extra)) { return true; } else { GeneralMethods.sendBrandingMessage(sender, this.noPermissionMessage); @@ -121,16 +126,16 @@ protected boolean hasPermission(CommandSender sender, String extra) { /** * Checks if the argument length is within certain parameters, and if not, * informs the CommandSender of how to correctly use the command. - * + * * @param sender The CommandSender who issued the command * @param size The length of the arguments list * @param min The minimum acceptable number of arguments * @param max The maximum acceptable number of arguments * @return True if min < size < max, false otherwise */ - protected boolean correctLength(CommandSender sender, int size, int min, int max) { + protected boolean correctLength(final CommandSender sender, final int size, final int min, final int max) { if (size < min || size > max) { - help(sender, false); + this.help(sender, false); return false; } else { return true; @@ -140,11 +145,11 @@ protected boolean correctLength(CommandSender sender, int size, int min, int max /** * Checks if the CommandSender is an instance of a Player. If not, it tells * them they must be a Player to use the command. - * + * * @param sender The CommandSender to check * @return True if sender instanceof Player, false otherwise */ - protected boolean isPlayer(CommandSender sender) { + protected boolean isPlayer(final CommandSender sender) { if (sender instanceof Player) { return true; } else { @@ -157,70 +162,71 @@ protected boolean isPlayer(CommandSender sender) { * Returns a string representation of one of the five base elements, * converted from any possible alias of that element, its combos, or its * subelements. - * + * * @param element The string to try and determine an element for * @return The element associated with the input string, if found, or null * otherwise */ - public String getElement(String element) { - if (Arrays.asList(Commands.firealiases).contains(element) || Arrays.asList(Commands.firecomboaliases).contains(element)) + public String getElement(final String element) { + if (Arrays.asList(Commands.firealiases).contains(element) || Arrays.asList(Commands.firecomboaliases).contains(element)) { return "fire"; - else if (Arrays.asList(Commands.combustionaliases).contains(element)) + } else if (Arrays.asList(Commands.combustionaliases).contains(element)) { return "combustion"; - else if (Arrays.asList(Commands.lightningaliases).contains(element)) + } else if (Arrays.asList(Commands.lightningaliases).contains(element)) { return "lightning"; - else if (Arrays.asList(Commands.earthaliases).contains(element) || Arrays.asList(Commands.earthcomboaliases).contains(element)) + } else if (Arrays.asList(Commands.earthaliases).contains(element) || Arrays.asList(Commands.earthcomboaliases).contains(element)) { return "earth"; - else if (Arrays.asList(Commands.metalbendingaliases).contains(element)) + } else if (Arrays.asList(Commands.metalbendingaliases).contains(element)) { return "metal"; - else if (Arrays.asList(Commands.sandbendingaliases).contains(element)) + } else if (Arrays.asList(Commands.sandbendingaliases).contains(element)) { return "sand"; - else if (Arrays.asList(Commands.lavabendingaliases).contains(element)) + } else if (Arrays.asList(Commands.lavabendingaliases).contains(element)) { return "lava"; - else if (Arrays.asList(Commands.airaliases).contains(element) || Arrays.asList(Commands.aircomboaliases).contains(element)) + } else if (Arrays.asList(Commands.airaliases).contains(element) || Arrays.asList(Commands.aircomboaliases).contains(element)) { return "air"; - else if (Arrays.asList(Commands.spiritualprojectionaliases).contains(element)) + } else if (Arrays.asList(Commands.spiritualprojectionaliases).contains(element)) { return "spiritual"; - else if (Arrays.asList(Commands.flightaliases).contains(element)) + } else if (Arrays.asList(Commands.flightaliases).contains(element)) { return "flight"; - else if (Arrays.asList(Commands.wateraliases).contains(element) || Arrays.asList(Commands.watercomboaliases).contains(element)) + } else if (Arrays.asList(Commands.wateraliases).contains(element) || Arrays.asList(Commands.watercomboaliases).contains(element)) { return "water"; - else if (Arrays.asList(Commands.healingaliases).contains(element)) + } else if (Arrays.asList(Commands.healingaliases).contains(element)) { return "healing"; - else if (Arrays.asList(Commands.bloodaliases).contains(element)) + } else if (Arrays.asList(Commands.bloodaliases).contains(element)) { return "blood"; - else if (Arrays.asList(Commands.icealiases).contains(element)) + } else if (Arrays.asList(Commands.icealiases).contains(element)) { return "ice"; - else if (Arrays.asList(Commands.plantaliases).contains(element)) + } else if (Arrays.asList(Commands.plantaliases).contains(element)) { return "plant"; - else if (Arrays.asList(Commands.chialiases).contains(element) || Arrays.asList(Commands.chicomboaliases).contains(element)) + } else if (Arrays.asList(Commands.chialiases).contains(element) || Arrays.asList(Commands.chicomboaliases).contains(element)) { return "chi"; + } return null; } /** * Returns a boolean if the string provided is numerical. - * + * * @param id * @return boolean */ - protected boolean isNumeric(String id) { - NumberFormat formatter = NumberFormat.getInstance(); - ParsePosition pos = new ParsePosition(0); + protected boolean isNumeric(final String id) { + final NumberFormat formatter = NumberFormat.getInstance(); + final ParsePosition pos = new ParsePosition(0); formatter.parse(id, pos); return id.length() == pos.getIndex(); } /** * Returns a list for of commands for a page. - * + * * @param entries * @param title * @param page * @return */ - protected List getPage(List entries, String title, int page, boolean sort) { - List strings = new ArrayList(); + protected List getPage(final List entries, final String title, int page, final boolean sort) { + final List strings = new ArrayList(); if (sort) { Collections.sort(entries); } @@ -250,7 +256,7 @@ protected List getPage(List entries, String title, int page, boo } /** Gets a list of valid arguments that can be used in tabbing. */ - protected List getTabCompletion(CommandSender sender, List args) { + protected List getTabCompletion(final CommandSender sender, final List args) { return new ArrayList(); } diff --git a/src/com/projectkorra/projectkorra/command/PermaremoveCommand.java b/src/com/projectkorra/projectkorra/command/PermaremoveCommand.java index 4ddc77921..aadd9d923 100644 --- a/src/com/projectkorra/projectkorra/command/PermaremoveCommand.java +++ b/src/com/projectkorra/projectkorra/command/PermaremoveCommand.java @@ -1,29 +1,29 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.configuration.ConfigManager; -import com.projectkorra.projectkorra.event.PlayerChangeElementEvent; -import com.projectkorra.projectkorra.event.PlayerChangeElementEvent.Result; +import java.util.ArrayList; +import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.configuration.ConfigManager; +import com.projectkorra.projectkorra.event.PlayerChangeElementEvent; +import com.projectkorra.projectkorra.event.PlayerChangeElementEvent.Result; /** * Executor for /bending permaremove. Extends {@link PKCommand}. */ public class PermaremoveCommand extends PKCommand { - private String playerIsOffline; - private String restored; - private String restoredConfirm; - private String removed; - private String removedConfirm; + private final String playerIsOffline; + private final String restored; + private final String restoredConfirm; + private final String removed; + private final String removedConfirm; public PermaremoveCommand() { super("permaremove", "/bending permaremove ", ConfigManager.languageConfig.get().getString("Commands.PermaRemove.Description"), new String[] { "permaremove", "premove", "permremove", "pr" }); @@ -36,25 +36,26 @@ public PermaremoveCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 1)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 1)) { return; } if (args.size() == 1) { - permaremove(sender, args.get(0)); - } else if (args.size() == 0 && isPlayer(sender)) - permaremove(sender, sender.getName()); + this.permaremove(sender, args.get(0)); + } else if (args.size() == 0 && this.isPlayer(sender)) { + this.permaremove(sender, sender.getName()); + } } /** * Permanently removes a player's bending, or restores it if it had already * been permaremoved. - * + * * @param sender The CommandSender who issued the permaremove command * @param target The Player who's bending should be permaremoved */ - private void permaremove(CommandSender sender, String target) { - Player player = Bukkit.getPlayer(target); + private void permaremove(final CommandSender sender, final String target) { + final Player player = Bukkit.getPlayer(target); if (player == null) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerIsOffline); return; @@ -70,8 +71,9 @@ private void permaremove(CommandSender sender, String target) { bPlayer.setPermaRemoved(false); GeneralMethods.savePermaRemoved(bPlayer); GeneralMethods.sendBrandingMessage(player, ChatColor.GREEN + this.restored); - if (!(sender instanceof Player) || !sender.getName().equalsIgnoreCase(target)) + if (!(sender instanceof Player) || !sender.getName().equalsIgnoreCase(target)) { GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.restoredConfirm.replace("{target}", ChatColor.DARK_AQUA + player.getName() + ChatColor.GREEN)); + } } else { bPlayer.getElements().clear(); GeneralMethods.saveElements(bPlayer); @@ -79,8 +81,9 @@ private void permaremove(CommandSender sender, String target) { GeneralMethods.savePermaRemoved(bPlayer); GeneralMethods.removeUnusableAbilities(player.getName()); GeneralMethods.sendBrandingMessage(player, ChatColor.RED + this.removed); - if (!(sender instanceof Player) || !sender.getName().equalsIgnoreCase(target)) + if (!(sender instanceof Player) || !sender.getName().equalsIgnoreCase(target)) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.removedConfirm.replace("{target}", ChatColor.DARK_AQUA + player.getName() + ChatColor.RED)); + } Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeElementEvent(sender, player, null, Result.PERMAREMOVE)); } } @@ -88,11 +91,11 @@ private void permaremove(CommandSender sender, String target) { /** * Checks if the sender has the permission 'bending.admin.permaremove'. If * not, it tells them they don't have permission to use the command. - * + * * @return True if they have the permission, false otherwise */ @Override - public boolean hasPermission(CommandSender sender) { + public boolean hasPermission(final CommandSender sender) { if (!sender.hasPermission("bending.admin.permaremove")) { GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); return false; @@ -101,11 +104,12 @@ public boolean hasPermission(CommandSender sender) { } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 1 || !sender.hasPermission("bending.command.permaremove")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 1 || !sender.hasPermission("bending.command.permaremove")) { return new ArrayList(); - List players = new ArrayList(); - for (Player p : Bukkit.getOnlinePlayers()) { + } + final List players = new ArrayList(); + for (final Player p : Bukkit.getOnlinePlayers()) { players.add(p.getName()); } return players; diff --git a/src/com/projectkorra/projectkorra/command/PresetCommand.java b/src/com/projectkorra/projectkorra/command/PresetCommand.java index d8dad3ed4..efa04582c 100644 --- a/src/com/projectkorra/projectkorra/command/PresetCommand.java +++ b/src/com/projectkorra/projectkorra/command/PresetCommand.java @@ -26,20 +26,20 @@ public class PresetCommand extends PKCommand { private static final String[] listaliases = { "list", "l" }; private static final String[] bindaliases = { "bind", "b" }; - private String noPresets; - private String noPresetName; - private String deletePreset; - private String noPresetNameExternal; - private String bendingRemoved; - private String bound; - private String failedToBindAll; - private String bendingRemovedOther; - private String boundOtherConfirm; - private String succesfullyCopied; - private String reachedMax; - private String alreadyExists; - private String createdNewPreset; - private String cantEditBinds; + private final String noPresets; + private final String noPresetName; + private final String deletePreset; + private final String noPresetNameExternal; + private final String bendingRemoved; + private final String bound; + private final String failedToBindAll; + private final String bendingRemovedOther; + private final String boundOtherConfirm; + private final String succesfullyCopied; + private final String reachedMax; + private final String alreadyExists; + private final String createdNewPreset; + private final String cantEditBinds; public PresetCommand() { super("preset", "/bending preset [Preset]", ConfigManager.languageConfig.get().getString("Commands.Preset.Description"), new String[] { "preset", "presets", "pre", "set", "p" }); @@ -60,67 +60,82 @@ public PresetCommand() { this.cantEditBinds = ConfigManager.languageConfig.get().getString("Commands.Preset.CantEditBinds"); } - @SuppressWarnings("unchecked") @Override - public void execute(CommandSender sender, List args) { - if (!isPlayer(sender) || !correctLength(sender, args.size(), 1, 3)) { + public void execute(final CommandSender sender, final List args) { + if (!this.isPlayer(sender) || !this.correctLength(sender, args.size(), 1, 3)) { return; } else if (MultiAbilityManager.hasMultiAbilityBound((Player) sender)) { GeneralMethods.sendBrandingMessage(sender, this.cantEditBinds); return; } - Player player = (Player) sender; + final Player player = (Player) sender; BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { - GeneralMethods.createBendingPlayer(((Player) player).getUniqueId(), player.getName()); + GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); bPlayer = BendingPlayer.getBendingPlayer(player); } - //bending preset list + // bending preset list. if (args.size() == 1) { - if (Arrays.asList(listaliases).contains(args.get(0)) && hasPermission(sender, "list")) { - List presets = Preset.presets.get(player.getUniqueId()); - List presetNames = new ArrayList(); + if (Arrays.asList(listaliases).contains(args.get(0)) && this.hasPermission(sender, "list")) { + boolean firstMessage = true; + + final List presets = Preset.presets.get(player.getUniqueId()); + final List presetNames = new ArrayList(); if (presets == null || presets.isEmpty()) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPresets); return; } - for (Preset preset : presets) { + for (final Preset preset : presets) { presetNames.add(preset.getName()); } - sender.sendMessage(ChatColor.GREEN + "Presets: " + ChatColor.DARK_AQUA + presetNames.toString()); + for (final String s : this.getPage(presetNames, ChatColor.GOLD + "Presets: ", 1, false)) { + if (firstMessage) { + GeneralMethods.sendBrandingMessage(sender, s); + firstMessage = false; + } else { + sender.sendMessage(ChatColor.YELLOW + s); + } + } + return; } else { - help(sender, false); + this.help(sender, false); return; } } - String name = args.get(1); - if (Arrays.asList(deletealiases).contains(args.get(0)) && hasPermission(sender, "delete")) { //bending preset delete name + final String name = args.get(1); + if (Arrays.asList(deletealiases).contains(args.get(0)) && this.hasPermission(sender, "delete")) { // bending preset delete name. if (!Preset.presetExists(player, name)) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPresetName); return; } - Preset preset = Preset.getPreset(player, name); + final Preset preset = Preset.getPreset(player, name); preset.delete(); - sender.sendMessage(ChatColor.GREEN + this.deletePreset.replace("{name}", ChatColor.YELLOW + preset.getName() + ChatColor.GREEN)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.deletePreset.replace("{name}", ChatColor.YELLOW + preset.getName() + ChatColor.GREEN)); return; - } else if (Arrays.asList(bindaliases).contains(args.get(0)) && hasPermission(sender, "bind")) { //bending preset bind name + } else if (Arrays.asList(bindaliases).contains(args.get(0)) && this.hasPermission(sender, "bind")) { // bending preset bind name. if (args.size() < 3) { boolean boundAll = false; if (Preset.presetExists(player, name)) { - Preset preset = Preset.getPreset(player, name); + final Preset preset = Preset.getPreset(player, name); + + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.bound.replace("{name}", ChatColor.YELLOW + preset.getName() + ChatColor.GREEN)); boundAll = Preset.bindPreset(player, preset); - } else if (Preset.externalPresetExists(name) && hasPermission(sender, "bind.external")) { + + if (!boundAll) { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.failedToBindAll); + } + } else if (Preset.externalPresetExists(name) && this.hasPermission(sender, "bind.external")) { boundAll = Preset.bindExternalPreset(player, name); - } else if (!Preset.externalPresetExists(name) && hasPermission(sender, "bind.external")) { + } else if (!Preset.externalPresetExists(name) && this.hasPermission(sender, "bind.external")) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPresetNameExternal); return; } else if (bPlayer.isPermaRemoved()) { @@ -131,29 +146,25 @@ public void execute(CommandSender sender, List args) { return; } - sender.sendMessage(ChatColor.GREEN + bound.replace("{name}", ChatColor.YELLOW + name + ChatColor.GREEN)); - if (!boundAll) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.failedToBindAll); - } - } else if (hasPermission(sender, "bind.external.assign") && Preset.externalPresetExists(name)) { + } else if (this.hasPermission(sender, "bind.external.assign") && Preset.externalPresetExists(name)) { if (!Preset.externalPresetExists(name)) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPresetNameExternal); return; } - Player player2 = Bukkit.getPlayer(args.get(2)); + final Player player2 = Bukkit.getPlayer(args.get(2)); if (player2 != null && player2.isOnline()) { BendingPlayer bPlayer2 = BendingPlayer.getBendingPlayer(player2); if (bPlayer2 == null) { - GeneralMethods.createBendingPlayer(((Player) player2).getUniqueId(), player2.getName()); + GeneralMethods.createBendingPlayer(player2.getUniqueId(), player2.getName()); bPlayer2 = BendingPlayer.getBendingPlayer(player2); } if (bPlayer2.isPermaRemoved()) { GeneralMethods.sendBrandingMessage(player, ChatColor.RED + this.bendingRemovedOther); return; } - boolean boundAll = Preset.bindExternalPreset(player2, name); + final boolean boundAll = Preset.bindExternalPreset(player2, name); GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.boundOtherConfirm.replace("{target}", ChatColor.YELLOW + player2.getName() + ChatColor.GREEN).replace("{name}", ChatColor.YELLOW + name + ChatColor.GREEN + ChatColor.YELLOW)); GeneralMethods.sendBrandingMessage(player2, ChatColor.GREEN + this.bound.replace("{name}", ChatColor.YELLOW + name + ChatColor.GREEN)); @@ -164,26 +175,26 @@ public void execute(CommandSender sender, List args) { } else { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + ConfigManager.languageConfig.get().getString("Commands.Preset.PlayerNotFound")); } - } else if (hasPermission(sender, "bind.assign") && Preset.presetExists(player, name)) { + } else if (this.hasPermission(sender, "bind.assign") && Preset.presetExists(player, name)) { if (!Preset.presetExists(player, name)) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPresetName); return; } - Player player2 = Bukkit.getPlayer(args.get(2)); + final Player player2 = Bukkit.getPlayer(args.get(2)); if (player2 != null && player2.isOnline()) { BendingPlayer bPlayer2 = BendingPlayer.getBendingPlayer(player2); if (bPlayer2 == null) { - GeneralMethods.createBendingPlayer(((Player) player2).getUniqueId(), player2.getName()); + GeneralMethods.createBendingPlayer(player2.getUniqueId(), player2.getName()); bPlayer2 = BendingPlayer.getBendingPlayer(player2); } if (bPlayer2.isPermaRemoved()) { GeneralMethods.sendBrandingMessage(player, ChatColor.RED + this.bendingRemovedOther); return; } - Preset preset = Preset.getPreset(player, name); - boolean boundAll = Preset.bindPreset(player2, preset); + final Preset preset = Preset.getPreset(player, name); + final boolean boundAll = Preset.bindPreset(player2, preset); GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.boundOtherConfirm.replace("{target}", ChatColor.YELLOW + player2.getName() + ChatColor.GREEN).replace("{name}", ChatColor.YELLOW + name + ChatColor.GREEN + ChatColor.YELLOW)); GeneralMethods.sendBrandingMessage(player2, ChatColor.GREEN + this.succesfullyCopied.replace("{target}", ChatColor.YELLOW + player.getName() + ChatColor.GREEN)); @@ -195,10 +206,10 @@ public void execute(CommandSender sender, List args) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + ConfigManager.languageConfig.get().getString("Commands.Preset.PlayerNotFound")); } } - } else if (Arrays.asList(createaliases).contains(args.get(0)) && hasPermission(sender, "create")) { //bending preset create name - int limit = GeneralMethods.getMaxPresets(player); + } else if (Arrays.asList(createaliases).contains(args.get(0)) && this.hasPermission(sender, "create")) { // bending preset create name. + final int limit = GeneralMethods.getMaxPresets(player); - if (Preset.presets.get(player) != null && Preset.presets.get(player).size() >= limit) { + if (Preset.presets.get(player.getUniqueId()) != null && Preset.presets.get(player.getUniqueId()).size() >= limit) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.reachedMax); return; } else if (Preset.presetExists(player, name)) { @@ -209,21 +220,22 @@ public void execute(CommandSender sender, List args) { if (bPlayer == null) { return; } - HashMap abilities = (HashMap) bPlayer.getAbilities().clone(); + final HashMap abilities = (HashMap) bPlayer.getAbilities().clone(); - Preset preset = new Preset(player.getUniqueId(), name, abilities); + final Preset preset = new Preset(player.getUniqueId(), name, abilities); preset.save(player); GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.createdNewPreset.replace("{name}", ChatColor.YELLOW + name + ChatColor.GREEN)); } else { - help(sender, false); + this.help(sender, false); } } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 3 || !sender.hasPermission("bending.command.preset") || !(sender instanceof Player)) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 3 || !sender.hasPermission("bending.command.preset") || !(sender instanceof Player)) { return new ArrayList(); - List l = new ArrayList(); + } + final List l = new ArrayList(); if (args.size() == 0) { l.add("create"); l.add("delete"); @@ -231,22 +243,23 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("bind"); return l; } else if (args.size() == 2 && Arrays.asList(new String[] { "delete", "d", "del", "bind", "b" }).contains(args.get(0).toLowerCase())) { - List presets = Preset.presets.get(((Player) sender).getUniqueId()); - List presetNames = new ArrayList(); + final List presets = Preset.presets.get(((Player) sender).getUniqueId()); + final List presetNames = new ArrayList(); if (presets != null && presets.size() != 0) { - for (Preset preset : presets) { + for (final Preset preset : presets) { presetNames.add(preset.getName()); } } if (sender.hasPermission("bending.command.preset.bind.external")) { if (Preset.externalPresets.keySet().size() > 0) { - for (String externalPreset : Preset.externalPresets.keySet()) { + for (final String externalPreset : Preset.externalPresets.keySet()) { presetNames.add(externalPreset); } } } - if (presetNames.size() == 0) + if (presetNames.size() == 0) { return new ArrayList(); + } } return l; } diff --git a/src/com/projectkorra/projectkorra/command/ReloadCommand.java b/src/com/projectkorra/projectkorra/command/ReloadCommand.java index 4571491f3..2804256ea 100644 --- a/src/com/projectkorra/projectkorra/command/ReloadCommand.java +++ b/src/com/projectkorra/projectkorra/command/ReloadCommand.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import java.util.List; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * Executor for /bending reload. Extends {@link PKCommand}. @@ -18,8 +18,8 @@ public ReloadCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 0)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 0)) { return; } GeneralMethods.reloadPlugin(sender); diff --git a/src/com/projectkorra/projectkorra/command/RemoveCommand.java b/src/com/projectkorra/projectkorra/command/RemoveCommand.java index c44aaea1c..cd793d281 100644 --- a/src/com/projectkorra/projectkorra/command/RemoveCommand.java +++ b/src/com/projectkorra/projectkorra/command/RemoveCommand.java @@ -1,5 +1,13 @@ package com.projectkorra.projectkorra.command; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.Element.SubElement; @@ -10,23 +18,12 @@ import com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent; import com.projectkorra.rpg.RPGMethods; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - /** * Executor for /bending remove. Extends {@link PKCommand}. */ public class RemoveCommand extends PKCommand { - private String succesfullyRemovedElementSelf, wrongElementSelf, invalidElement, playerOffline, - wrongElementTarget, succesfullyRemovedElementTarget, - succesfullyRemovedElementTargetConfirm, succesfullyRemovedAllElementsTarget, - succesfullyRemovedAllElementsTargetConfirm; + private final String succesfullyRemovedElementSelf, wrongElementSelf, invalidElement, playerOffline, wrongElementTarget, succesfullyRemovedElementTarget, succesfullyRemovedElementTargetConfirm, succesfullyRemovedAllElementsTarget, succesfullyRemovedAllElementsTargetConfirm; public RemoveCommand() { super("remove", "/bending remove [Element]", ConfigManager.languageConfig.get().getString("Commands.Remove.Description"), new String[] { "remove", "rm" }); @@ -43,16 +40,16 @@ public RemoveCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 1, 2)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 1, 2)) { return; } - Player player = Bukkit.getPlayer(args.get(0)); + final Player player = Bukkit.getPlayer(args.get(0)); if (player == null) { if (args.size() == 1) { - Element e = Element.fromString(args.get(0)); - BendingPlayer senderBPlayer = BendingPlayer.getBendingPlayer(sender.getName()); + final Element e = Element.fromString(args.get(0)); + final BendingPlayer senderBPlayer = BendingPlayer.getBendingPlayer(sender.getName()); if (senderBPlayer != null && sender instanceof Player) { if (e != null) { @@ -63,38 +60,41 @@ public void execute(CommandSender sender, List args) { GeneralMethods.removeUnusableAbilities(sender.getName()); GeneralMethods.sendBrandingMessage(sender, e.getColor() + this.succesfullyRemovedElementSelf.replace("{element}", e.getName() + e.getType().getBending()).replace("{sender}", ChatColor.DARK_AQUA + sender.getName() + e.getColor())); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeSubElementEvent(sender, player, (SubElement) e, com.projectkorra.projectkorra.event.PlayerChangeSubElementEvent.Result.REMOVE)); - } else - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongElementSelf); + } else { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongElementSelf); + } return; } else if (e instanceof Element) { if (senderBPlayer.hasElement(e)) { senderBPlayer.getElements().remove(e); - for (SubElement sub : SubElement.getSubElements(e)) { + for (final SubElement sub : Element.getSubElements(e)) { senderBPlayer.getSubElements().remove(sub); } GeneralMethods.saveElements(senderBPlayer); GeneralMethods.saveSubElements(senderBPlayer); GeneralMethods.removeUnusableAbilities(sender.getName()); - GeneralMethods.sendBrandingMessage(sender, e.getColor() + succesfullyRemovedElementSelf.replace("{element}", e.getName() + e.getType().getBending())); + GeneralMethods.sendBrandingMessage(sender, e.getColor() + this.succesfullyRemovedElementSelf.replace("{element}", e.getName() + e.getType().getBending())); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeElementEvent(sender, (Player) sender, e, Result.REMOVE)); return; - } else - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongElementSelf); + } else { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongElementSelf); + } { return; } } - } else - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + invalidElement); + } else { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.invalidElement); + } { return; } } - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + playerOffline); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.playerOffline); return; } else { - help(sender, false); + this.help(sender, false); return; } } @@ -105,10 +105,10 @@ public void execute(CommandSender sender, List args) { bPlayer = BendingPlayer.getBendingPlayer(player); } if (args.size() == 2) { - Element e = Element.fromString(args.get(1)); + final Element e = Element.fromString(args.get(1)); if (e != null) { if (!bPlayer.hasElement(e)) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + wrongElementTarget.replace("{target}", player.getName())); + GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + this.wrongElementTarget.replace("{target}", player.getName())); return; } if (e instanceof SubElement) { @@ -116,7 +116,7 @@ public void execute(CommandSender sender, List args) { GeneralMethods.saveSubElements(bPlayer); } else { bPlayer.getElements().remove(e); - for (SubElement sub : SubElement.getSubElements(e)) { + for (final SubElement sub : Element.getSubElements(e)) { bPlayer.getSubElements().remove(sub); } GeneralMethods.saveElements(bPlayer); @@ -135,10 +135,12 @@ public void execute(CommandSender sender, List args) { GeneralMethods.saveElements(bPlayer); GeneralMethods.saveSubElements(bPlayer); GeneralMethods.removeUnusableAbilities(player.getName()); - if (GeneralMethods.hasRPG()) + if (GeneralMethods.hasRPG()) { RPGMethods.revokeAvatar(bPlayer.getUUID()); - if (!player.getName().equalsIgnoreCase(sender.getName())) + } + if (!player.getName().equalsIgnoreCase(sender.getName())) { GeneralMethods.sendBrandingMessage(sender, ChatColor.YELLOW + this.succesfullyRemovedAllElementsTargetConfirm.replace("{target}", ChatColor.DARK_AQUA + player.getName() + ChatColor.YELLOW)); + } GeneralMethods.sendBrandingMessage(player, ChatColor.YELLOW + this.succesfullyRemovedAllElementsTarget.replace("{sender}", ChatColor.DARK_AQUA + sender.getName() + ChatColor.YELLOW)); Bukkit.getServer().getPluginManager().callEvent(new PlayerChangeElementEvent(sender, player, null, Result.REMOVE)); @@ -148,12 +150,12 @@ public void execute(CommandSender sender, List args) { /** * Checks if the CommandSender has the permission 'bending.admin.remove'. If * not, it tells them they don't have permission to use the command. - * + * * @return True if they have the permission, false otherwise */ @Override - public boolean hasPermission(CommandSender sender) { - if (sender.hasPermission("bending.admin." + getName())) { + public boolean hasPermission(final CommandSender sender) { + if (sender.hasPermission("bending.admin." + this.getName())) { return true; } GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); @@ -161,12 +163,13 @@ public boolean hasPermission(CommandSender sender) { } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 2 || !sender.hasPermission("bending.command.remove")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 2 || !sender.hasPermission("bending.command.remove")) { return new ArrayList(); - List l = new ArrayList(); + } + final List l = new ArrayList(); if (args.size() == 0) { - for (Player p : Bukkit.getOnlinePlayers()) { + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } } else { @@ -175,7 +178,7 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("Fire"); l.add("Water"); l.add("Chi"); - for (Element e : Element.getAddonElements()) { + for (final Element e : Element.getAddonElements()) { l.add(e.getName()); } @@ -191,7 +194,7 @@ protected List getTabCompletion(CommandSender sender, List args) l.add("Sand"); l.add("Spiritual"); - for (SubElement e : Element.getAddonSubElements()) { + for (final SubElement e : Element.getAddonSubElements()) { l.add(e.getName()); } } diff --git a/src/com/projectkorra/projectkorra/command/StatsCommand.java b/src/com/projectkorra/projectkorra/command/StatsCommand.java new file mode 100644 index 000000000..9f84ae9f7 --- /dev/null +++ b/src/com/projectkorra/projectkorra/command/StatsCommand.java @@ -0,0 +1,239 @@ +package com.projectkorra.projectkorra.command; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; +import com.projectkorra.projectkorra.storage.DBConnection; +import com.projectkorra.projectkorra.util.Statistic; +import com.projectkorra.projectkorra.util.StatisticsMethods; + +public class StatsCommand extends PKCommand { + + private static final String[] getaliases = { "get", "g" }; + private static final String[] leaderboardaliases = { "leaderboard", "lb", "l" }; + + private final String invalidLookup; + private final String invalidSearchType; + private final String invalidStatistic; + private final String invalidPlayer; + + public StatsCommand() { + super("stats", "/bending stats [player/page]", ConfigManager.languageConfig.get().getString("Commands.Stats.Description"), new String[] { "statistics", "stats" }); + + this.invalidLookup = ConfigManager.languageConfig.get().getString("Commands.Stats.InvalidLookup"); + this.invalidSearchType = ConfigManager.languageConfig.get().getString("Commands.Stats.InvalidSearchType"); + this.invalidStatistic = ConfigManager.languageConfig.get().getString("Commands.Stats.InvalidStatistic"); + this.invalidPlayer = ConfigManager.languageConfig.get().getString("Commands.Stats.InvalidPlayer"); + } + + @Override + public void execute(final CommandSender sender, final List args) { + if (!this.correctLength(sender, args.size(), 3, 4)) { + return; + } + final CoreAbility ability = CoreAbility.getAbility(args.get(1)); + final Element element = Element.getElement(args.get(1)); + Object object = null; + if (ability != null) { + object = ability; + } else if (element != null) { + object = element; + } + final Statistic statistic = Statistic.getStatistic(args.get(2)); + + final boolean containsGet = this.contains(args.get(0), Arrays.asList(getaliases)); + final boolean containsLeaderboard = this.contains(args.get(0), Arrays.asList(leaderboardaliases)); + if (!containsGet && !containsLeaderboard) { + GeneralMethods.sendBrandingMessage(sender, this.invalidLookup); + return; + } else if (object == null && !args.get(1).equalsIgnoreCase("all")) { + GeneralMethods.sendBrandingMessage(sender, this.invalidSearchType); + return; + } else if (statistic == null) { + GeneralMethods.sendBrandingMessage(sender, this.invalidStatistic); + return; + } + if (containsGet) { + Player target = null; + if (args.size() == 4) { + target = ProjectKorra.plugin.getServer().getPlayer(args.get(3)); + if (target == null) { + GeneralMethods.sendBrandingMessage(sender, this.invalidPlayer.replace("%player%", args.get(3))); + return; + } + } else { + if (this.isPlayer(sender)) { + target = (Player) sender; + } else { + return; + } + } + final String message = this.getTarget(object, statistic, target); + GeneralMethods.sendBrandingMessage(sender, ChatColor.translateAlternateColorCodes('&', message)); + } else if (containsLeaderboard) { + int page = 1; + try { + page = Integer.parseInt(args.get(3)); + } + catch (IndexOutOfBoundsException | NumberFormatException e) { + } + final Object o = object; + final int p = page; + new BukkitRunnable() { + @Override + public void run() { + final List messages = StatsCommand.this.getLeaderboard(sender, o, statistic, p); + for (final String message : messages) { + sender.sendMessage(ChatColor.translateAlternateColorCodes('&', message)); + } + } + }.runTaskAsynchronously(ProjectKorra.plugin); + } + } + + public boolean contains(final String s, final List l) { + for (final String string : l) { + if (string.equalsIgnoreCase(s)) { + return true; + } + } + return false; + } + + public String getTarget(final Object object, final Statistic statistic, final Player target) { + String message = "&8- &f%object% " + statistic.getDisplayName() + " &e%player%: " + "&f%value%"; + long value = 0; + if (object == null) { + value = StatisticsMethods.getStatisticTotal(target.getUniqueId(), statistic); + } else { + value = StatisticsMethods.getStatistic(target.getUniqueId(), object, statistic); + } + if (object instanceof CoreAbility) { + final CoreAbility ability = (CoreAbility) object; + message = message.replace("%object%", ability.getName()).replace("%player%", target.getName()).replace("%value%", String.valueOf(value)); + } else if (object instanceof Element) { + final Element element = (Element) object; + message = message.replace("%object%", element.getName()).replace("%player%", target.getName()).replace("%value%", String.valueOf(value)); + } else { + message = message.replace("%object%", "Total").replace("%player%", target.getName()).replace("%value%", String.valueOf(value)); + } + return message; + } + + public List getLeaderboard(final CommandSender sender, final Object object, final Statistic statistic, final int page) { + final List messages = new ArrayList<>(); + final List uuids = this.pullUUIDs(statistic, object); + final int maxPage = (uuids.size() / 10) + 1; + int p = page > maxPage ? maxPage : page; + p = p < 1 ? 1 : p; + String title = "%object% " + statistic.getDisplayName() + " Leaderboard"; + if (object instanceof CoreAbility) { + final CoreAbility ability = (CoreAbility) object; + title = title.replace("%object%", ability.getName()); + } else if (object instanceof Element) { + final Element element = (Element) object; + title = title.replace("%object%", element.getName()); + } else { + title = title.replace("%object%", "Total"); + } + GeneralMethods.sendBrandingMessage(sender, ChatColor.translateAlternateColorCodes('&', "&8- &f" + title + " &8- [&7" + p + "/" + maxPage + "&8]")); + final int maxIndex = (10 * p) - 1; + final int minIndex = maxIndex - 9; + try { + uuids.get(minIndex); + } + catch (final IndexOutOfBoundsException e) { + messages.add("&7No statistics found."); + return messages; + } + for (int index = minIndex; index < maxIndex; index++) { + if (index < 0 || index >= uuids.size()) { + break; + } + final UUID uuid = uuids.get(index); + long value = 0; + if (object == null) { + value = StatisticsMethods.getStatisticTotal(uuid, statistic); + } else { + value = StatisticsMethods.getStatistic(uuid, object, statistic); + } + final OfflinePlayer oPlayer = ProjectKorra.plugin.getServer().getOfflinePlayer(uuid); + messages.add("&7" + (index + 1) + ") &e" + oPlayer.getName() + " &f" + value); + } + return messages; + } + + public List pullUUIDs(final Statistic statistic) { + return this.pullUUIDs(statistic, null); + } + + public List pullUUIDs(final Statistic statistic, final Object object) { + final Set uuids = new HashSet<>(); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT uuid FROM pk_stats")) { + while (rs.next()) { + final UUID uuid = UUID.fromString(rs.getString("uuid")); + if (object == null) { + if (StatisticsMethods.getStatisticTotal(uuid, statistic) > 0) { + uuids.add(uuid); + } + } else { + if (StatisticsMethods.getStatistic(uuid, object, statistic) > 0) { + uuids.add(uuid); + } + } + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + for (final Player player : ProjectKorra.plugin.getServer().getOnlinePlayers()) { + final UUID uuid = player.getUniqueId(); + if (object == null) { + if (StatisticsMethods.getStatisticTotal(uuid, statistic) > 0) { + uuids.add(uuid); + } + } else { + if (StatisticsMethods.getStatistic(uuid, object, statistic) > 0) { + uuids.add(uuid); + } + } + } + final List list = new ArrayList<>(uuids); + Collections.sort(list, new Comparator() { + @Override + public int compare(final UUID u1, final UUID u2) { + long value1 = 0; + long value2 = 0; + if (object == null) { + value1 = StatisticsMethods.getStatisticTotal(u1, statistic); + value2 = StatisticsMethods.getStatisticTotal(u2, statistic); + } else { + value1 = StatisticsMethods.getStatistic(u1, object, statistic); + value2 = StatisticsMethods.getStatistic(u2, object, statistic); + } + return (int) (value2 - value1); + } + }); + return list; + } + +} diff --git a/src/com/projectkorra/projectkorra/command/SubCommand.java b/src/com/projectkorra/projectkorra/command/SubCommand.java index b0b57a41c..8166a7825 100644 --- a/src/com/projectkorra/projectkorra/command/SubCommand.java +++ b/src/com/projectkorra/projectkorra/command/SubCommand.java @@ -1,23 +1,23 @@ package com.projectkorra.projectkorra.command; -import org.bukkit.command.CommandSender; - import java.util.List; +import org.bukkit.command.CommandSender; + /** * Interface representation of a command executor. */ public interface SubCommand { /** * Gets the name of the command. - * + * * @return The command's name */ public String getName(); /** * Gets the aliases for the command. - * + * * @return All aliases for the command */ public String[] getAliases(); @@ -25,14 +25,14 @@ public interface SubCommand { /** * Gets the proper use of the command, in the format '/b * {@link PKCommand#name name} arg1 arg2 ... ' - * + * * @return the proper use of the command */ public String getProperUse(); /** * Gets the description of the command. - * + * * @return the description */ public String getDescription(); @@ -40,7 +40,7 @@ public interface SubCommand { /** * Outputs the correct usage, and optionally the description, of a command * to the given {@link CommandSender}. - * + * * @param sender The CommandSender to output the help to * @param description Whether or not to output the description of the * command @@ -49,7 +49,7 @@ public interface SubCommand { /** * Executes the command. - * + * * @param sender The CommandSender who issued the command * @param args the command's arguments */ diff --git a/src/com/projectkorra/projectkorra/command/ToggleCommand.java b/src/com/projectkorra/projectkorra/command/ToggleCommand.java index 38a124978..853511d42 100644 --- a/src/com/projectkorra/projectkorra/command/ToggleCommand.java +++ b/src/com/projectkorra/projectkorra/command/ToggleCommand.java @@ -21,20 +21,12 @@ */ public class ToggleCommand extends PKCommand { - private String toggledOffForAll, toggleOffSelf, toggleOnSelf, toggleOffAll, toggleOnAll, - toggledOffSingleElement, toggledOnSingleElement, wrongElementOther, - toggledOnOtherElementConfirm, toggledOffOtherElementConfirm, toggledOnOtherElement, - toggledOffOtherElement, wrongElement, notFound; - - //config.addDefault("Commands.Toggle.Other.ToggledOnElementConfirm", "You've toggled on {target}'s {element}"); - //config.addDefault("Commands.Toggle.Other.ToggledOffElementConfirm", "You've toggled off {target}'s {element}"); - //config.addDefault("Commands.Toggle.Other.ToggledOnElementConfirm", "Your {element} has been toggled on by {sender}."); - //config.addDefault("Commands.Toggle.Other.ToggledOffElementConfirm", "Your {element} has been toggled off by {sender}."); + private final String toggledOffForAll, toggleOffSelf, toggleOnSelf, toggleOffAll, toggleOnAll, toggledOffSingleElement, toggledOnSingleElement, wrongElementOther, toggledOnOtherElementConfirm, toggledOffOtherElementConfirm, toggledOnOtherElement, toggledOffOtherElement, wrongElement, notFound; public ToggleCommand() { super("toggle", "/bending toggle [Player]", ConfigManager.languageConfig.get().getString("Commands.Toggle.Description"), new String[] { "toggle", "t" }); - FileConfiguration c = ConfigManager.languageConfig.get(); + final FileConfiguration c = ConfigManager.languageConfig.get(); this.toggledOffForAll = c.getString("Commands.Toggle.All.ToggledOffForAll"); this.toggleOffSelf = c.getString("Commands.Toggle.ToggledOff"); @@ -53,15 +45,15 @@ public ToggleCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!correctLength(sender, args.size(), 0, 2)) { + public void execute(final CommandSender sender, final List args) { + if (!this.correctLength(sender, args.size(), 0, 2)) { return; - } else if (args.size() == 0) { //bending toggle - if (!hasPermission(sender) || !isPlayer(sender)) { + } else if (args.size() == 0) { // bending toggle, + if (!this.hasPermission(sender) || !this.isPlayer(sender)) { return; } if (Commands.isToggledForAll) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + toggledOffForAll); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.toggledOffForAll); return; } BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); @@ -70,64 +62,67 @@ public void execute(CommandSender sender, List args) { bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); } if (bPlayer.isToggled()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + toggleOffSelf); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.toggleOffSelf); bPlayer.toggleBending(); } else { - GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + toggleOnSelf); + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.toggleOnSelf); bPlayer.toggleBending(); } } else if (args.size() == 1) { - if (args.size() == 1 && args.get(0).equalsIgnoreCase("all") && hasPermission(sender, "all")) { //bending toggle all + if (args.size() == 1 && args.get(0).equalsIgnoreCase("all") && this.hasPermission(sender, "all")) { // bending toggle all. if (Commands.isToggledForAll) { // Bending is toggled off for all players. Commands.isToggledForAll = false; - for (Player player : Bukkit.getOnlinePlayers()) { - GeneralMethods.sendBrandingMessage(player, ChatColor.GREEN + toggleOnAll); + for (final Player player : Bukkit.getOnlinePlayers()) { + GeneralMethods.sendBrandingMessage(player, ChatColor.GREEN + this.toggleOnAll); + } + if (!(sender instanceof Player)) { + GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + this.toggleOnAll); } - if (!(sender instanceof Player)) - GeneralMethods.sendBrandingMessage(sender, ChatColor.GREEN + toggleOnAll); } else { Commands.isToggledForAll = true; - for (Player player : Bukkit.getOnlinePlayers()) { - GeneralMethods.sendBrandingMessage(player, ChatColor.RED + toggleOffAll); + for (final Player player : Bukkit.getOnlinePlayers()) { + GeneralMethods.sendBrandingMessage(player, ChatColor.RED + this.toggleOffAll); + } + if (!(sender instanceof Player)) { + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.toggleOffAll); } - if (!(sender instanceof Player)) - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + toggleOffAll); } } else if (sender instanceof Player && args.size() == 1 && Element.fromString(args.get(0)) != null && !(Element.fromString(args.get(0)) instanceof SubElement)) { if (!BendingPlayer.getBendingPlayer(sender.getName()).hasElement(Element.fromString(args.get(0)))) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongElement); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongElement); return; } - Element e = Element.fromString(args.get(0)); - ChatColor color = e != null ? e.getColor() : null; - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); + final Element e = Element.fromString(args.get(0)); + final ChatColor color = e != null ? e.getColor() : null; + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(sender.getName()); bPlayer.toggleElement(e); if (bPlayer.isElementToggled(e)) { - GeneralMethods.sendBrandingMessage(sender, color + toggledOnSingleElement.replace("{element}", e.getName() + (e.getType() != null ? e.getType().getBending() : ""))); + GeneralMethods.sendBrandingMessage(sender, color + this.toggledOnSingleElement.replace("{element}", e.getName() + (e.getType() != null ? e.getType().getBending() : ""))); } else { - GeneralMethods.sendBrandingMessage(sender, color + toggledOffSingleElement.replace("{element}", e.getName() + (e.getType() != null ? e.getType().getBending() : ""))); + GeneralMethods.sendBrandingMessage(sender, color + this.toggledOffSingleElement.replace("{element}", e.getName() + (e.getType() != null ? e.getType().getBending() : ""))); } } else { - help(sender, false); + this.help(sender, false); } } else if (sender instanceof Player && args.size() == 2 && Element.fromString(args.get(0)) != null && !(Element.fromString(args.get(0)) instanceof SubElement)) { - Player target = Bukkit.getPlayer(args.get(1)); - if (!hasAdminPermission(sender)) + final Player target = Bukkit.getPlayer(args.get(1)); + if (!this.hasAdminPermission(sender)) { return; + } if (target == null) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + notFound); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.notFound); return; } if (!BendingPlayer.getBendingPlayer(target.getName()).hasElement(Element.fromString(args.get(0)))) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + wrongElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.wrongElementOther.replace("{target}", ChatColor.DARK_AQUA + target.getName() + ChatColor.RED)); return; } - Element e = Element.fromString(args.get(0)); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target.getName()); - ChatColor color = e != null ? e.getColor() : null; + final Element e = Element.fromString(args.get(0)); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(target.getName()); + final ChatColor color = e != null ? e.getColor() : null; if (bPlayer.isElementToggled(e)) { GeneralMethods.sendBrandingMessage(sender, color + this.toggledOffOtherElementConfirm.replace("{target}", target.getName()).replace("{element}", e.getName() + (e.getType() != null ? e.getType().getBending() : ""))); @@ -138,11 +133,11 @@ public void execute(CommandSender sender, List args) { } bPlayer.toggleElement(e); } else { - help(sender, false); + this.help(sender, false); } } - public boolean hasAdminPermission(CommandSender sender) { + public boolean hasAdminPermission(final CommandSender sender) { if (!sender.hasPermission("bending.admin.toggle")) { GeneralMethods.sendBrandingMessage(sender, super.noPermissionMessage); return false; @@ -151,23 +146,24 @@ public boolean hasAdminPermission(CommandSender sender) { } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 2 || !sender.hasPermission("bending.command.toggle.others")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 2 || !sender.hasPermission("bending.command.toggle.others")) { return new ArrayList(); - List l = new ArrayList(); + } + final List l = new ArrayList(); if (args.size() == 0) { - List elements = new ArrayList(); - for (Element e : Element.getAllElements()) { + final List elements = new ArrayList(); + for (final Element e : Element.getAllElements()) { elements.add(e.getName()); } Collections.sort(elements); l.add("All"); l.addAll(elements); } else { - for (Player p : Bukkit.getOnlinePlayers()) { + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } } return l; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/command/VersionCommand.java b/src/com/projectkorra/projectkorra/command/VersionCommand.java index bae277c25..05643ac3d 100644 --- a/src/com/projectkorra/projectkorra/command/VersionCommand.java +++ b/src/com/projectkorra/projectkorra/command/VersionCommand.java @@ -1,13 +1,13 @@ package com.projectkorra.projectkorra.command; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -import java.util.List; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * Executor for /bending version. Extends {@link PKCommand}. @@ -19,8 +19,8 @@ public VersionCommand() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 0)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 0)) { return; } diff --git a/src/com/projectkorra/projectkorra/command/WhoCommand.java b/src/com/projectkorra/projectkorra/command/WhoCommand.java index a4259172a..a337f8655 100644 --- a/src/com/projectkorra/projectkorra/command/WhoCommand.java +++ b/src/com/projectkorra/projectkorra/command/WhoCommand.java @@ -40,47 +40,47 @@ public class WhoCommand extends PKCommand { /** * Map storage of all ProjectKorra staffs' UUIDs and titles */ - final Map staff = new HashMap(), - playerInfoWords = new HashMap(); + final Map staff = new HashMap(), playerInfoWords = new HashMap(); - private String databaseOverload, noPlayersOnline, playerOffline; + private final String databaseOverload, noPlayersOnline, playerOffline; public WhoCommand() { super("who", "/bending who [Page/Player]", ConfigManager.languageConfig.get().getString("Commands.Who.Description"), new String[] { "who", "w" }); - databaseOverload = ConfigManager.languageConfig.get().getString("Commands.Who.DatabaseOverload"); - noPlayersOnline = ConfigManager.languageConfig.get().getString("Commands.Who.NoPlayersOnline"); - playerOffline = ConfigManager.languageConfig.get().getString("Commands.Who.PlayerOffline"); + this.databaseOverload = ConfigManager.languageConfig.get().getString("Commands.Who.DatabaseOverload"); + this.noPlayersOnline = ConfigManager.languageConfig.get().getString("Commands.Who.NoPlayersOnline"); + this.playerOffline = ConfigManager.languageConfig.get().getString("Commands.Who.PlayerOffline"); new BukkitRunnable() { + @Override public void run() { - Map updatedstaff = new HashMap(); + final Map updatedstaff = new HashMap(); try { - // Create a URL for the desired page - URLConnection url = new URL("http://www.projectkorra.com/staff.txt").openConnection(); + // Create a URL for the desired page. + final URLConnection url = new URL("https://projectkorra.com/staff.txt").openConnection(); url.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); - // Read all the text returned by the server - BufferedReader in = new BufferedReader(new InputStreamReader(url.getInputStream(), Charset.forName("UTF-8"))); + // Read all the text returned by the server. + final BufferedReader in = new BufferedReader(new InputStreamReader(url.getInputStream(), Charset.forName("UTF-8"))); String unparsed; while ((unparsed = in.readLine()) != null) { - String[] staffEntry = unparsed.split("/"); + final String[] staffEntry = unparsed.split("/"); if (staffEntry.length >= 2) { updatedstaff.put(staffEntry[0], ChatColor.translateAlternateColorCodes('&', staffEntry[1])); } } in.close(); - staff.clear(); - staff.putAll(updatedstaff); + WhoCommand.this.staff.clear(); + WhoCommand.this.staff.putAll(updatedstaff); } - catch (SocketException e) { + catch (final SocketException e) { ProjectKorra.log.info("Could not update staff list."); } - catch (MalformedURLException e) { + catch (final MalformedURLException e) { e.printStackTrace(); } - catch (IOException e) { + catch (final IOException e) { e.printStackTrace(); } } @@ -88,19 +88,19 @@ public void run() { } @Override - public void execute(CommandSender sender, List args) { - if (!hasPermission(sender) || !correctLength(sender, args.size(), 0, 1)) { + public void execute(final CommandSender sender, final List args) { + if (!this.hasPermission(sender) || !this.correctLength(sender, args.size(), 0, 1)) { return; } else if (args.size() == 1 && args.get(0).length() > 2) { - whoPlayer(sender, args.get(0)); + this.whoPlayer(sender, args.get(0)); } else if (args.size() == 0 || args.size() == 1) { int page = 1; - if (args.size() == 1 && isNumeric(args.get(0))) { + if (args.size() == 1 && this.isNumeric(args.get(0))) { page = Integer.valueOf(args.get(0)); } - List players = new ArrayList(); - for (Player player : Bukkit.getOnlinePlayers()) { - String playerName = player.getName(); + final List players = new ArrayList(); + for (final Player player : Bukkit.getOnlinePlayers()) { + final String playerName = player.getName(); String result = ""; BendingPlayer bp = BendingPlayer.getBendingPlayer(playerName); @@ -108,18 +108,18 @@ public void execute(CommandSender sender, List args) { GeneralMethods.createBendingPlayer(player.getUniqueId(), player.getName()); bp = BendingPlayer.getBendingPlayer(player.getName()); } - for (Element element : bp.getElements()) { + for (final Element element : bp.getElements()) { if (result == "") { result = ChatColor.WHITE + playerName + " - " + (((!bp.isElementToggled(element) || !bp.isToggled()) ? element.getColor() + "" + ChatColor.STRIKETHROUGH : element.getColor()) + element.getName().substring(0, 1)); } else { result = result + ChatColor.WHITE + " | " + (((!bp.isElementToggled(element) || !bp.isToggled()) ? element.getColor() + "" + ChatColor.STRIKETHROUGH : element.getColor()) + element.getName().substring(0, 1)); } } - if (staff.containsKey(player.getUniqueId().toString())) { + if (this.staff.containsKey(player.getUniqueId().toString())) { if (result == "") { - result = ChatColor.WHITE + playerName + " | " + staff.get(player.getUniqueId().toString()); + result = ChatColor.WHITE + playerName + " | " + this.staff.get(player.getUniqueId().toString()); } else { - result = result + ChatColor.WHITE + " | " + staff.get(player.getUniqueId().toString()); + result = result + ChatColor.WHITE + " | " + this.staff.get(player.getUniqueId().toString()); } } if (result == "") { @@ -128,11 +128,11 @@ public void execute(CommandSender sender, List args) { players.add(result); } if (players.isEmpty()) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + noPlayersOnline); + GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + this.noPlayersOnline); } else { boolean firstMessage = true; - - for (String s : getPage(players, ChatColor.GOLD + "Players:", page, true)) { + + for (final String s : this.getPage(players, ChatColor.GOLD + "Players:", page, true)) { if (firstMessage) { GeneralMethods.sendBrandingMessage(sender, s); firstMessage = false; @@ -146,48 +146,46 @@ public void execute(CommandSender sender, List args) { /** * Sends information on the given player to the CommandSender. - * + * * @param sender The CommandSender to display the information to * @param playerName The Player to look up */ private void whoPlayer(final CommandSender sender, final String playerName) { - //Player player = Bukkit.getPlayer(playerName); - @SuppressWarnings("deprecation") final OfflinePlayer player = Bukkit.getOfflinePlayer(playerName); if (player == null || !player.hasPlayedBefore() && !player.isOnline()) { GeneralMethods.sendBrandingMessage(sender, ChatColor.RED + "Player not found!"); return; } if (!player.isOnline() && !BendingPlayer.getPlayers().containsKey(player.getUniqueId())) { - GeneralMethods.sendBrandingMessage(sender, ChatColor.GRAY + playerOffline.replace("{player}", ChatColor.WHITE + player.getName() + ChatColor.GRAY).replace("{target}", ChatColor.WHITE + player.getName() + ChatColor.GRAY)); + GeneralMethods.sendBrandingMessage(sender, ChatColor.GRAY + this.playerOffline.replace("{player}", ChatColor.WHITE + player.getName() + ChatColor.GRAY).replace("{target}", ChatColor.WHITE + player.getName() + ChatColor.GRAY)); } - Player player_ = (Player) (player.isOnline() ? player : null); + final Player player_ = (Player) (player.isOnline() ? player : null); BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { GeneralMethods.createBendingPlayer(player.getUniqueId(), playerName); - BukkitRunnable runnable = new BukkitRunnable() { + final BukkitRunnable runnable = new BukkitRunnable() { @Override public void run() { int count = 0; final long delay = 200L; while (!BendingPlayer.getPlayers().containsKey(player.getUniqueId())) { - if (count > 5 * (1000 / delay)) { //After 5 seconds of waiting, tell the user the database is busy and to try again in a few seconds. - GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + databaseOverload); + if (count > 5 * (1000 / delay)) { // After 5 seconds of waiting, tell the user the database is busy and to try again in a few seconds. + GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + WhoCommand.this.databaseOverload); break; } count++; try { Thread.sleep(delay); } - catch (InterruptedException e) { + catch (final InterruptedException e) { e.printStackTrace(); - GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + databaseOverload); + GeneralMethods.sendBrandingMessage(sender, ChatColor.DARK_RED + WhoCommand.this.databaseOverload); break; } } - whoPlayer(sender, playerName); + WhoCommand.this.whoPlayer(sender, playerName); } }; runnable.runTaskAsynchronously(ProjectKorra.plugin); @@ -211,14 +209,14 @@ public void run() { if (bPlayer.canUseSpiritualProjection()) { sender.sendMessage(Element.SPIRITUAL.getColor() + " Can use Spiritual Projection"); } - for (SubElement se : Element.getAddonSubElements(Element.AIR)) { + for (final SubElement se : Element.getAddonSubElements(Element.AIR)) { if (bPlayer.canUseSubElement(se)) { sender.sendMessage(se.getColor() + " Can " + (!se.getType().equals(ElementType.NO_SUFFIX) ? "" : "use ") + se.getName() + se.getType().getBend()); } } } } - + if (bPlayer.hasElement(Element.WATER)) { if (bPlayer.isElementToggled(Element.WATER)) { sender.sendMessage(Element.WATER.getColor() + "- Waterbender"); @@ -243,14 +241,14 @@ public void run() { if (bPlayer.canWaterHeal()) { sender.sendMessage(Element.HEALING.getColor() + " Can Heal"); } - for (SubElement se : Element.getAddonSubElements(Element.WATER)) { + for (final SubElement se : Element.getAddonSubElements(Element.WATER)) { if (bPlayer.canUseSubElement(se)) { sender.sendMessage(se.getColor() + " Can " + (!se.getType().equals(ElementType.NO_SUFFIX) ? "" : "use ") + se.getName() + se.getType().getBend()); } } } } - + if (bPlayer.hasElement(Element.EARTH)) { if (bPlayer.isElementToggled(Element.EARTH)) { sender.sendMessage(Element.EARTH.getColor() + "- Earthbender"); @@ -268,14 +266,14 @@ public void run() { if (bPlayer.canSandbend()) { sender.sendMessage(Element.SAND.getColor() + " Can Sandbend"); } - for (SubElement se : Element.getAddonSubElements(Element.EARTH)) { + for (final SubElement se : Element.getAddonSubElements(Element.EARTH)) { if (bPlayer.canUseSubElement(se)) { sender.sendMessage(se.getColor() + " Can " + (!se.getType().equals(ElementType.NO_SUFFIX) ? "" : "use ") + se.getName() + se.getType().getBend()); } } } } - + if (bPlayer.hasElement(Element.FIRE)) { if (bPlayer.isElementToggled(Element.FIRE)) { sender.sendMessage(Element.FIRE.getColor() + "- Firebender"); @@ -290,14 +288,14 @@ public void run() { if (bPlayer.canLightningbend()) { sender.sendMessage(Element.LIGHTNING.getColor() + " Can Lightningbend"); } - for (SubElement se : Element.getAddonSubElements(Element.FIRE)) { + for (final SubElement se : Element.getAddonSubElements(Element.FIRE)) { if (bPlayer.canUseSubElement(se)) { sender.sendMessage(se.getColor() + " Can " + (!se.getType().equals(ElementType.NO_SUFFIX) ? "" : "use ") + se.getName() + se.getType().getBend()); } } } } - + if (bPlayer.hasElement(Element.CHI)) { if (bPlayer.isElementToggled(Element.CHI)) { sender.sendMessage(Element.CHI.getColor() + "- Chiblocker"); @@ -305,14 +303,14 @@ public void run() { sender.sendMessage(Element.CHI.getColor() + "" + ChatColor.STRIKETHROUGH + "- Chiblocker"); } } - - for (Element element : Element.getAddonElements()) { + + for (final Element element : Element.getAddonElements()) { if (bPlayer.hasElement(element)) { sender.sendMessage(element.getColor() + "" + (bPlayer.isElementToggled(element) ? "" : ChatColor.STRIKETHROUGH) + "- " + element.getName() + (element.getType() != null ? element.getType().getBender() : "")); if (player_ != null) { - for (SubElement subelement : Element.getSubElements(element)) { + for (final SubElement subelement : Element.getSubElements(element)) { if (GeneralMethods.hasSpirits()) { - SpiritPlayer sPlayer = SpiritPlayer.getSpiritPlayer(player_); + final SpiritPlayer sPlayer = SpiritPlayer.getSpiritPlayer(player_); if (subelement.equals(SpiritElement.DARK) && sPlayer.isLightSpirit()) { sender.sendMessage(subelement.getColor() + " Is " + sPlayer.getSpirit().getName() + element.getName()); } @@ -331,12 +329,12 @@ public void run() { } } - UUID uuid = player.getUniqueId(); + final UUID uuid = player.getUniqueId(); if (bPlayer != null) { sender.sendMessage("Abilities: "); for (int i = 1; i <= 9; i++) { - String ability = bPlayer.getAbilities().get(i); - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final String ability = bPlayer.getAbilities().get(i); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (coreAbil == null) { continue; } else { @@ -353,12 +351,12 @@ public void run() { } } - if (staff.containsKey(uuid.toString())) { - sender.sendMessage(staff.get(uuid.toString())); + if (this.staff.containsKey(uuid.toString())) { + sender.sendMessage(this.staff.get(uuid.toString())); } - - if (player_.hasPermission("bending.donor")) { - // Requires Servers to define `server-name` in their server.properties file. Example: server-name=My Server + + if (player.getPlayer() != null && player.getPlayer().hasPermission("bending.donor")) { + // Requires Servers to define `server-name` in their server.properties file. Example: server-name=My Server. sender.sendMessage(Element.AVATAR.getColor() + ProjectKorra.plugin.getServer().getServerName() + " Donor"); } } @@ -366,11 +364,12 @@ public void run() { } @Override - protected List getTabCompletion(CommandSender sender, List args) { - if (args.size() >= 1 || !sender.hasPermission("bending.command.who")) + protected List getTabCompletion(final CommandSender sender, final List args) { + if (args.size() >= 1 || !sender.hasPermission("bending.command.who")) { return new ArrayList(); - List l = new ArrayList(); - for (Player p : Bukkit.getOnlinePlayers()) { + } + final List l = new ArrayList(); + for (final Player p : Bukkit.getOnlinePlayers()) { l.add(p.getName()); } return l; diff --git a/src/com/projectkorra/projectkorra/configuration/Config.java b/src/com/projectkorra/projectkorra/configuration/Config.java index 8072997c1..bb63cd011 100644 --- a/src/com/projectkorra/projectkorra/configuration/Config.java +++ b/src/com/projectkorra/projectkorra/configuration/Config.java @@ -1,11 +1,11 @@ package com.projectkorra.projectkorra.configuration; -import com.projectkorra.projectkorra.ProjectKorra; +import java.io.File; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; -import java.io.File; +import com.projectkorra.projectkorra.ProjectKorra; /** * A config utility class for Project Korra. To get the config itself use @@ -13,21 +13,21 @@ */ public class Config { - private ProjectKorra plugin; + private final ProjectKorra plugin; - private File file; - private FileConfiguration config; + private final File file; + private final FileConfiguration config; /** * Creates a new {@link Config} with the file being the configuration file. - * + * * @param file The file to create/load */ - public Config(File file) { + public Config(final File file) { this.plugin = ProjectKorra.plugin; - this.file = new File(plugin.getDataFolder() + File.separator + file); + this.file = new File(this.plugin.getDataFolder() + File.separator + file); this.config = YamlConfiguration.loadConfiguration(this.file); - reload(); + this.reload(); } /** @@ -36,24 +36,24 @@ public Config(File file) { * for the config. */ public void create() { - if (!file.getParentFile().exists()) { + if (!this.file.getParentFile().exists()) { try { - file.getParentFile().mkdir(); - plugin.getLogger().info("Generating new directory for " + file.getName() + "!"); + this.file.getParentFile().mkdir(); + this.plugin.getLogger().info("Generating new directory for " + this.file.getName() + "!"); } - catch (Exception e) { - plugin.getLogger().info("Failed to generate directory!"); + catch (final Exception e) { + this.plugin.getLogger().info("Failed to generate directory!"); e.printStackTrace(); } } - if (!file.exists()) { + if (!this.file.exists()) { try { - file.createNewFile(); - plugin.getLogger().info("Generating new " + file.getName() + "!"); + this.file.createNewFile(); + this.plugin.getLogger().info("Generating new " + this.file.getName() + "!"); } - catch (Exception e) { - plugin.getLogger().info("Failed to generate " + file.getName() + "!"); + catch (final Exception e) { + this.plugin.getLogger().info("Failed to generate " + this.file.getName() + "!"); e.printStackTrace(); } } @@ -61,11 +61,11 @@ public void create() { /** * Gets the {@link FileConfiguration} object from the {@link Config}. - * + * * @return the file configuration object */ public FileConfiguration get() { - return config; + return this.config; } /** @@ -73,11 +73,11 @@ public FileConfiguration get() { * not exist it will run {@link #create()} first before loading the config. */ public void reload() { - create(); + this.create(); try { - config.load(file); + this.config.load(this.file); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } @@ -89,10 +89,10 @@ public void reload() { */ public void save() { try { - config.options().copyDefaults(true); - config.save(file); + this.config.options().copyDefaults(true); + this.config.save(this.file); } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java index cc15bdc8a..429e365fe 100644 --- a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java +++ b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java @@ -20,12 +20,12 @@ public ConfigManager() { configCheck(ConfigType.PRESETS); } - public static void configCheck(ConfigType type) { + public static void configCheck(final ConfigType type) { FileConfiguration config; if (type == ConfigType.PRESETS) { config = presetConfig.get(); - ArrayList abilities = new ArrayList(); + final ArrayList abilities = new ArrayList(); abilities.add("FireBlast"); abilities.add("AirBlast"); abilities.add("WaterManipulation"); @@ -42,7 +42,7 @@ public static void configCheck(ConfigType type) { } else if (type == ConfigType.LANGUAGE) { config = languageConfig.get(); - ArrayList helpLines = new ArrayList(); + final ArrayList helpLines = new ArrayList(); helpLines.add("&c/bending help [Ability/Command] &eDisplay help."); helpLines.add("&c/bending choose [Element] &eChoose an element."); helpLines.add("&c/bending bind [Ability] # &eBind an ability."); @@ -76,14 +76,13 @@ public static void configCheck(ConfigType type) { config.addDefault("Chat.Prefixes.Avatar", "[Avatar]"); config.addDefault("Chat.Prefixes.Nonbender", "[Nonbender]"); - config.addDefault("Extras.Water.NightMessage", "Your waterbending has become empowered due to the full moon rising."); + config.addDefault("Extras.Water.NightMessage", "Your waterbending has become empowered due to the moon rising."); config.addDefault("Extras.Water.DayMessage", "You feel the empowering of your waterbending subside as the moon sets."); config.addDefault("Extras.Fire.NightMessage", "You feel the empowering of your firebending subside as the sun sets."); - config.addDefault("Extras.Fire.DayMessage", "You feel the strength of the rising sun empowering your firebending."); + config.addDefault("Extras.Fire.DayMessage", "You feel the strength of the rising sun empower your firebending."); config.addDefault("Commands.NoPermission", "You do not have permission to do that."); config.addDefault("Commands.MustBePlayer", "You must be a player to perform this action."); - config.addDefault("Commands.GeneralHelpLines", helpLines); config.addDefault("Commands.Who.Description", "This command will tell you what element all players that are online are (If you don't specify a player) or give you information about the player that you specify."); config.addDefault("Commands.Who.NoPlayersOnline", "There is no one online."); @@ -92,7 +91,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Version.Description", "Displays the installed version of ProjectKorra."); - config.addDefault("Commands.Toggle.Description", "This command will toggle a player's own Bending on or off. If toggled off, all abilities should stop working until it is toggled back on. Logging off will automatically toggle your Bending back on. If you run the command /bending toggle all, Bending will be turned off for all players and cannot be turned back on until the command is run again."); + config.addDefault("Commands.Toggle.Description", "This command will toggle a player's own bending on or off. If toggled off, all abilities should stop working until it is toggled back on. Logging off will automatically toggle your Bending back on. If you run the command /bending toggle all, Bending will be turned off for all players and cannot be turned back on until the command is run again."); config.addDefault("Commands.Toggle.ToggledOn", "You have turned your bending back on."); config.addDefault("Commands.Toggle.ToggledOff", "Your bending has been toggled off. You will not be able to use most abilities until you toggle it back."); config.addDefault("Commands.Toggle.ToggleOnSingleElement", "You have toggled on your {element}."); @@ -108,18 +107,18 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Toggle.Other.PlayerNotFound", "Target is not found."); config.addDefault("Commands.Toggle.Other.WrongElement", "{target} doesn't have that element."); - config.addDefault("Commands.Remove.Description", "This command will remove the element of the targeted [Player]. The player will be able to re-pick their element after this command is run on them, assuming their Bending was not permaremoved."); + config.addDefault("Commands.Remove.Description", "This command will remove the element of the targeted [Player]. The player will be able to re-pick their element after this command is run on them, assuming their bending was not permaremoved."); config.addDefault("Commands.Remove.Other.RemovedAllElements", "Your bending has been removed by {sender}."); config.addDefault("Commands.Remove.Other.RemovedAllElementsConfirm", "You've removed {target}'s bending."); config.addDefault("Commands.Remove.Other.RemovedElement", "Your {element} has been removed by {sender}."); config.addDefault("Commands.Remove.Other.RemovedElementConfirm", "You removed {target}'s {element}."); - config.addDefault("Commands.Remove.Other.WrongElement", "{target} does not have that element!"); + config.addDefault("Commands.Remove.Other.WrongElement", "{target} does not have that element."); config.addDefault("Commands.Remove.RemovedElement", "You've removed your {element}."); config.addDefault("Commands.Remove.InvalidElement", "That element is invalid!"); - config.addDefault("Commands.Remove.WrongElement", "You do not have that element!"); + config.addDefault("Commands.Remove.WrongElement", "You do not have that element."); config.addDefault("Commands.Remove.PlayerOffline", "That player is offline!"); - config.addDefault("Commands.Reload.Description", "This command will reload the Bending config file."); + config.addDefault("Commands.Reload.Description", "This command will reload the bending config files."); config.addDefault("Commands.Reload.SuccessfullyReloaded", "Bending Config reloaded!"); config.addDefault("Commands.Preset.Description", "This command manages Presets, which are saved bindings. Use /bending preset list to view your existing presets, use /bending [create|delete] [name] to manage your presets, and use /bending bind [name] to bind an existing preset."); @@ -141,24 +140,24 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Preset.Other.SuccesfullyBoundConfirm", "The bound slots of {target} have been set to match the {name} preset."); config.addDefault("Commands.Preset.External.NoPresetName", "No external preset found with that name."); - config.addDefault("Commands.PermaRemove.Description", "This command will permanently remove the Bending of the targeted . Once removed, a player may only receive Bending again if this command is run on them again. This command is typically reserved for administrators."); + config.addDefault("Commands.Stats.InvalidLookup", "Invalid lookup argument."); + config.addDefault("Commands.Stats.InvalidSearchType", "Invalid search type."); + config.addDefault("Commands.Stats.InvalidStatistic", "Invalid statistic."); + config.addDefault("Commands.Stats.InvalidPlayer", "Player '%player%' not found."); + + config.addDefault("Commands.Stats.Description", "This command manages statistics. View your own, another player's statistics along with the server leaderboard."); + + config.addDefault("Commands.PermaRemove.Description", "This command will permanently remove the bending of the targeted . Once removed, a player may only receive bending again if this command is run on them again. This command is typically reserved for administrators."); config.addDefault("Commands.PermaRemove.PlayerOffline", "That player is not online."); config.addDefault("Commands.PermaRemove.Restored", "Your bending has been restored."); config.addDefault("Commands.PermaRemove.RestoredConfirm", "You have restored the bending of {target}."); config.addDefault("Commands.PermaRemove.Removed", "Your bending has been permanently removed."); config.addDefault("Commands.PermaRemove.RemovedConfirm", "You have removed the bending of {target}."); - config.addDefault("Commands.Invincible.Description", "This command will make you impervious to all Bending damage. Once you use this command, you will stay invincible until you log off or use this command again."); + config.addDefault("Commands.Invincible.Description", "This command will make you immune to all bending damage. Once you use this command, you will stay invincible until you log off or use this command again."); config.addDefault("Commands.Invincible.ToggledOn", "You are now invincible to all bending damage and effects. Use this command again to disable this."); config.addDefault("Commands.Invincible.ToggledOff", "You are no longer invincible to all bending damage and effects."); - config.addDefault("Commands.Import.Description", "This command will import your old bendingPlayers.yml from the Bending plugin. It will generate a convert.yml file to convert the data to be used with this plugin. You can delete the file once the complete message is displayed. This command should only be used ONCE."); - config.addDefault("Commands.Import.Disabled", "Import has been disabled in the config!"); - config.addDefault("Commands.Import.PreparingData", "Preparing Data for import."); - config.addDefault("Commands.Import.ImportStarted", "Import of data started. Do NOT stop / reload your server."); - config.addDefault("Commands.Import.DebugWarning", "Console will print out all of the players that are imported if debug mode is enabled as they import."); - config.addDefault("Commands.Import.DataQueuedUp", "All data has been queued up, please allow up to 5 minutes for the data to complete, then reboot your server."); - config.addDefault("Commands.Help.Description", "This command provides information on how to use other commands in ProjectKorra."); config.addDefault("Commands.Help.Required", "Required"); config.addDefault("Commands.Help.Optional", "Optional"); @@ -171,9 +170,9 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Display.NoCombosAvailable", "There are no {element} combos available."); config.addDefault("Commands.Display.NoPassivesAvailable", "There are no {element} passives available."); - config.addDefault("Commands.Display.NoAbilitiesAvailable", "There are no {element} abilities on this server!"); + config.addDefault("Commands.Display.NoAbilitiesAvailable", "There are no {element} abilities on this server."); config.addDefault("Commands.Display.InvalidArgument", "Not a valid argument."); - config.addDefault("Commands.Display.PlayersOnly", "This command is only useable by players."); + config.addDefault("Commands.Display.PlayersOnly", "This command is only usable by players."); config.addDefault("Commands.Display.NoBinds", "You do not have any abilities bound.\nIf you would like to see a list of available abilities, please use the /bending display [Element] command. Use /bending help for more information."); config.addDefault("Commands.Debug.Description", "Outputs information on the current ProjectKorra installation to /plugins/ProjectKorra/debug.txt"); @@ -182,7 +181,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Copy.Description", "This command will allow the user to copy the binds of another player either for himself or assign them to if specified."); config.addDefault("Commands.Copy.PlayerNotFound", "Couldn't find player."); config.addDefault("Commands.Copy.SuccessfullyCopied", "Your binds have been set to match {target}'s!"); - config.addDefault("Commands.Copy.FailedToBindAll", "Not all moves have been bound because you do not have the permission to."); + config.addDefault("Commands.Copy.FailedToBindAll", "Some moves were not bound due to insufficient permissions."); config.addDefault("Commands.Copy.Other.SuccessfullyCopied", "{target1}'s binds have been set to match {target2}'s."); config.addDefault("Commands.Clear.Description", "This command will clear the bound ability from the slot you specify (if you specify one). If you choose not to specify a slot, all of your abilities will be cleared."); @@ -190,11 +189,12 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Clear.Cleared", "Your bound abilities have been cleared."); config.addDefault("Commands.Clear.WrongNumber", "The slot must be an integer between 1 and 9."); config.addDefault("Commands.Clear.ClearedSlot", "You have cleared slot #{slot}."); - config.addDefault("Commands.Clear.AlreadyEmpty", "That slot was is already empty."); + config.addDefault("Commands.Clear.AlreadyEmpty", "That slot is already empty."); - config.addDefault("Commands.Choose.Description", "This command will allow the user to choose a player either for himself or if specified. This command can only be used once per player unless they have permission to rechoose their element."); + config.addDefault("Commands.Choose.Description", "This command will allow the user to choose a single element for themselves or if specified. This command can only be used once per player unless they have permission to rechoose their element."); config.addDefault("Commands.Choose.InvalidElement", "That is not a valid element."); config.addDefault("Commands.Choose.PlayerNotFound", "Could not find player."); + config.addDefault("Commands.Choose.OnCooldown", "You must wait %cooldown% before changing your element."); config.addDefault("Commands.Choose.SuccessfullyChosenCFW", "You are now a {element}."); config.addDefault("Commands.Choose.SuccessfullyChosenAE", "You are now an {element}."); config.addDefault("Commands.Choose.Other.SuccessfullyChosenCFW", "{target} is now a {element}."); @@ -231,21 +231,21 @@ public static void configCheck(ConfigType type) { config.addDefault("Commands.Add.Other.AlreadyHasElement", "{target} already has that element!"); config.addDefault("Commands.Add.Other.AlreadyHasSubElement", "{target} already has that subelement!"); config.addDefault("Commands.Add.Other.AlreadyHasAllElements", "{target} already has all elements!"); - + config.addDefault("DeathMessages.Enabled", true); config.addDefault("DeathMessages.Default", "{victim} was slain by {attacker}'s {ability}"); config.addDefault("Abilities.Avatar.AvatarState.Description", "The signature ability of the Avatar, this is a toggle. Left click to activate to become " + "nearly unstoppable. While in the Avatar State, the user takes severely reduced damage from " + "all sources, regenerates health rapidly, and is granted extreme speed. Nearly all abilities " + "are incredibly amplified in this state. Additionally, AirShield and FireJet become toggle-able " + "abilities and last until you deactivate them or the Avatar State. Left click again with the Avatar " + "State selected to deactivate it."); - config.addDefault("Commands.Help.Elements.Air", "Air is the element of freedom. Airbenders are natural pacifists and great explorers. There is nothing stopping them from scaling the tallest of mountains and walls easily. They specialize in redirection, from blasting things away with gusts of winds, to forming a shield around them to prevent damage. Easy to get across flat terrains, such as oceans, there is practically no terrain off limits to Airbenders. They lack much raw damage output, but make up for it with with their ridiculous amounts of utility and speed.\nAirbenders can chain their abilities into combos, type /b help AirCombos for more information."); + config.addDefault("Commands.Help.Elements.Air", "Air is the element of freedom. Airbenders are natural pacifists and great explorers. There is nothing stopping them from scaling the tallest mountains and walls easily. They specialize in redirection, from blasting things away with gusts of winds, to forming a shield around them to prevent damage. Easy to get across flat terrains, such as oceans, there is practically no terrain off limits to Airbenders. They lack much raw damage output, but make up for it with with their ridiculous amounts of utility and speed.\nEnter /b display Air for a list of the available air abilities."); config.addDefault("Abilities.Air.AirBlast.Description", "AirBlast is the most fundamental bending technique of an airbender. It allows the bender to be extremely agile and possess great mobility, but also has many utility options, such as cooling lava, opening doors and flicking levers."); config.addDefault("Abilities.Air.AirBlast.Instructions", "\n" + "(Push) " + "Left click while aiming at an entity to push them back." + "\n" + "(Throw) " + "Tap sneak to select a location and left click in a direction to throw entities away from the selected location."); config.addDefault("Abilities.Air.AirBlast.DeathMessage", "{victim} was flung by {attacker}'s {ability}"); - config.addDefault("Abilities.Air.AirBlast.HorizontalVelocityDeath", "{victim} experienced kinetic damage by {attacker}'s {ability}"); + config.addDefault("Abilities.Air.AirBlast.HorizontalVelocityDeath", "{victim} experienced a fatal collision by {attacker}'s {ability}"); config.addDefault("Abilities.Air.AirBurst.Description", "AirBurst is one of the most powerful abilities in the airbender's arsenal. It allows the bender to create space between them and whoever is close to them. AirBurst is extremely useful when you're surrounded by mobs, of if you're low in health and need to escape. It can also be useful for confusing your target also."); config.addDefault("Abilities.Air.AirBurst.Instructions", "\n" + "(Sphere) Hold sneak until particles appear and then release shift to create air that expands outwards, pushing entities back. If you fall from great height while you are on this slot, the burst will automatically activate." + "\n" + "(Cone) While charging the move with shift, click to send the burst in a cone only going in one direction."); config.addDefault("Abilities.Air.AirBurst.DeathMessage", "{victim} was thrown down by {attacker}'s {ability}"); - config.addDefault("Abilities.Air.AirBurst.HorizontalVelocityDeath", "{victim} experienced kinetic damage by {attacker}'s {ability}"); + config.addDefault("Abilities.Air.AirBurst.HorizontalVelocityDeath", "{victim} experienced a fatal collision by {attacker}'s {ability}"); config.addDefault("Abilities.Air.AirScooter.Description", "AirScooter is a fast means of transportation. It can be used to escape from enemies or confuse them by using air scooter around them."); config.addDefault("Abilities.Air.AirScooter.Instructions", "Sprint, jump, and left click while in the air to activate air scooter. You will then move forward in the direction you're looking."); config.addDefault("Abilities.Air.Tornado.Description", "Tornado is one of the most powerful and advanced abilities that an Airbender knows. If the tornado meets a player or mob, it will push them around. Tornado can also be used to push back projectiles and used for mobility. Use a tornado directly under you to propel yourself upwards."); @@ -256,12 +256,12 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.AirSpout.Instructions", "Left click to activate a spout beneath you and hold spacebar to go higher. If you wish to go lower, simply hold sneak. To disable this ability, left click once again."); config.addDefault("Abilities.Air.AirSuction.Description", "AirSuction is a basic ability that allows you to manipulation an entity's movement. It can be used to bring someone back to you when they're running away, or even to get yourself to great heights."); config.addDefault("Abilities.Air.AirSuction.Instructions", "\n" + "(Pull) Left click while aiming at a target to pull them towards you." + "\n" + "(Manipulation) Sneak to select a point and then left click at a target or yourself to send you or your target to the point that you selected."); - config.addDefault("Abilities.Air.AirSuction.HorizontalVelocityDeath", "{victim} experienced kinetic damage by {attacker}'s {ability}"); + config.addDefault("Abilities.Air.AirSuction.HorizontalVelocityDeath", "{victim} experienced a fatal collision by {attacker}'s {ability}"); config.addDefault("Abilities.Air.AirSwipe.Description", "AirSwipe is the most commonly used damage ability in an airbender's arsenal. An arc of air will flow from you towards the direction you're facing, cutting and pushing back anything in its path. This ability will extinguish fires, cool lava, and cut things like grass, mushrooms, and flowers."); config.addDefault("Abilities.Air.AirSwipe.Instructions", "\n" + "(Uncharged) Simply left click to send an air swipe out that will damage targets that it comes into contact with." + "\n" + "(Charged) Hold sneak until particles appear, then release sneak to send a more powerful air swipe out that damages entity's that it comes into contact with."); config.addDefault("Abilities.Air.AirSwipe.DeathMessage", "{victim} was struck by {attacker}'s {ability}"); - config.addDefault("Abilities.Air.Flight.Description", "Flight is one of the most advanced airbending abilities there is. It's used to escape from players or mobs or to confuse your enemy by flying around them, making you extremely hard to hit."); - config.addDefault("Abilities.Air.Flight.Instructions", "\n" + "(Fly) Jump in the air and hold sneak to fly in the direction that you're looking." + "\n" + "(Hover) While flying with this ability, left click to hover in the air. Left click again to disable hovering"); + config.addDefault("Abilities.Air.Flight.Description", "Fly through the air as Zaheer and Guru Laghima did! This multiability allows for three modes of flight: soaring, gliding, and levitating. You can also right-click another player while flying to have them become your passenger! When flying at fast speeds, flying past nearby enemies will damage them for half your speed and knock them in the direction you're heading!"); + config.addDefault("Abilities.Air.Flight.Instructions", "\n- (To start flying, jump and left-click)\n- (Soar) Left-Click to change flying speeds.\n- (Glide) Normal minecraft gliding. Slowing down or speeding up in this mode will affect the Soar speed.\n- (Levitate) Basically minecraft flying, allowing players to fly around for building purposes or a more controlled 'hovering'.\n- (Ending) Being in this mode sets any gliding and flight back the the state they were before using the ability."); config.addDefault("Abilities.Air.Suffocate.Description", "This ability is one of the most dangerous abilities an Airbender possesses. Although it is difficult to perform, it's extremely deadly once the ability starts, making it difficult for enemies to escape."); config.addDefault("Abilities.Air.Suffocate.Instructions", "Hold sneak while looking at a target to begin suffocating them. If the target goes out of range, you get damaged, or you release sneak, the ability will cancel."); config.addDefault("Abilities.Air.Suffocate.DeathMessage", "{victim} was asphyxiated by {attacker}'s {ability}"); @@ -273,11 +273,11 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.Passive.AirSaturation.Description", "AirSaturation is a passive ability which causes airbenders' hunger to deplete at a slower rate."); config.addDefault("Abilities.Air.Passive.GracefulDescent.Description", "GracefulDescent is a passive ability which allows airbenders to make a gentle landing, negating all fall damage on any surface."); - config.addDefault("Commands.Help.Elements.Water", "Water is the element of change. Waterbending focuses on using your opponents own force against them. Using redirection and various dodging tactics, you can be made practically untouchable by an opponent. Waterbending provides agility, along with strong offensive skills while in or near water.\nWaterbenders can chain their abilities into combos, type /b help WaterCombos for more information."); + config.addDefault("Commands.Help.Elements.Water", "Water is the element of change. Waterbending focuses on using your opponents own force against them. Using redirection and various dodging tactics, you can be made practically untouchable by an opponent. Waterbending provides agility, along with strong offensive skills while in or near water.\nEnter /b display Water for a list of the available water abilities."); config.addDefault("Abilities.Water.Bloodbending.Description", "Bloodbending is one of the most unique bending abilities that existed and it has immense power, which is why it was made illegal in the Avatar universe. People who are capable of bloodbending are immune to your technique, and you are immune to theirs."); config.addDefault("Abilities.Water.Bloodbending.Instructions", "\n" + "(Control) Hold sneak while looking at an entity to bloodbend them. You will then be controlling the entity, making them move wherever you look." + "\n" + "(Throw) While bloodbending an entity, left click to throw that entity in the direction you're looking."); config.addDefault("Abilities.Water.Bloodbending.DeathMessage", "{victim} was destroyed by {attacker}'s {ability}"); - config.addDefault("Abilities.Water.Bloodbending.HorizontalVelocityDeath", "{victim} experienced kinetic damage by {attacker}'s {ability}"); + config.addDefault("Abilities.Water.Bloodbending.HorizontalVelocityDeath", "{victim} experienced a fatal collision from {attacker}'s {ability}"); config.addDefault("Abilities.Water.HealingWaters.Description", "HealingWaters is an advanced waterbender skill that allows the player to heal themselves or others from the damage they've taken. If healing another player, you must continue to look at them to channel the ability."); config.addDefault("Abilities.Water.HealingWaters.Instructions", "Hold sneak to begin healing yourself or right click while sneaking to begin healing another player. You or the player must be in water and damaged for this ability to work, or you need to have water bottles in your inventory."); config.addDefault("Abilities.Water.IceBlast.Description", "IceBlast is a powerful ability that deals damage to entities it comes into contact with. Because IceBlast's travel time is pretty quick, it's increddibly useful for finishing off low health targets."); @@ -288,14 +288,14 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.IceSpike.DeathMessage", "{victim} was impaled by {attacker}'s {ability}"); config.addDefault("Abilities.Water.OctopusForm.Description", "OctopusForm is one of the most advanced abilities in a waterbender's aresenal. It has the possibility of doing high damage to anyone it comes into contact with."); config.addDefault("Abilities.Water.OctopusForm.Instructions", "Left click a water source and then hold sneak to form a set of water tentacles. This ability will channel as long as you are holding sneak. Additionally, if you left click this ability will whip targets you're facing dealing damage and knockback, if they're in range."); - config.addDefault("Abilities.Water.OctopusForm.DeathMessage", "{victim} was slapped by {attacker}'s {ability}"); + config.addDefault("Abilities.Water.OctopusForm.DeathMessage", "{victim} was slapped to death by {attacker}'s {ability}"); config.addDefault("Abilities.Water.PhaseChange.Description", "PhaseChange is one of the most useful utility moves that a waterbender possess. This ability is better used when fighting, allowing you to create a platform on water that you can fight on and being territorial by manipulating your environment. It's also useful for travelling across seas."); config.addDefault("Abilities.Water.PhaseChange.Instructions", "\n" + "(Melt) To melt ice, hold sneak while looking at an ice block." + "\n" + "(Freeze) To freeze water and turn it into ice, simply left click at water. This ice will stay so long as you are in range, otherwise it will revert back to water. This only freezes the top layer of ice."); config.addDefault("Abilities.Water.Surge.Description", "Surge offers great utility and is one of the most important defence abilities for waterbender's. It can be used to push entities back, used to push yourself in a direction, trap entities and protect yourself with a shield."); config.addDefault("Abilities.Water.Surge.Instructions", "\n" + "(Shield) Left click on a water source and then hold sneak while looking up to create a water shield that will move wherever you look. Additionally, you can left click to turn this shield into ice. If you let go of sneak at any point, this ability will cancel." + "\n" + "(Surge) Tap sneak at a water source and click in a direction to fire a surge of water that will knock entities back. Additionally, if you tap sneak again before the surge reaches an entity, when it hits them it will encase them in ice."); config.addDefault("Abilities.Water.Torrent.Description", "Torrent is one of the strongest moves in a waterbender's arsenal. It has the potential to do immense damage and to be comboed with other abilities to perform a deal a large damage burst. Torrent is fundamental for waterbender's. "); config.addDefault("Abilities.Water.Torrent.Instructions", "\n" + "(Torrent) Left click at a water source and hold sneak to form the torrent. Then, left click and the torrent will shoot out, moving in the direction you're looking. If the torrent hits an entity, it can drag them and deal damage. Additionally, if you left click before the torrent hits a surface or entity it will freeze on impact." + "\n" + "(Wave) Left click a water source and hold sneak to form a torrent around you. Then, release sneak to send a wave of water expanding outwards every direction that will push entities back."); - config.addDefault("Abilities.Water.Torrent.DeathMessage", "{victim} was taken down by {attacker}'s {ability}"); + config.addDefault("Abilities.Water.Torrent.DeathMessage", "{victim} was washed away by {attacker}'s {ability}"); config.addDefault("Abilities.Water.WaterArms.Description", "One of the most diverse moves in a Waterbender's arsenal, this move creates tendrils " + "of water from the players arms to emulate their actual arms. It has the potential to do a variety of things that can either do mass amounts of damage, or used for mobility."); config.addDefault("Abilities.Water.WaterArms.Instructions", "To activate this ability, tap sneak at a water source. Additionally, to de-activate this ability, hold sneak and left click." + "\n" + "(Pull) Left click at a target and your arms will expand outwards, pulling entities towards you if they're in range." + "\n" + "(Punch) Left click and one arm will expand outwards, punching anyone it hits and dealing damage." + "\n" + "(Grapple) Left click to send your arms forward, pulling you to whatever surface they land on." + "\n" + "(Grab) Left click to grab an entity that's in range. They will then be controlled and moved in whatever direction you look. Additionally, if you left click again you can throw the target that you're controlling." + "\n" + "(Freeze) Left click to rapidly fire ice blasts at a target, damaging the target and giving them slowness." + "\n" + "(Spear) Left click to send an ice spear out, damaging and freezing whoever it hits in ice blocks."); config.addDefault("Abilities.Water.WaterArms.SneakMessage", "Active Ability:"); @@ -306,7 +306,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.WaterBubble.Instructions", "Hold sneak when in range of water to push the water back and create a water bubble. Alternatively, you can click to create a bubble for a short amount of time."); config.addDefault("Abilities.Water.WaterManipulation.Description", "WaterManipulation is a fundamental ability for waterbenders. Although it is a basic move, it allows for fast damage due to its rapid fire nature, which is incredibly useful when wanting to finish off low health targets."); config.addDefault("Abilities.Water.WaterManipulation.Instructions", "Tap sneak on a water source and left click to send a water manipulation to the point that you clicked. Additionally, you can left click again to change the direction of this move. This includes other players' WaterManipulations."); - config.addDefault("Abilities.Water.WaterManipulation.DeathMessage", "{victim} was taken down by {attacker}'s {ability}"); + config.addDefault("Abilities.Water.WaterManipulation.DeathMessage", "{victim} was drowned by {attacker}'s {ability}"); config.addDefault("Abilities.Water.WaterSpout.Description", "This ability provides a Waterbender with a means of transportation. It's the most useful mobility move that a waterbender possesses and is great for chasing down targets or escaping."); config.addDefault("Abilities.Water.WaterSpout.Instructions", "\n" + "(Spout) Left click to activate a spout beneath you and hold spacebar to go higher. If you wish to go lower, simply hold sneak. To disable this ability, left click once again." + "\n" + "(Wave) Left click a water source and hold sneak until water has formed around you. Then, release sneak to ride a water wave that transports you in the direction you're looking. To cancel this water wave, left click with WaterSpout."); config.addDefault("Abilities.Water.Combo.IceBullet.Description", "Using a large cavern of ice, you can punch ice shards at your opponent causing moderate damage. To rapid fire, you must alternate between Left clicking and right clicking with IceBlast."); @@ -314,9 +314,9 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.Combo.IceWave.Description", "PhaseChange your WaterWave into an IceWave that freezes and damages enemies."); config.addDefault("Abilities.Water.Combo.IceWave.DeathMessage", "{victim} was frozen solid by {attacker}'s {ability}"); config.addDefault("Abilities.Water.Passive.FastSwim.Description", "FastSwim is a passive ability for waterbenders allowing them to travel quickly through the water. Simple hold shift while underwater to propel yourself forward."); - config.addDefault("Abilities.Water.Passive.Hydrosink.Description", "Hydrosink is a passive ability for waterbenders enabling them to softly land on any waterbendable surface, cancelling all damage."); + config.addDefault("Abilities.Water.Passive.HydroSink.Description", "Hydrosink is a passive ability for waterbenders enabling them to softly land on any waterbendable surface, cancelling all damage."); - config.addDefault("Commands.Help.Elements.Earth", "Earth is the element of substance. Earthbenders share many of the same fundamental techniques as Waterbenders, but their domain is quite different and more readily accessible. Earthbenders dominate the ground and subterranean, having abilities to pull columns of rock straight up from the earth or drill their way through the mountain. They can also launch themselves through the air using pillars of rock, and will not hurt themselves assuming they land on something they can bend. The more skilled Earthbenders can even bend metal."); + config.addDefault("Commands.Help.Elements.Earth", "Earth is the element of substance. Earthbenders share many of the same fundamental techniques as Waterbenders, but their domain is quite different and more readily accessible. Earthbenders dominate the ground and subterranean, having abilities to pull columns of rock straight up from the earth or drill their way through the mountain. They can also launch themselves through the air using pillars of rock, and will not hurt themselves assuming they land on something they can bend. The more skilled Earthbenders can even bend metal, sand, and lava.\nEnter /b display Earth for a list of the available earth abilities."); config.addDefault("Abilities.Earth.Catapult.Description", "Catapult is an advanced earthbending ability that allows you to forcefully push yourself using earth, reaching great heights. This technique is best used when travelling, but it can also be used to quickly escape a battle."); config.addDefault("Abilities.Earth.Catapult.Instructions", "Hold sneak until you see particles and hear a sound and then release to be propelled in the direction you're looking. Additionally, you can left-click to be propelled with less power."); config.addDefault("Abilities.Earth.Collapse.Description", "This ability is a basic earthbending ability that allows the earthbender great utility. It allows them to control earth blocks by compressing earth. Players and mobs can be trapped and killed if earth is collapsed and they're stuck inside it, meaning this move is deadly when in cave systems."); @@ -326,16 +326,16 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Earth.EarthArmor.Instructions", "Tap sneak while looking at an earthbendable block to bring those blocks towards you, forming earth armor. This ability will give you extra hearts and will be removed once those extra hearts are gone. You can disable this ability by holding sneak and left clicking with EarthArmor."); config.addDefault("Abilities.Earth.EarthBlast.Description", "EarthBlast is a basic yet fundamental earthbending ability. It allows you to deal rapid fire damage to your target to finish low health targets off or deal burst damage to them. Although it can be used at long range, it's potential is greater in close ranged comat."); config.addDefault("Abilities.Earth.EarthBlast.Instructions", "Tap sneak at an earthbendable block and then left click in a direction to send an earthblast. Additionally, you can left click again to change the direction of the earthblast. You can also redirect other earthbender's earth blast by left clicking. If the earth blast hits an entity it will deal damage and knockback."); - config.addDefault("Abilities.Earth.EarthBlast.DeathMessage", "{victim} was broken apart by {attacker}'s {ability}"); - config.addDefault("Abilities.Earth.EarthGrab.Description", "EarthGrab is one of the best defence abilities in an earthbender's aresenal. It allows you to trap someone who is running away so that you can catch up to someone, or quickly create a dome to protect yourself from incomming attacks. Although this ability is basic, it requires fast reactions to reach its full potential."); - config.addDefault("Abilities.Earth.EarthGrab.Instructions", "\n" + "(Grab) To grab an entity, hold sneak and left click in the direction of the target. Earth will expand out and create an earth dome around the target, trapping them." + "\n" + "(Dome) To encase yourself in an earth dome, simply left click at an earthbendable block under you."); + config.addDefault("Abilities.Earth.EarthBlast.DeathMessage", "{victim} was shattered by {attacker}'s {ability}"); + config.addDefault("Abilities.Earth.EarthGrab.Description", "EarthGrab is one of the best defence abilities in an earthbender's arsenal. It allows you to trap someone who is running away so that you can catch up to someone. It is also of great utility use to an earthbender. It can be used to drag items, arrows, and crops that are on earthbendable blocks towards you, saving you the time of running to get them."); + config.addDefault("Abilities.Earth.EarthGrab.Instructions", "\n" + "(Grab) To grab an entity, left click in the direction of the target. Your power will be sent through the earth, and then it will reach up and root them in their spot upon contact. The ability can be manually be disabled by sneaking or clicking again on the EarthGrab slot." + "\n" + "(Drag) To drag items towards you, sneak" + "\n(Escaping) To escape, the trap must be destroyed or the user damaged. The trap can be destroyed by damage or the trapped entity right-clicking it a certain number of times. Additionally, forcefully moving the entity with another earth ability destroys the trap."); config.addDefault("Abilities.Earth.EarthTunnel.Description", "Earth Tunnel is a completely utility ability for earthbenders. It allows you to dig a hole that lowers players down while you continue the ability, create fast escape routes or just great for making your own cave systems."); config.addDefault("Abilities.Earth.EarthTunnel.Instructions", "Hold sneak while looking at an earthbendable block to tunnel the blocks away. If you release sneak or look at a block that isn't earthbendable, the ability will cancel."); config.addDefault("Abilities.Earth.Extraction.Description", "This ability allows metalbenders to extract the minerals from ore blocks. This ability is extremely useful for gathering materials as it has a chance to extract double or tripple the ores."); config.addDefault("Abilities.Earth.Extraction.Instructions", "Tap sneak while looking at an earthbendable ore to extract the ore."); config.addDefault("Abilities.Earth.LavaFlow.Description", "LavaFlow is an extremely advanced, and dangerous ability. It allows the earthbender to create pools of lava around them, or to solidify existing lava. This ability can be deadly when comboed with EarthGrab."); config.addDefault("Abilities.Earth.LavaFlow.Instructions", "\n" + "(Flow) Hold sneak and lava will begin expanding outwards. Once the lava has stopped expanding, you can release sneak. Additionally, if you tap sneak the lava you created will revert back to the earthbendable block." + "\n" + "(Lava Pool) Left click to slowly transform earthbendable blocks into a pool of lava." + "\n" + "(Solidify) Left click on lava to solidify it, turning it to stone."); - config.addDefault("Abilities.Earth.LavaFlow.DeathMessage", "{victim} was caught in by {attacker}'s {ability}"); + config.addDefault("Abilities.Earth.LavaFlow.DeathMessage", "{victim} was caught by {attacker}'s {ability}"); config.addDefault("Abilities.Earth.EarthSmash.Description", "EarthSmash is an advanced earthbending technique that has lots of utility. It can be comboed with abilities such as Shockwave, but also be used for mobility and to produce high damage. EarthSmash is great for escaping when at low health."); config.addDefault("Abilities.Earth.EarthSmash.Instructions", "\n" + "(Smash) Hold sneak until particles appear, then release sneak while looking at an earthbendable block which will raise an earth boulder. Then, hold sneak while looking at this boulder to control it. Left click to send the bounder in the direction you're facing, damanging entities and knocking them back." + "\n" + "(Ride) After you have created an earth boulder, hold sneak and right click on the boulder to ride it. You will now ride the boulder in whatever direction you look. Additionally, you can ride the boulder by going on top of it and holding sneak. If you come into contact with an entity while riding the boulder, it will drag them along with you. If you left go of sneak, the ability will cancel."); config.addDefault("Abilities.Earth.EarthSmash.DeathMessage", "{victim} was crushed by {attacker}'s {ability}"); @@ -349,13 +349,15 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Earth.Shockwave.DeathMessage", "{victim} was blown away by {attacker}'s {ability}"); config.addDefault("Abilities.Earth.Tremorsense.Description", "This is a pure utility ability for earthbenders. If you are in an area of low-light and are standing on top of an earthbendable block, this ability will automatically turn that block into glowstone, visible *only by you*. If you lose contact with a bendable block, the light will go out as you have lost contact with the earth and cannot 'see' until you can touch earth again. Additionally, if you click with this ability selected, smoke will appear above nearby earth with pockets of air beneath them."); config.addDefault("Abilities.Earth.Tremorsense.Instructions", "Simply left click while on an earthbendable block."); + config.addDefault("Abilities.Earth.Combo.EarthDome.Description", "EarthDome allows earthbenders to surround themselves or another entity in earth, temporarily preventing anything from entering or escaping the dome."); + config.addDefault("Abilities.Earth.Combo.EarthPillars.Description", "Send players and entities flying into the air and possibly stunning them by raising pillars of earth under their feet, dealing damage initally as well. This combo can also be used by falling from high off the ground and landing while on the Catapult ability"); config.addDefault("Abilities.Earth.Passive.DensityShift.Description", "DensityShift is a passive ability which allows earthbenders to make a firm landing negating all fall damage on any earthbendable surface."); config.addDefault("Abilities.Earth.Passive.FerroControl.Description", "FerroControl is a passive ability which allows metalbenders to simply open and close iron doors by sneaking."); - config.addDefault("Commands.Help.Elements.Fire", "Fire is the element of power. Firebenders focus on destruction and incineration. Their abilities are pretty straight forward: set things on fire. They do have a bit of utility however, being able to make themselves un-ignitable, extinguish large areas, cook food in their hands, extinguish large areas, small bursts of flight, and then comes the abilities to shoot fire from your hands.\nFirebenders can chain their abilities into combos, type /b help FireCombos for more information."); + config.addDefault("Commands.Help.Elements.Fire", "Fire is the element of power. Firebenders focus on destruction and incineration. Their abilities are pretty straight forward: set things on fire. They do have a bit of utility however, being able to make themselves un-ignitable, extinguish large areas, cook food in their hands, extinguish large areas, small bursts of flight, and then comes the abilities to shoot fire from your hands.\nEnter /b display Fire for a list of the available fire abilities."); config.addDefault("Abilities.Fire.Blaze.Description", "Blaze is a basic firebending technique that can be extremely deadly if used right. It's useful to stop people from chasing you or to create space between you and other players.."); config.addDefault("Abilities.Fire.Blaze.Instructions", "Left click to send an arc of fire in the direction you're facing that will burn entities in its path. Additionally, you can tap sneak to send a blaze all around you."); - config.addDefault("Abilities.Fire.Blaze.DeathMessage", "{victim} was burned alive by {attacker}'s {ability}"); + config.addDefault("Abilities.Fire.Blaze.DeathMessage", "{victim} was incinerated by {attacker}'s {ability}"); config.addDefault("Abilities.Fire.Combustion.Description", "Combustion is a special firebending technique that's extremely deadly. It allows you to create a powerful blast to deal immense damage to players at long range."); config.addDefault("Abilities.Fire.Combustion.Instructions", "Tap sneak to send a combustion out in the direction you're looking. It will explode on impact, or you can left click to manually expload it. This deals damage to players who are in radius of the blast."); config.addDefault("Abilities.Fire.Combustion.DeathMessage", "{victim} was shot down by {attacker}'s {ability}"); @@ -369,10 +371,10 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.FireJet.Instructions", "Left click to propel yourself in the direction you're looking. Additionally, left click while flying to cancel the jet."); config.addDefault("Abilities.Fire.FireShield.Description", "FireShield is a basic defensive ability that allows a firebender to block projectiles or other bending abilities. It's useful while fighting off skeletons, or while trying to block bending abilities at low health."); config.addDefault("Abilities.Fire.FireShield.Instructions", "Hold sneak to create a fire shield around you that will block projectiles and other bending abilities. Additionally, left click to create a temporary fire shield. If entities step inside this fire shield, they will be ignited."); - config.addDefault("Abilities.Fire.FireShield.DeathMessage", "{victim} scorched theirself on {attacker}'s {ability}"); + config.addDefault("Abilities.Fire.FireShield.DeathMessage", "{victim} scorched themselves on {attacker}'s {ability}"); config.addDefault("Abilities.Fire.FireManipulation.Description", "FireManipulation is an extremely advanced and unique Firebending technique that allows the bender to create fire and manipulate it to block incoming attacks. You can also manipulate the fire you create to be used as an offence ability."); config.addDefault("Abilities.Fire.FireManipulation.Instructions", "Stream: Hold sneak and move your cursor around to create a fire where you look, blocking incoming attacks. Once you've created enough fire, left click to send the fire stream outwards, damaging anything it comes into contact with."); - config.addDefault("Abilities.Fire.FireManipulation.DeathMessage", "{victim} scorched theirself on {attacker}'s {ability}"); + config.addDefault("Abilities.Fire.FireManipulation.DeathMessage", "{victim} scorched themselves on {attacker}'s {ability}"); config.addDefault("Abilities.Fire.HeatControl.Description", "HeatControl is a fundamental firebending technique that allows the firebender to control and manipulate heat. This ability is extremely useful for ensuring that you're protected from your own fire and fire from that of other firebenders. It's also offers utility by melting ice or cooking food."); config.addDefault("Abilities.Fire.HeatControl.Instructions", "\n" + "(Melt) To melt ice, simply left click while looking at ice." + "\n" + "(Solidify) To solidify lava, hold sneak while looking at lava while standing still and it will start to solidify the lava pool you're looking at." + "\n" + "(Extinguish) To extinguish nearby fire or yourself, simply tap sneak." + "\n" + "(Cook) To cook food, place the raw food on your HeatControl slot and hold sneak. The food will then begin to cook."); config.addDefault("Abilities.Fire.Illumination.Description", "Illumination is a basic firebending technique that allows firebenders to manipulate their fire to create a light source. This ability will automatically activate when you're in low light."); @@ -384,29 +386,29 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.WallOfFire.Instructions", "Left click to create a fire wall at the location you clicked. This fire wall will damage entities that run into it and deal knockback."); config.addDefault("Abilities.Fire.WallOfFire.DeathMessage", "{victim} ran into {attacker}'s {ability}"); config.addDefault("Abilities.Fire.Combo.FireKick.Description", "A short ranged arc of fire launches from the player's feet dealing moderate damage to enemies."); - config.addDefault("Abilities.Fire.Combo.FireKick.DeathMessage", "{victim} was kicked to the floor with flames by {attacker}'s {ability}"); + config.addDefault("Abilities.Fire.Combo.FireKick.DeathMessage", "{victim} was kicked to the floor, in flames, from {attacker}'s {ability}"); config.addDefault("Abilities.Fire.Combo.FireSpin.Description", "A circular array of fire that causes damage and massive knockback to nearby enemies."); config.addDefault("Abilities.Fire.Combo.FireSpin.DeathMessage", "{victim} was caught in {attacker}'s {ability} inferno"); config.addDefault("Abilities.Fire.Combo.JetBlaze.Description", "Damages and burns all enemies in the proximity of your FireJet."); - config.addDefault("Abilities.Fire.Combo.JetBlaze.DeathMessage", "{victim} was blasted away by {attacker}'s {ability}"); + config.addDefault("Abilities.Fire.Combo.JetBlaze.DeathMessage", "{victim} was lit ablaze by {attacker}'s {ability}"); config.addDefault("Abilities.Fire.Combo.JetBlast.Description", "Create an explosive blast that propels your FireJet at higher speeds."); config.addDefault("Abilities.Fire.Combo.FireWheel.Description", "A high-speed wheel of fire that travels along the ground for long distances dealing high damage."); config.addDefault("Abilities.Fire.Combo.FireWheel.DeathMessage", "{victim} was incinerated by {attacker}'s {ability}"); - config.addDefault("Commands.Help.Elements.Chi", "Chiblockers focus on bare handed combat, utilizing their agility and speed to stop any bender right in their path. Although they lack the ability to bend any of the other elements, they are great in combat, and a serious threat to any bender. Chiblocking was first shown to be used by Ty Lee in Avatar: The Last Airbender, then later by members of the Equalists in The Legend of Korra.\nChiblockers can chain their abilities into combos, type /b help ChiCombos for more information."); + config.addDefault("Commands.Help.Elements.Chi", "Chiblockers focus on bare handed combat, utilizing their agility and speed to stop any bender right in their path. Although they lack the ability to bend any of the other elements, they are great in combat, and a serious threat to any bender. Chiblocking was first shown to be used by Ty Lee in Avatar: The Last Airbender, then later by members of the Equalists in The Legend of Korra.\nEnter /b display Chi for a list of the available chi abilities."); config.addDefault("Abilities.Chi.AcrobatStance.Description", "AcrobatStance gives a Chiblocker a higher probability of blocking a Bender's Chi while granting them a Speed and Jump Boost. It also increases the rate at which the hunger bar depletes."); - config.addDefault("Abilities.Chi.AcrobatStance.Instructions", "To use, simply left click to activate this stance. Left click once more to deactivate it."); + config.addDefault("Abilities.Chi.AcrobatStance.Instructions", "To use, simply left click to activate this stance. Left click once more to deactivate it."); config.addDefault("Abilities.Chi.HighJump.Description", "HighJump gives the Chiblocker the ability to leap into the air. This ability is used for mobility, and is often used to dodge incoming attacks."); config.addDefault("Abilities.Chi.HighJump.Instructions", "To use, simply left click while standing on the ground."); config.addDefault("Abilities.Chi.Smokescreen.Description", "Smokescreen, if used correctly, can serve as a defensive and offensive ability for Chiblockers. When used, a smoke bomb is fired which will blind anyone within a small radius of the explosion, allowing you to either get away, or move in for the kill."); - config.addDefault("Abiltiies.Chi.Smokescreen.Instructions", "Left click and a smoke bomb will be fired in the direction you're looking."); + config.addDefault("Abilities.Chi.Smokescreen.Instructions", "Left click and a smoke bomb will be fired in the direction you're looking."); config.addDefault("Abilities.Chi.WarriorStance.Description", "WariorStance is an advanced chiblocker technique that gives the chiblocker increased damage but makes them a tad more vulnerable. This ability is useful when finishing off weak targets."); config.addDefault("Abilities.Chi.WarriorStance.Instructions", "Left click to activate the warrior stance mode. Additionally, left click to disable it."); config.addDefault("Abilities.Chi.Paralyze.Description", "Paralyzes the target, making them unable to do anything for a short period of time as they will be paralyzed where they're stood. "); config.addDefault("Abilities.Chi.Paralyze.Instructions", "Punch a player to paralyze them."); config.addDefault("Abilities.Chi.RapidPunch.Description", "This ability allows the chiblocker to punch rapidly in a short period. To use, simply punch. This has a short cooldown."); config.addDefault("Abilities.Chi.RapidPunch.Instructions", "Punch a player to deal massive damage."); - config.addDefault("Abilities.Chi.RapidPunch.DeathMessage", "{victim} took all the hits against {attacker}'s {ability}"); + config.addDefault("Abilities.Chi.RapidPunch.DeathMessage", "{victim} took all the hits from {attacker}'s {ability}"); config.addDefault("Abilities.Chi.QuickStrike.Description", "QuickStrike enables a chiblocker to quickly strike an enemy, potentially blocking their chi."); config.addDefault("Abilities.Chi.QuickStrike.Instructions", "Left click on a player to quick strike them."); config.addDefault("Abilities.Chi.QuickStrike.DeathMessage", "{victim} was struck down by {attacker}'s {ability}"); @@ -418,11 +420,13 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Chi.Passive.ChiSaturation.Description", "ChiSaturation is a passive ability which causes chiblockers' hunger to deplete at a slower rate."); config.addDefault("Abilities.Chi.Passive.Acrobatics.Description", "Acrobatics is a passive ability which negates all fall damage based on a percent chance."); + config.addDefault("Commands.Help.Elements.Avatar", "Avatars are the human embodiment of light and peace created through a connection with the Avatar Spirit. It is considered an Avatar's duty to master the four elements and use that power to keep balance among the four nations as well as act as the bridge between the physical and spiritual worlds.\nEnter /b display Avatar for a list of the available avatar abilities."); + languageConfig.save(); } else if (type == ConfigType.DEFAULT) { config = defaultConfig.get(); - ArrayList earthBlocks = new ArrayList(); + final ArrayList earthBlocks = new ArrayList(); earthBlocks.add("DIRT"); earthBlocks.add("MYCEL"); earthBlocks.add("GRASS"); @@ -430,18 +434,15 @@ public static void configCheck(ConfigType type) { earthBlocks.add("GRAVEL"); earthBlocks.add("CLAY"); earthBlocks.add("COAL_ORE"); - earthBlocks.add("IRON_ORE"); - earthBlocks.add("GOLD_ORE"); earthBlocks.add("REDSTONE_ORE"); earthBlocks.add("LAPIS_ORE"); earthBlocks.add("DIAMOND_ORE"); earthBlocks.add("NETHERRACK"); - earthBlocks.add("QUARTZ_ORE"); earthBlocks.add("COBBLESTONE"); earthBlocks.add("STEP"); earthBlocks.add("GRASS_PATH"); - ArrayList metalBlocks = new ArrayList(); + final ArrayList metalBlocks = new ArrayList(); metalBlocks.add("IRON_ORE"); metalBlocks.add("GOLD_ORE"); metalBlocks.add("QUARTZ_ORE"); @@ -449,17 +450,17 @@ public static void configCheck(ConfigType type) { metalBlocks.add("GOLD_BLOCK"); metalBlocks.add("QUARTZ_BLOCK"); - ArrayList sandBlocks = new ArrayList(); + final ArrayList sandBlocks = new ArrayList(); sandBlocks.add("SAND"); sandBlocks.add("SANDSTONE"); sandBlocks.add("RED_SAND"); sandBlocks.add("RED_SANDSTONE"); - ArrayList iceBlocks = new ArrayList(); + final ArrayList iceBlocks = new ArrayList(); iceBlocks.add("ICE"); iceBlocks.add("PACKED_ICE"); - ArrayList plantBlocks = new ArrayList(); + final ArrayList plantBlocks = new ArrayList(); plantBlocks.add("SAPLING"); plantBlocks.add("LEAVES"); plantBlocks.add("LEAVES_2"); @@ -482,11 +483,12 @@ public static void configCheck(ConfigType type) { plantBlocks.add("PUMPKIN_STEM"); plantBlocks.add("MELON_STEM"); - ArrayList snowBlocks = new ArrayList<>(); + final ArrayList snowBlocks = new ArrayList<>(); snowBlocks.add("SNOW"); + config.addDefault("Properties.UpdateChecker", true); + config.addDefault("Properties.Statistics", true); config.addDefault("Properties.BendingPreview", true); - config.addDefault("Properties.ImportEnabled", true); config.addDefault("Properties.BendingAffectFallingSand.Normal", true); config.addDefault("Properties.BendingAffectFallingSand.NormalStrengthMultiplier", 1.0); config.addDefault("Properties.BendingAffectFallingSand.TNT", true); @@ -494,6 +496,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Properties.GlobalCooldown", 500); config.addDefault("Properties.TogglePassivesWithAllBending", true); config.addDefault("Properties.SeaLevel", 62); + config.addDefault("Properties.ChooseCooldown", 0L); config.addDefault("Properties.HorizontalCollisionPhysics.Enabled", true); config.addDefault("Properties.HorizontalCollisionPhysics.DamageOnBarrierBlock", false); @@ -519,6 +522,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Properties.Air.Sound.Volume", 1); config.addDefault("Properties.Air.Sound.Pitch", 2); + config.addDefault("Properties.Water.DynamicSourcing", true); config.addDefault("Properties.Water.CanBendWithWeapons", true); config.addDefault("Properties.Water.IceBlocks", iceBlocks); config.addDefault("Properties.Water.PlantBlocks", plantBlocks); @@ -536,6 +540,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Properties.Water.IceSound.Volume", 1); config.addDefault("Properties.Water.IceSound.Pitch", 1); + config.addDefault("Properties.Earth.DynamicSourcing", true); config.addDefault("Properties.Earth.RevertEarthbending", true); config.addDefault("Properties.Earth.SafeRevert", true); config.addDefault("Properties.Earth.RevertCheckTime", 300000); @@ -572,10 +577,10 @@ public static void configCheck(ConfigType type) { config.addDefault("Properties.Fire.LightningSound.Sound", "ENTITY_CREEPER_HURT"); config.addDefault("Properties.Fire.LightningSound.Volume", 1); config.addDefault("Properties.Fire.LightningSound.Pitch", 0); - + config.addDefault("Properties.Chi.CanBendWithWeapons", true); - ArrayList disabledWorlds = new ArrayList(); + final ArrayList disabledWorlds = new ArrayList(); disabledWorlds.add("TestWorld"); disabledWorlds.add("TestWorld2"); config.addDefault("Properties.DisabledWorlds", disabledWorlds); @@ -604,6 +609,8 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Avatar.AvatarState.Air.AirSwipe.Cooldown", 1000); config.addDefault("Abilities.Avatar.AvatarState.Air.AirSwipe.Damage", 4.5); config.addDefault("Abilities.Avatar.AvatarState.Air.AirSwipe.Push", 1.0); + config.addDefault("Abilities.Avatar.AvatarState.Air.AirSwipe.Range", 24); + config.addDefault("Abilities.Avatar.AvatarState.Air.AirSwipe.Radius", 3); config.addDefault("Abilities.Avatar.AvatarState.Air.AirBurst.ChargeTime", 1000); config.addDefault("Abilities.Avatar.AvatarState.Air.AirBurst.Damage", 3); config.addDefault("Abilities.Avatar.AvatarState.Air.AirShield.IsAvatarStateToggle", true); @@ -613,7 +620,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Avatar.AvatarState.Air.Suffocate.Range", 16); config.addDefault("Abilities.Avatar.AvatarState.Air.AirStream.Range", 60); config.addDefault("Abilities.Avatar.AvatarState.Air.AirStream.EntityHeight", 21); - config.addDefault("Abilities.Avatar.AvatarState.Air.AirStream.EntityDuration", 6000); + config.addDefault("Abilities.Avatar.AvatarState.Air.AirStream.EntityDuration", 20000); config.addDefault("Abilities.Avatar.AvatarState.Air.AirSweep.Damage", 6); config.addDefault("Abilities.Avatar.AvatarState.Air.AirSweep.Range", 21); config.addDefault("Abilities.Avatar.AvatarState.Air.AirSweep.Knockback", 4); @@ -675,11 +682,10 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Avatar.AvatarState.Fire.FireSpin.Range", 9); config.addDefault("Abilities.Avatar.AvatarState.Fire.FireSpin.Knockback", 3); config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Damage", 5); - config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Range", 13); + config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Range", 35); config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Height", 3); config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Speed", 0.75); config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.FireTicks", 4); - config.addDefault("Abilities.Avatar.AvatarState.Fire.FireWheel.Radius", 1.5); config.addDefault("Abilities.Avatar.AvatarState.Fire.WallOfFire.Height", 6); config.addDefault("Abilities.Avatar.AvatarState.Fire.WallOfFire.Width", 6); config.addDefault("Abilities.Avatar.AvatarState.Fire.WallOfFire.Duration", 8000); @@ -747,6 +753,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.AirBurst.PushFactor", 1.5); config.addDefault("Abilities.Air.AirBurst.ChargeTime", 1750); config.addDefault("Abilities.Air.AirBurst.Damage", 0); + config.addDefault("Abilities.Air.AirBurst.Cooldown", 0); config.addDefault("Abilities.Air.AirBurst.SneakParticles", 10); config.addDefault("Abilities.Air.AirBurst.ParticlePercentage", 50); config.addDefault("Abilities.Air.AirBurst.AnglePhi", 10); @@ -757,10 +764,12 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.AirScooter.Interval", 100); config.addDefault("Abilities.Air.AirScooter.Radius", 1); config.addDefault("Abilities.Air.AirScooter.Cooldown", 7000); + config.addDefault("Abilities.Air.AirScooter.Duration", 0); config.addDefault("Abilities.Air.AirScooter.MaxHeightFromGround", 7); config.addDefault("Abilities.Air.AirShield.Enabled", true); config.addDefault("Abilities.Air.AirShield.Cooldown", 0); + config.addDefault("Abilities.Air.AirShield.Duration", 0); config.addDefault("Abilities.Air.AirShield.Radius", 7); config.addDefault("Abilities.Air.AirShield.Streams", 5); config.addDefault("Abilities.Air.AirShield.Speed", 10); @@ -768,6 +777,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.AirSpout.Enabled", true); config.addDefault("Abilities.Air.AirSpout.Cooldown", 0); + config.addDefault("Abilities.Air.AirSpout.Duration", 0); config.addDefault("Abilities.Air.AirSpout.Height", 16); config.addDefault("Abilities.Air.AirSpout.Interval", 100); @@ -795,11 +805,9 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.AirSwipe.StepSize", 4); config.addDefault("Abilities.Air.Flight.Enabled", true); - config.addDefault("Abilities.Air.Flight.HoverEnabled", true); - config.addDefault("Abilities.Air.Flight.Cooldown", 5000); - config.addDefault("Abilities.Air.Flight.Speed", 1); - config.addDefault("Abilities.Air.Flight.MaxHits", 4); - config.addDefault("Abilities.Air.Flight.MaxDuration", 0); + config.addDefault("Abilities.Air.Flight.Cooldown", 0); + config.addDefault("Abilities.Air.Flight.BaseSpeed", 1.2); + config.addDefault("Abilities.Air.Flight.Duration", 0); config.addDefault("Abilities.Air.Suffocate.Enabled", true); config.addDefault("Abilities.Air.Suffocate.ChargeTime", 500); @@ -823,6 +831,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.Tornado.Enabled", true); config.addDefault("Abilities.Air.Tornado.Cooldown", 0); + config.addDefault("Abilities.Air.Tornado.Duration", 0); config.addDefault("Abilities.Air.Tornado.Radius", 10); config.addDefault("Abilities.Air.Tornado.Height", 20); config.addDefault("Abilities.Air.Tornado.Range", 25); @@ -839,14 +848,14 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Air.Twister.Cooldown", 10000); config.addDefault("Abilities.Air.Twister.DegreesPerParticle", 7); config.addDefault("Abilities.Air.Twister.HeightPerParticle", 1.25); - + config.addDefault("Abilities.Air.AirStream.Enabled", true); config.addDefault("Abilities.Air.AirStream.Speed", 0.5); config.addDefault("Abilities.Air.AirStream.Range", 40); config.addDefault("Abilities.Air.AirStream.EntityDuration", 4000); config.addDefault("Abilities.Air.AirStream.EntityHeight", 14); config.addDefault("Abilities.Air.AirStream.Cooldown", 7000); - + config.addDefault("Abilities.Air.AirSweep.Enabled", true); config.addDefault("Abilities.Air.AirSweep.Speed", 1.4); config.addDefault("Abilities.Air.AirSweep.Range", 14); @@ -856,6 +865,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.Passive.FastSwim.Enabled", true); config.addDefault("Abilities.Water.Passive.FastSwim.Cooldown", 0); + config.addDefault("Abilities.Water.Passive.FastSwim.Duration", 0); config.addDefault("Abilities.Water.Passive.FastSwim.SpeedFactor", 0.7); config.addDefault("Abilities.Water.Passive.Hydrosink.Enabled", true); @@ -875,7 +885,8 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.HealingWaters.Interval", 750); config.addDefault("Abilities.Water.HealingWaters.ChargeTime", 1000); config.addDefault("Abilities.Water.HealingWaters.Power", 1); - config.addDefault("Abilities.Water.HealingWaters.Duration", 70); + config.addDefault("Abilities.Water.HealingWaters.HealingDuration", 70); + config.addDefault("Abilities.Water.HealingWaters.Duration", 0); config.addDefault("Abilities.Water.HealingWaters.EnableParticles", true); config.addDefault("Abilities.Water.IceBlast.Enabled", true); @@ -918,6 +929,8 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.OctopusForm.Knockback", 1.75); config.addDefault("Abilities.Water.OctopusForm.FormDelay", 40); config.addDefault("Abilities.Water.OctopusForm.Cooldown", 0); + config.addDefault("Abilities.Water.OctopusForm.Duration", 0); + config.addDefault("Abilities.Water.OctopusForm.UsageCooldown", 0); config.addDefault("Abilities.Water.OctopusForm.AngleIncrement", 45); config.addDefault("Abilities.Water.PhaseChange.Enabled", true); @@ -943,6 +956,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.Surge.Wall.Range", 5); config.addDefault("Abilities.Water.Surge.Wall.Radius", 2); config.addDefault("Abilities.Water.Surge.Wall.Cooldown", 0); + config.addDefault("Abilities.Water.Surge.Wall.Duration", 0); config.addDefault("Abilities.Water.Surge.Wall.Interval", 30); config.addDefault("Abilities.Water.Surge.Wave.IceRevertTime", 60000); @@ -985,9 +999,14 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.WaterArms.Arms.Lightning.Damage", Double.valueOf(10.0)); config.addDefault("Abilities.Water.WaterArms.Arms.Lightning.KillUser", false); - config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldownEnabled", false); - config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown", 200); - + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Enabled", false); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Pull", 200); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Punch", 200); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Grapple", 200); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Grab", 200); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Freeze", 200); + config.addDefault("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Spear", 200); + config.addDefault("Abilities.Water.WaterArms.Whip.MaxLength", 12); config.addDefault("Abilities.Water.WaterArms.Whip.MaxLengthWeak", 8); @@ -997,7 +1016,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.WaterArms.Whip.Pull.Multiplier", 0.15); config.addDefault("Abilities.Water.WaterArms.Whip.Punch.PunchDamage", 0.5); - config.addDefault("Abilities.Water.WaterArms.Whip.Punch.MaxLength", 6); + config.addDefault("Abilities.Water.WaterArms.Whip.Punch.MaxLength", 8); config.addDefault("Abilities.Water.WaterArms.Whip.Punch.NightAugments.MaxLength.Normal", 11); config.addDefault("Abilities.Water.WaterArms.Whip.Punch.NightAugments.MaxLength.FullMoon", 13); @@ -1029,7 +1048,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.WaterBubble.Speed", 0.5); config.addDefault("Abilities.Water.WaterBubble.ClickDuration", 2000L); config.addDefault("Abilities.Water.WaterBubble.MustStartAboveWater", false); - + config.addDefault("Abilities.Water.WaterManipulation.Enabled", true); config.addDefault("Abilities.Water.WaterManipulation.Damage", 3.0); config.addDefault("Abilities.Water.WaterManipulation.Range", 25); @@ -1042,6 +1061,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.WaterSpout.Enabled", true); config.addDefault("Abilities.Water.WaterSpout.Cooldown", 0); + config.addDefault("Abilities.Water.WaterSpout.Duration", 0); config.addDefault("Abilities.Water.WaterSpout.Height", 16); config.addDefault("Abilities.Water.WaterSpout.Interval", 50); config.addDefault("Abilities.Water.WaterSpout.BlockSpiral", true); @@ -1064,7 +1084,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Water.IceWave.ThawRadius", 10); config.addDefault("Abilities.Water.IceWave.RevertSphere", true); config.addDefault("Abilities.Water.IceWave.RevertSphereTime", 30000L); - + config.addDefault("Abilities.Water.IceBullet.Enabled", true); config.addDefault("Abilities.Water.IceBullet.Damage", 2); config.addDefault("Abilities.Water.IceBullet.Radius", 2.5); @@ -1111,11 +1131,20 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Earth.EarthBlast.DeflectRange", 3); config.addDefault("Abilities.Earth.EarthBlast.CollisionRadius", 1.5); + config.addDefault("Abilities.Earth.EarthDome.Enabled", true); + config.addDefault("Abilities.Earth.EarthDome.Cooldown", 10000); + config.addDefault("Abilities.Earth.EarthDome.Radius", 2); + config.addDefault("Abilities.Earth.EarthDome.Range", 14); + config.addDefault("Abilities.Earth.EarthDome.Height", 3); + config.addDefault("Abilities.Earth.EarthGrab.Enabled", true); - config.addDefault("Abilities.Earth.EarthGrab.SelectRange", 20); - config.addDefault("Abilities.Earth.EarthGrab.Height", 4); - config.addDefault("Abilities.Earth.EarthGrab.Cooldown", 2000); - config.addDefault("Abilities.Earth.EarthGrab.Radius", 4); + config.addDefault("Abilities.Earth.EarthGrab.SelectRange", 7); + config.addDefault("Abilities.Earth.EarthGrab.DragSpeed", 0.8); + config.addDefault("Abilities.Earth.EarthGrab.Cooldown", 5000); + config.addDefault("Abilities.Earth.EarthGrab.Range", 14); + config.addDefault("Abilities.Earth.EarthGrab.TrapHitInterval", 400); + config.addDefault("Abilities.Earth.EarthGrab.TrapHP", 3); + config.addDefault("Abilities.Earth.EarthGrab.DamageThreshold", 4); config.addDefault("Abilities.Earth.EarthTunnel.Enabled", true); config.addDefault("Abilities.Earth.EarthTunnel.Cooldown", 0); @@ -1213,6 +1242,15 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Earth.Tremorsense.Radius", 5); config.addDefault("Abilities.Earth.Tremorsense.LightThreshold", 7); config.addDefault("Abilities.Earth.Tremorsense.Cooldown", 1000); + config.addDefault("Abilities.Earth.Tremorsense.StickyRange", 3); + + config.addDefault("Abilities.Earth.EarthPillars.Enabled", true); + config.addDefault("Abilities.Earth.EarthPillars.Cooldown", 8000); + config.addDefault("Abilities.Earth.EarthPillars.Radius", 9); + config.addDefault("Abilities.Earth.EarthPillars.Power", 1.2); + config.addDefault("Abilities.Earth.EarthPillars.Damage.Enabled", true); + config.addDefault("Abilities.Earth.EarthPillars.Damage.Value", 2); + config.addDefault("Abilities.Earth.EarthPillars.FallThreshold", 12); config.addDefault("Abilities.Fire.Blaze.Enabled", true); config.addDefault("Abilities.Fire.Blaze.Arc", 14); @@ -1267,12 +1305,14 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.FireJet.Duration", 2000); config.addDefault("Abilities.Fire.FireJet.Cooldown", 7000); + config.addDefault("Abilities.Fire.FireManipulation.Enabled", false); + config.addDefault("Abilities.Fire.FireManipulation.Stream.Cooldown", 12000); config.addDefault("Abilities.Fire.FireManipulation.Stream.Range", 50); config.addDefault("Abilities.Fire.FireManipulation.Stream.Damage", 2); config.addDefault("Abilities.Fire.FireManipulation.Stream.Speed", 0.75); config.addDefault("Abilities.Fire.FireManipulation.Stream.Particles", 50); - + config.addDefault("Abilities.Fire.FireManipulation.Shield.Cooldown", 6000); config.addDefault("Abilities.Fire.FireManipulation.Shield.Range", 4); config.addDefault("Abilities.Fire.FireManipulation.Shield.Damage", 1); @@ -1280,10 +1320,12 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.FireManipulation.Shield.Particles", 12); config.addDefault("Abilities.Fire.FireShield.Enabled", true); - config.addDefault("Abilities.Fire.FireShield.Radius", 3); - config.addDefault("Abilities.Fire.FireShield.DiscRadius", 1.5); - config.addDefault("Abilities.Fire.FireShield.Duration", 1000); - config.addDefault("Abilities.Fire.FireShield.Cooldown", 500); + config.addDefault("Abilities.Fire.FireShield.Shield.Radius", 3); + config.addDefault("Abilities.Fire.FireShield.Shield.Duration", 0); + config.addDefault("Abilities.Fire.FireShield.Shield.Cooldown", 0); + config.addDefault("Abilities.Fire.FireShield.Disc.Radius", 1.5); + config.addDefault("Abilities.Fire.FireShield.Disc.Duration", 1000); + config.addDefault("Abilities.Fire.FireShield.Disc.Cooldown", 500); config.addDefault("Abilities.Fire.FireShield.Interval", 100); config.addDefault("Abilities.Fire.FireShield.FireTicks", 2); @@ -1339,14 +1381,14 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.FireKick.Damage", 3.0); config.addDefault("Abilities.Fire.FireKick.Cooldown", 6000); config.addDefault("Abilities.Fire.FireKick.Speed", 1); - + config.addDefault("Abilities.Fire.FireSpin.Enabled", true); config.addDefault("Abilities.Fire.FireSpin.Range", 7); config.addDefault("Abilities.Fire.FireSpin.Damage", 3.0); config.addDefault("Abilities.Fire.FireSpin.Knockback", 3.0); config.addDefault("Abilities.Fire.FireSpin.Cooldown", 5000); config.addDefault("Abilities.Fire.FireSpin.Speed", 0.3); - + config.addDefault("Abilities.Fire.FireWheel.Enabled", true); config.addDefault("Abilities.Fire.FireWheel.Range", 20.0); config.addDefault("Abilities.Fire.FireWheel.Damage", 4.0); @@ -1354,13 +1396,12 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Fire.FireWheel.Cooldown", 6000); config.addDefault("Abilities.Fire.FireWheel.FireTicks", 2.5); config.addDefault("Abilities.Fire.FireWheel.Height", 2); - config.addDefault("Abilities.Fire.FireWheel.Radius", 1.0); - + config.addDefault("Abilities.Fire.JetBlast.Enabled", true); config.addDefault("Abilities.Fire.JetBlast.Speed", 1.2); config.addDefault("Abilities.Fire.JetBlast.Cooldown", 6000); config.addDefault("Abilities.Fire.JetBlast.Duration", 5000); - + config.addDefault("Abilities.Fire.JetBlaze.Enabled", true); config.addDefault("Abilities.Fire.JetBlaze.Speed", 1.1); config.addDefault("Abilities.Fire.JetBlaze.Damage", 4); @@ -1411,7 +1452,7 @@ public static void configCheck(ConfigType type) { config.addDefault("Abilities.Chi.WarriorStance.Enabled", true); config.addDefault("Abilities.Chi.WarriorStance.Cooldown", 0); config.addDefault("Abilities.Chi.WarriorStance.Strength", 1); - config.addDefault("Abilities.Chi.WarriorStance.Resistance", -1); + config.addDefault("Abilities.Chi.WarriorStance.Resistance", -3); config.addDefault("Abilities.Chi.QuickStrike.Enabled", true); config.addDefault("Abilities.Chi.QuickStrike.Damage", 2); @@ -1440,4 +1481,4 @@ public static void configCheck(ConfigType type) { public static FileConfiguration getConfig() { return ConfigManager.defaultConfig.get(); } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/configuration/ConfigType.java b/src/com/projectkorra/projectkorra/configuration/ConfigType.java index 4f54a8726..c807bcd2f 100644 --- a/src/com/projectkorra/projectkorra/configuration/ConfigType.java +++ b/src/com/projectkorra/projectkorra/configuration/ConfigType.java @@ -14,16 +14,16 @@ public class ConfigType { public static final ConfigType LANGUAGE = new ConfigType("Language"); public static final ConfigType[] CORE_TYPES = { DEFAULT, PRESETS, LANGUAGE }; - private String string; + private final String string; - public ConfigType(String string) { + public ConfigType(final String string) { this.string = string; ALL_TYPES.put(string, this); } public static List addonValues() { - List values = new ArrayList<>(); - for (String key : ALL_TYPES.keySet()) { + final List values = new ArrayList<>(); + for (final String key : ALL_TYPES.keySet()) { if (!Arrays.asList(CORE_TYPES).contains(ALL_TYPES.get(key))) { values.add(ALL_TYPES.get(key)); } @@ -35,13 +35,14 @@ public static List coreValues() { return Arrays.asList(CORE_TYPES); } + @Override public String toString() { - return string; + return this.string; } public static List values() { - List values = new ArrayList<>(); - for (String key : ALL_TYPES.keySet()) { + final List values = new ArrayList<>(); + for (final String key : ALL_TYPES.keySet()) { values.add(ALL_TYPES.get(key)); } return values; diff --git a/src/com/projectkorra/projectkorra/earthbending/Catapult.java b/src/com/projectkorra/projectkorra/earthbending/Catapult.java index a52d5fff9..78e8fb642 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Catapult.java +++ b/src/com/projectkorra/projectkorra/earthbending/Catapult.java @@ -31,21 +31,21 @@ public class Catapult extends EarthAbility { private double angle; private boolean cancelWithAngle; - public Catapult(Player player, boolean sneak) { + public Catapult(final Player player, final boolean sneak) { super(player); - setFields(); - Block b = player.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); + this.setFields(); + final Block b = player.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); if (!(isEarth(b) || isSand(b) || isMetal(b))) { return; } - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.Catapult.Cooldown"); } this.charging = sneak; - start(); + this.start(); } private void setFields() { @@ -56,75 +56,75 @@ private void setFields() { this.activationHandled = false; this.stage = 1; this.stageStart = System.currentTimeMillis(); - up = new Vector(0, 1, 0); + this.up = new Vector(0, 1, 0); } - private void moveEarth(Vector apply, Vector direction) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(origin, 2)) { - if (entity.getEntityId() != player.getEntityId()) { + private void moveEarth(final Vector apply, final Vector direction) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.origin, 2)) { + if (entity.getEntityId() != this.player.getEntityId()) { entity.setVelocity(apply); } } - moveEarth(this.origin.clone().subtract(direction), direction, 3, false); + this.moveEarth(this.origin.clone().subtract(direction), direction, 3, false); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (charging) { - if (stage == 4 || !player.isSneaking()) { - charging = false; + if (this.charging) { + if (this.stage == 4 || !this.player.isSneaking()) { + this.charging = false; } else { if ((System.currentTimeMillis() - this.stageStart) >= ((Math.max(0, this.stageTimeMult * (this.stage - 1))) * 1000)) { this.stage++; this.stageStart = System.currentTimeMillis(); - Random random = new Random(); - ParticleEffect.BLOCK_DUST.display(new BlockData(Material.DIRT, (byte) 0), random.nextFloat(), random.nextFloat(), random.nextFloat(), 0, 20, player.getLocation(), 257); - ParticleEffect.BLOCK_DUST.display(new BlockData(Material.DIRT, (byte) 0), random.nextFloat(), random.nextFloat(), random.nextFloat(), 0, 20, player.getLocation().add(0, 0.5, 0), 257); - player.getWorld().playEffect(player.getLocation(), Effect.GHAST_SHOOT, 0, 10); + final Random random = new Random(); + ParticleEffect.BLOCK_DUST.display(new BlockData(Material.DIRT, (byte) 0), random.nextFloat(), random.nextFloat(), random.nextFloat(), 0, 20, this.player.getLocation(), 257); + ParticleEffect.BLOCK_DUST.display(new BlockData(Material.DIRT, (byte) 0), random.nextFloat(), random.nextFloat(), random.nextFloat(), 0, 20, this.player.getLocation().add(0, 0.5, 0), 257); + this.player.getWorld().playEffect(this.player.getLocation(), Effect.GHAST_SHOOT, 0, 10); } } return; } - - Block b = player.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); + + final Block b = this.player.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); if (!(isEarth(b) || isSand(b) || isMetal(b))) { - remove(); + this.remove(); return; } Vector direction = null; if (!this.activationHandled) { - this.origin = player.getLocation().clone(); - direction = player.getEyeLocation().getDirection().clone().normalize(); + this.origin = this.player.getLocation().clone(); + direction = this.player.getEyeLocation().getDirection().clone().normalize(); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { this.activationHandled = true; - remove(); + this.remove(); return; } this.activationHandled = true; - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } - - if (up.angle(player.getEyeLocation().getDirection()) > angle) { - if (cancelWithAngle) { - remove(); + + if (this.up.angle(this.player.getEyeLocation().getDirection()) > this.angle) { + if (this.cancelWithAngle) { + this.remove(); return; } - direction = up; + direction = this.up; } - - Location tar = this.origin.clone().add(direction.clone().normalize().multiply(this.stage + 0.5)); + + final Location tar = this.origin.clone().add(direction.clone().normalize().multiply(this.stage + 0.5)); this.target = tar; - Vector apply = this.target.clone().toVector().subtract(this.origin.clone().toVector()); - player.setVelocity(apply); - moveEarth(apply, direction); - remove(); + final Vector apply = this.target.clone().toVector().subtract(this.origin.clone().toVector()); + this.player.setVelocity(apply); + this.moveEarth(apply, direction); + this.remove(); } @Override @@ -134,15 +134,15 @@ public String getName() { @Override public Location getLocation() { - if (player != null) { - return player.getLocation(); + if (this.player != null) { + return this.player.getLocation(); } return null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -156,22 +156,22 @@ public boolean isHarmlessAbility() { } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Location getTarget() { - return target; + return this.target; } - public void setTarget(Location target) { + public void setTarget(final Location target) { this.target = target; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } } diff --git a/src/com/projectkorra/projectkorra/earthbending/Collapse.java b/src/com/projectkorra/projectkorra/earthbending/Collapse.java index 0be8d43ee..9ddeb79db 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Collapse.java +++ b/src/com/projectkorra/projectkorra/earthbending/Collapse.java @@ -28,56 +28,56 @@ public class Collapse extends EarthAbility { private Block block; private Map affectedBlocks; - public Collapse(Player player) { + public Collapse(final Player player) { super(player); - setFields(); + this.setFields(); - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("CollapsePillar")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("CollapsePillar")) { return; } - block = BlockSource.getEarthSourceBlock(player, selectRange, ClickType.LEFT_CLICK); - if (block == null) { + this.block = BlockSource.getEarthSourceBlock(player, this.selectRange, ClickType.LEFT_CLICK); + if (this.block == null) { return; } - this.origin = block.getLocation(); - this.location = origin.clone(); - this.distance = getEarthbendableBlocksLength(block, direction.clone().multiply(-1), height); - loadAffectedBlocks(); + this.origin = this.block.getLocation(); + this.location = this.origin.clone(); + this.distance = this.getEarthbendableBlocksLength(this.block, this.direction.clone().multiply(-1), this.height); + this.loadAffectedBlocks(); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.Collapse.Column.Height"); } - if (distance != 0) { - start(); - bPlayer.addCooldown("CollapsePillar", cooldown); - time = System.currentTimeMillis() - (long) (1000.0 / speed); + if (this.distance != 0) { + this.start(); + this.bPlayer.addCooldown("CollapsePillar", this.cooldown); + this.time = System.currentTimeMillis() - (long) (1000.0 / this.speed); } else { - remove(); + this.remove(); } } - public Collapse(Player player, Location origin) { + public Collapse(final Player player, final Location origin) { super(player); - setFields(); + this.setFields(); this.origin = origin; this.player = player; this.block = origin.getBlock(); this.location = origin.clone(); - this.distance = getEarthbendableBlocksLength(block, direction.clone().multiply(-1), height); - loadAffectedBlocks(); + this.distance = this.getEarthbendableBlocksLength(this.block, this.direction.clone().multiply(-1), this.height); + this.loadAffectedBlocks(); - if (distance != 0) { - start(); - time = System.currentTimeMillis() - (long) (1000.0 / speed); + if (this.distance != 0) { + this.start(); + this.time = System.currentTimeMillis() - (long) (1000.0 / this.speed); } else { - remove(); + this.remove(); } } private void setFields() { - this.height = bPlayer.isAvatarState() ? getConfig().getInt("Abilities.Avatar.AvatarState.Earth.Collapse.Column.Height") : getConfig().getInt("Abilities.Earth.Collapse.Column.Height"); + this.height = this.bPlayer.isAvatarState() ? getConfig().getInt("Abilities.Avatar.AvatarState.Earth.Collapse.Column.Height") : getConfig().getInt("Abilities.Earth.Collapse.Column.Height"); this.selectRange = getConfig().getInt("Abilities.Earth.Collapse.SelectRange"); this.speed = getConfig().getDouble("Abilities.Earth.Collapse.Speed"); this.cooldown = getConfig().getLong("Abilities.Earth.Collapse.Column.Cooldown"); @@ -86,20 +86,20 @@ private void setFields() { } private void loadAffectedBlocks() { - affectedBlocks.clear(); + this.affectedBlocks.clear(); Block thisBlock; - for (int i = 0; i <= distance; i++) { - thisBlock = block.getWorld().getBlockAt(location.clone().add(direction.clone().multiply(-i))); - affectedBlocks.put(thisBlock, thisBlock); + for (int i = 0; i <= this.distance; i++) { + thisBlock = this.block.getWorld().getBlockAt(this.location.clone().add(this.direction.clone().multiply(-i))); + this.affectedBlocks.put(thisBlock, thisBlock); if (RaiseEarth.blockInAllAffectedBlocks(thisBlock)) { - RaiseEarth.revertBlock(thisBlock); + EarthAbility.revertBlock(thisBlock); } } } - public static boolean blockInAllAffectedBlocks(Block block) { - for (Collapse collapse : getAbilities(Collapse.class)) { + public static boolean blockInAllAffectedBlocks(final Block block) { + for (final Collapse collapse : getAbilities(Collapse.class)) { if (collapse.affectedBlocks.containsKey(block)) { return true; } @@ -107,33 +107,33 @@ public static boolean blockInAllAffectedBlocks(Block block) { return false; } - public static void revert(Block block) { - for (Collapse collapse : getAbilities(Collapse.class)) { + public static void revert(final Block block) { + for (final Collapse collapse : getAbilities(Collapse.class)) { collapse.affectedBlocks.remove(block); } } @Override public void progress() { - if (System.currentTimeMillis() - time >= (long) (1000.0 / speed)) { - time = System.currentTimeMillis(); - if (!tryToMoveEarth()) { - remove(); + if (System.currentTimeMillis() - this.time >= (long) (1000.0 / this.speed)) { + this.time = System.currentTimeMillis(); + if (!this.tryToMoveEarth()) { + this.remove(); return; } } } private boolean tryToMoveEarth() { - Block block = location.getBlock(); - location = location.add(direction); - if (distance == 0) { + final Block block = this.location.getBlock(); + this.location = this.location.add(this.direction); + if (this.distance == 0) { return false; } - moveEarth(block, direction, distance); - loadAffectedBlocks(); - return location.distanceSquared(origin) < distance * distance; + this.moveEarth(block, this.direction, this.distance); + this.loadAffectedBlocks(); + return this.location.distanceSquared(this.origin) < this.distance * this.distance; } @Override @@ -143,12 +143,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -163,86 +163,86 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (Block block : affectedBlocks.values()) { + final ArrayList locations = new ArrayList<>(); + for (final Block block : this.affectedBlocks.values()) { locations.add(block.getLocation()); } return locations; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Block getBlock() { - return block; + return this.block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } public int getDistance() { - return distance; + return this.distance; } - public void setDistance(int distance) { + public void setDistance(final int distance) { this.distance = distance; } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public Map getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } } diff --git a/src/com/projectkorra/projectkorra/earthbending/CollapseWall.java b/src/com/projectkorra/projectkorra/earthbending/CollapseWall.java index 891b02398..61422a2a6 100644 --- a/src/com/projectkorra/projectkorra/earthbending/CollapseWall.java +++ b/src/com/projectkorra/projectkorra/earthbending/CollapseWall.java @@ -24,10 +24,10 @@ public class CollapseWall extends EarthAbility { private Map blocks; private Map baseBlocks; - public CollapseWall(Player player) { + public CollapseWall(final Player player) { super(player); - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("CollapseWall")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("CollapseWall")) { return; } @@ -38,40 +38,40 @@ public CollapseWall(Player player) { this.blocks = new ConcurrentHashMap<>(); this.baseBlocks = new ConcurrentHashMap<>(); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.Collapse.Wall.Height"); } - - Block sblock = BlockSource.getEarthSourceBlock(player, selectRange, ClickType.SHIFT_DOWN); + + final Block sblock = BlockSource.getEarthSourceBlock(player, this.selectRange, ClickType.SHIFT_DOWN); if (sblock == null) { - location = getTargetEarthBlock(selectRange).getLocation(); + this.location = this.getTargetEarthBlock(this.selectRange).getLocation(); } else { - location = sblock.getLocation(); + this.location = sblock.getLocation(); } - for (Block block : GeneralMethods.getBlocksAroundPoint(location, radius)) { - if (isEarthbendable(block) && !blocks.containsKey(block) && block.getY() >= location.getBlockY()) { - getAffectedBlocks(block); + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.location, this.radius)) { + if (this.isEarthbendable(block) && !this.blocks.containsKey(block) && block.getY() >= this.location.getBlockY()) { + this.getAffectedBlocks(block); } } - if (!baseBlocks.isEmpty()) { - bPlayer.addCooldown("CollapseWall", cooldown); + if (!this.baseBlocks.isEmpty()) { + this.bPlayer.addCooldown("CollapseWall", this.cooldown); } - for (Block block : baseBlocks.keySet()) { + for (final Block block : this.baseBlocks.keySet()) { new Collapse(player, block.getLocation()); } } - private void getAffectedBlocks(Block block) { + private void getAffectedBlocks(final Block block) { int tall = 0; Block baseBlock = block; - ArrayList bendableBlocks = new ArrayList(); + final ArrayList bendableBlocks = new ArrayList(); bendableBlocks.add(block); - for (int i = 1; i <= height; i++) { - Block blocki = block.getRelative(BlockFace.DOWN, i); - if (isEarthbendable(blocki)) { + for (int i = 1; i <= this.height; i++) { + final Block blocki = block.getRelative(BlockFace.DOWN, i); + if (this.isEarthbendable(blocki)) { baseBlock = blocki; bendableBlocks.add(blocki); tall++; @@ -80,9 +80,9 @@ private void getAffectedBlocks(Block block) { } } - baseBlocks.put(baseBlock, tall); - for (Block blocki : bendableBlocks) { - blocks.put(blocki, baseBlock); + this.baseBlocks.put(baseBlock, tall); + for (final Block blocki : bendableBlocks) { + this.blocks.put(blocki, baseBlock); } } @@ -97,12 +97,12 @@ public void progress() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -116,42 +116,42 @@ public boolean isHarmlessAbility() { } public int getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(int selectRange) { + public void setSelectRange(final int selectRange) { this.selectRange = selectRange; } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public Map getBlocks() { - return blocks; + return this.blocks; } public Map getBaseBlocks() { - return baseBlocks; + return this.baseBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthArmor.java b/src/com/projectkorra/projectkorra/earthbending/EarthArmor.java index 8ab16f66c..000e9b5c3 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthArmor.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthArmor.java @@ -43,10 +43,11 @@ public class EarthArmor extends EarthAbility { private PotionEffect oldAbsorbtion = null; private float goldHearts; private int maxGoldHearts; + private TempArmor armor; - public EarthArmor(Player player) { + public EarthArmor(final Player player) { super(player); - if (hasAbility(player, EarthArmor.class) || !canBend()) { + if (hasAbility(player, EarthArmor.class) || !this.canBend()) { return; } @@ -59,23 +60,23 @@ public EarthArmor(Player player) { this.selectRange = getConfig().getDouble("Abilities.Earth.EarthArmor.SelectRange"); this.maxGoldHearts = getConfig().getInt("Abilities.Earth.EarthArmor.GoldHearts"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthArmor.Cooldown"); this.maxGoldHearts = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.EarthArmor.GoldHearts"); } - headBlock = getTargetEarthBlock((int) selectRange); - if (!GeneralMethods.isRegionProtectedFromBuild(this, headBlock.getLocation()) && getEarthbendableBlocksLength(headBlock, new Vector(0, -1, 0), 2) >= 2) { - this.legsBlock = headBlock.getRelative(BlockFace.DOWN); - this.headData = headBlock.getState().getData(); - this.legsData = legsBlock.getState().getData(); - this.headBlockLocation = headBlock.getLocation(); - this.legsBlockLocation = legsBlock.getLocation(); + this.headBlock = this.getTargetEarthBlock((int) this.selectRange); + if (!GeneralMethods.isRegionProtectedFromBuild(this, this.headBlock.getLocation()) && this.getEarthbendableBlocksLength(this.headBlock, new Vector(0, -1, 0), 2) >= 2) { + this.legsBlock = this.headBlock.getRelative(BlockFace.DOWN); + this.headData = this.headBlock.getState().getData(); + this.legsData = this.legsBlock.getState().getData(); + this.headBlockLocation = this.headBlock.getLocation(); + this.legsBlockLocation = this.legsBlock.getLocation(); - Block oldHeadBlock = headBlock; - Block oldLegsBlock = legsBlock; + final Block oldHeadBlock = this.headBlock; + final Block oldLegsBlock = this.legsBlock; - if (!moveBlocks()) { + if (!this.moveBlocks()) { return; } if (isEarthRevertOn()) { @@ -86,179 +87,175 @@ public EarthArmor(Player player) { GeneralMethods.removeBlock(oldLegsBlock); } - playEarthbendingSound(headBlock.getLocation()); - start(); + playEarthbendingSound(this.headBlock.getLocation()); + this.start(); } } - @SuppressWarnings("deprecation") private void formArmor() { - if (TempBlock.isTempBlock(headBlock)) { - TempBlock.revertBlock(headBlock, Material.AIR); + if (TempBlock.isTempBlock(this.headBlock)) { + TempBlock.revertBlock(this.headBlock, Material.AIR); } - if (TempBlock.isTempBlock(legsBlock)) { - TempBlock.revertBlock(legsBlock, Material.AIR); + if (TempBlock.isTempBlock(this.legsBlock)) { + TempBlock.revertBlock(this.legsBlock, Material.AIR); } - ItemStack head = new ItemStack(Material.LEATHER_HELMET, 1); - ItemStack chestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1); - ItemStack leggings = new ItemStack(Material.LEATHER_LEGGINGS, 1); - ItemStack boots = new ItemStack(Material.LEATHER_BOOTS, 1); + final ItemStack head = new ItemStack(Material.LEATHER_HELMET, 1); + final ItemStack chestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1); + final ItemStack leggings = new ItemStack(Material.LEATHER_LEGGINGS, 1); + final ItemStack boots = new ItemStack(Material.LEATHER_BOOTS, 1); - LeatherArmorMeta metaHead = (LeatherArmorMeta) head.getItemMeta(); - LeatherArmorMeta metaChest = (LeatherArmorMeta) chestplate.getItemMeta(); - LeatherArmorMeta metaLegs = (LeatherArmorMeta) leggings.getItemMeta(); - LeatherArmorMeta metaBottom = (LeatherArmorMeta) boots.getItemMeta(); + final LeatherArmorMeta metaHead = (LeatherArmorMeta) head.getItemMeta(); + final LeatherArmorMeta metaChest = (LeatherArmorMeta) chestplate.getItemMeta(); + final LeatherArmorMeta metaLegs = (LeatherArmorMeta) leggings.getItemMeta(); + final LeatherArmorMeta metaBottom = (LeatherArmorMeta) boots.getItemMeta(); - metaHead.setColor(Color.fromRGB(getColor(headData.getItemType(), headData.getData()))); - metaChest.setColor(Color.fromRGB(getColor(headData.getItemType(), headData.getData()))); - metaLegs.setColor(Color.fromRGB(getColor(legsData.getItemType(), legsData.getData()))); - metaBottom.setColor(Color.fromRGB(getColor(legsData.getItemType(), legsData.getData()))); + metaHead.setColor(Color.fromRGB(getColor(this.headData.getItemType(), this.headData.getData()))); + metaChest.setColor(Color.fromRGB(getColor(this.headData.getItemType(), this.headData.getData()))); + metaLegs.setColor(Color.fromRGB(getColor(this.legsData.getItemType(), this.legsData.getData()))); + metaBottom.setColor(Color.fromRGB(getColor(this.legsData.getItemType(), this.legsData.getData()))); head.setItemMeta(metaHead); chestplate.setItemMeta(metaChest); leggings.setItemMeta(metaLegs); boots.setItemMeta(metaBottom); - ItemStack armors[] = { boots, leggings, chestplate, head }; - TempArmor armor = new TempArmor(player, 72000000L, this, armors); //Duration of 2 hours - armor.setRemovesAbilityOnForceRevert(true); - formed = true; + final ItemStack armors[] = { boots, leggings, chestplate, head }; + this.armor = new TempArmor(this.player, 72000000L, this, armors); // Duration of 2 hours. + this.armor.setRemovesAbilityOnForceRevert(true); + this.formed = true; - for (PotionEffect effect : player.getActivePotionEffects()) { + for (final PotionEffect effect : this.player.getActivePotionEffects()) { if (effect.getType() == PotionEffectType.ABSORPTION) { this.oldAbsorbtion = effect; - player.removePotionEffect(PotionEffectType.ABSORPTION); + this.player.removePotionEffect(PotionEffectType.ABSORPTION); break; } } - int level = (int) (maxGoldHearts / 2 - 1 + (maxGoldHearts % 2)); - player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, Integer.MAX_VALUE, level, true, false)); + final int level = this.maxGoldHearts / 2 - 1 + (this.maxGoldHearts % 2); + this.player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, Integer.MAX_VALUE, level, true, false)); - this.goldHearts = maxGoldHearts * 2; - GeneralMethods.setAbsorbationHealth(player, goldHearts); + this.goldHearts = this.maxGoldHearts * 2; + GeneralMethods.setAbsorbationHealth(this.player, this.goldHearts); } private boolean inPosition() { - return headBlock.equals(player.getEyeLocation().getBlock()) && legsBlock.equals(player.getLocation().getBlock()); + return this.headBlock.equals(this.player.getEyeLocation().getBlock()) && this.legsBlock.equals(this.player.getLocation().getBlock()); } - @SuppressWarnings("deprecation") private boolean moveBlocks() { - if (!player.getWorld().equals(headBlock.getWorld())) { - remove(); + if (!this.player.getWorld().equals(this.headBlock.getWorld())) { + this.remove(); return false; } - Location headLocation = player.getEyeLocation(); - Location legsLocation = player.getLocation(); - Vector headDirection = headLocation.toVector().subtract(headBlockLocation.toVector()).normalize().multiply(.5); - //Vector legsDirection = legsLocation.toVector().subtract(legsBlockLocation.toVector()).normalize().multiply(.5); - Block newHeadBlock = headBlock; - Block newLegsBlock = legsBlock; + final Location headLocation = this.player.getEyeLocation(); + final Location legsLocation = this.player.getLocation(); + Vector headDirection = headLocation.toVector().subtract(this.headBlockLocation.toVector()).normalize().multiply(.5); - int yDiff = player.getEyeLocation().getBlockY() - headBlock.getY(); + Block newHeadBlock = this.headBlock; + Block newLegsBlock = this.legsBlock; + + final int yDiff = this.player.getEyeLocation().getBlockY() - this.headBlock.getY(); if (yDiff != 0) { - Block checkBlock = yDiff > 0 ? headBlock.getRelative(BlockFace.UP) : legsBlock.getRelative(BlockFace.DOWN); + final Block checkBlock = yDiff > 0 ? this.headBlock.getRelative(BlockFace.UP) : this.legsBlock.getRelative(BlockFace.DOWN); - if (isTransparent(checkBlock) && !checkBlock.isLiquid()) { - GeneralMethods.breakBlock(checkBlock); //Destroy any minor blocks that are in the way + if (this.isTransparent(checkBlock) && !checkBlock.isLiquid()) { + GeneralMethods.breakBlock(checkBlock); // Destroy any minor blocks that are in the way. headDirection = new Vector(0, yDiff > 0 ? 0.5 : -0.5, 0); } } - if (!headLocation.getBlock().equals(headBlock)) { - headBlockLocation = headBlockLocation.clone().add(headDirection); - newHeadBlock = headBlockLocation.getBlock(); + if (!headLocation.getBlock().equals(this.headBlock)) { + this.headBlockLocation = this.headBlockLocation.clone().add(headDirection); + newHeadBlock = this.headBlockLocation.getBlock(); } - if (!legsLocation.getBlock().equals(legsBlock)) { - legsBlockLocation = headBlockLocation.clone().add(0, -1, 0); + if (!legsLocation.getBlock().equals(this.legsBlock)) { + this.legsBlockLocation = this.headBlockLocation.clone().add(0, -1, 0); newLegsBlock = newHeadBlock.getRelative(BlockFace.DOWN); } - if (isTransparent(newHeadBlock) && !newHeadBlock.isLiquid()) { + if (this.isTransparent(newHeadBlock) && !newHeadBlock.isLiquid()) { GeneralMethods.breakBlock(newHeadBlock); - } else if (!isEarthbendable(newHeadBlock) && !newHeadBlock.isLiquid() && newHeadBlock.getType() != Material.AIR) { - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(headData.getItemType(), headData.getData()), 0.5F, 0.5F, 0.5F, 1, 32, newLegsBlock.getLocation(), 128); - remove(); + } else if (!this.isEarthbendable(newHeadBlock) && !newHeadBlock.isLiquid() && newHeadBlock.getType() != Material.AIR) { + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.headData.getItemType(), this.headData.getData()), 0.5F, 0.5F, 0.5F, 1, 32, newLegsBlock.getLocation(), 128); + this.remove(); return false; } - if (isTransparent(newLegsBlock) && !newLegsBlock.isLiquid()) { + if (this.isTransparent(newLegsBlock) && !newLegsBlock.isLiquid()) { GeneralMethods.breakBlock(newLegsBlock); - } else if (!isEarthbendable(newLegsBlock) && !newLegsBlock.isLiquid() && newLegsBlock.getType() != Material.AIR) { + } else if (!this.isEarthbendable(newLegsBlock) && !newLegsBlock.isLiquid() && newLegsBlock.getType() != Material.AIR) { newLegsBlock.getLocation().getWorld().playSound(newLegsBlock.getLocation(), Sound.BLOCK_GRASS_BREAK, 1, 1); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(legsData.getItemType(), legsData.getData()), 0.5F, 0.5F, 0.5F, 1, 32, newLegsBlock.getLocation(), 128); - remove(); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.legsData.getItemType(), this.legsData.getData()), 0.5F, 0.5F, 0.5F, 1, 32, newLegsBlock.getLocation(), 128); + this.remove(); return false; } - if (headBlock.getLocation().distanceSquared(player.getEyeLocation()) > selectRange * selectRange) { - remove(); + if (this.headBlock.getLocation().distanceSquared(this.player.getEyeLocation()) > this.selectRange * this.selectRange) { + this.remove(); return false; } - if (!newHeadBlock.equals(headBlock)) { - new TempBlock(newHeadBlock, headData.getItemType(), headData.getData()); - if (TempBlock.isTempBlock(headBlock)) { - TempBlock.revertBlock(headBlock, Material.AIR); + if (!newHeadBlock.equals(this.headBlock)) { + new TempBlock(newHeadBlock, this.headData.getItemType(), this.headData.getData()); + if (TempBlock.isTempBlock(this.headBlock)) { + TempBlock.revertBlock(this.headBlock, Material.AIR); } } - if (!newLegsBlock.equals(legsBlock)) { - new TempBlock(newLegsBlock, legsData.getItemType(), legsData.getData()); - if (TempBlock.isTempBlock(legsBlock)) { - TempBlock.revertBlock(legsBlock, Material.AIR); + if (!newLegsBlock.equals(this.legsBlock)) { + new TempBlock(newLegsBlock, this.legsData.getItemType(), this.legsData.getData()); + if (TempBlock.isTempBlock(this.legsBlock)) { + TempBlock.revertBlock(this.legsBlock, Material.AIR); } } - headBlock = newHeadBlock; - legsBlock = newLegsBlock; + this.headBlock = newHeadBlock; + this.legsBlock = newLegsBlock; return true; } - @SuppressWarnings("deprecation") @Override public void progress() { - if (!canBend()) { - remove(); + if (!this.canBend()) { + this.remove(); return; } - if (System.currentTimeMillis() - getStartTime() > maxDuration) { - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + if (System.currentTimeMillis() - this.getStartTime() > this.maxDuration) { + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(headData.getItemType(), headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getEyeLocation(), 128); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(legsData.getItemType(), legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.headData.getItemType(), this.headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, this.player.getEyeLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.legsData.getItemType(), this.legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, this.player.getLocation(), 128); - bPlayer.addCooldown(this); - remove(); + this.bPlayer.addCooldown(this); + this.remove(); return; } - if (formed) { - //PassiveHandler.checkArmorPassives(player); - if (!player.hasPotionEffect(PotionEffectType.ABSORPTION)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, Integer.MAX_VALUE, 1, true, false)); - GeneralMethods.setAbsorbationHealth(player, goldHearts); + if (this.formed) { + if (!this.player.hasPotionEffect(PotionEffectType.ABSORPTION)) { + this.player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, Integer.MAX_VALUE, 1, true, false)); + GeneralMethods.setAbsorbationHealth(this.player, this.goldHearts); } - if (!active) { - bPlayer.addCooldown(this); - remove(); + if (!this.active) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - player.setFireTicks(0); + this.player.setFireTicks(0); } else { - if (!moveBlocks()) { + if (!this.moveBlocks()) { return; } - if (inPosition()) { - formArmor(); + if (this.inPosition()) { + this.formArmor(); } } } @@ -267,25 +264,25 @@ public void progress() { public void remove() { super.remove(); if (isEarthRevertOn()) { - if (TempBlock.isTempBlock(headBlock)) { - TempBlock.revertBlock(headBlock, Material.AIR); + if (TempBlock.isTempBlock(this.headBlock)) { + TempBlock.revertBlock(this.headBlock, Material.AIR); } - if (TempBlock.isTempBlock(legsBlock)) { - TempBlock.revertBlock(legsBlock, Material.AIR); + if (TempBlock.isTempBlock(this.legsBlock)) { + TempBlock.revertBlock(this.legsBlock, Material.AIR); } } else { - headBlock.breakNaturally(); - legsBlock.breakNaturally(); + this.headBlock.breakNaturally(); + this.legsBlock.breakNaturally(); } - if (TempArmor.hasTempArmor(player) && TempArmor.getTempArmor(player).getAbility().equals(this)) { - TempArmor.getTempArmor(player).revert(); + if (TempArmor.getTempArmorList(this.player).contains(this.armor)) { + this.armor.revert(); } - player.removePotionEffect(PotionEffectType.ABSORPTION); + this.player.removePotionEffect(PotionEffectType.ABSORPTION); - if (oldAbsorbtion != null) { - player.addPotionEffect(oldAbsorbtion); + if (this.oldAbsorbtion != null) { + this.player.addPotionEffect(this.oldAbsorbtion); } } @@ -293,160 +290,201 @@ public void remove() { public void updateAbsorbtion() { final EarthArmor abil = this; new BukkitRunnable() { - @SuppressWarnings("deprecation") + @Override public void run() { - goldHearts = GeneralMethods.getAbsorbationHealth(player); - if (formed && goldHearts < 0.9F) { - bPlayer.addCooldown(abil); + EarthArmor.this.goldHearts = GeneralMethods.getAbsorbationHealth(EarthArmor.this.player); + if (EarthArmor.this.formed && EarthArmor.this.goldHearts < 0.9F) { + EarthArmor.this.bPlayer.addCooldown(abil); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + EarthArmor.this.player.getLocation().getWorld().playSound(EarthArmor.this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + EarthArmor.this.player.getLocation().getWorld().playSound(EarthArmor.this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + EarthArmor.this.player.getLocation().getWorld().playSound(EarthArmor.this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(headData.getItemType(), headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getEyeLocation(), 128); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(legsData.getItemType(), legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(EarthArmor.this.headData.getItemType(), EarthArmor.this.headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, EarthArmor.this.player.getEyeLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(EarthArmor.this.legsData.getItemType(), EarthArmor.this.legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, EarthArmor.this.player.getLocation(), 128); - remove(); + EarthArmor.this.remove(); } } }.runTaskLater(ProjectKorra.plugin, 1L); } - public static int getColor(Material material) { + public static int getColor(final Material material) { return getColor(material, (byte) 0x0); } /** Returns the color for the specified material. */ - public static int getColor(Material material, byte damage) { - if (material == Material.DIRT) - return 0xa86e45; //Default dirt brown - if (material == Material.GRASS) - return 0xa86e45; //Default dirt brown - if (material == Material.MYCEL) - return 0xa86e45; //Default dirt brown - if (material == Material.CLAY) - return 0xBAC2D1; //Dull gray-brown - if (material == Material.STONE && damage == 0x0) - return 0x9e9e9e; //Gray - if (material == Material.STONE && (damage == 0x1 || damage == 0x2)) - return 0xc69489; //Pink - if (material == Material.STONE && (damage == 0x3 || damage == 0x4)) - return 0xe3e3e5; //White - if (material == Material.STONE && (damage == 0x5 || damage == 0x6)) - return 0xa3a3a3; //Gray - if (material == Material.COBBLESTONE) - return 0x6B6B6B; //Dark Gray - if (material == Material.SAND && damage == 0x0) - return 0xffffaf; //Sand yellow - if (material == Material.SAND && damage == 0x1) - return 0xb85f25; //Sand orange - if (material == Material.SANDSTONE) - return 0xffffaf; //Sand - if (material == Material.RED_SANDSTONE) - return 0xbc5a1a; //Red sandstone - if (material == Material.GRAVEL) - return 0xaaa49e; //Dark Gray - if (material == Material.GOLD_ORE) - return 0xa2a38f; //Gray-yellow - if (material == Material.GOLD_BLOCK) - return 0xF2F204; //Gold - Could be a tiny bit darker - if (material == Material.IRON_ORE) - return 0xa39d91; //Gray-brown - if (material == Material.IRON_BLOCK) - return 0xf4f4f4; //Silver/Gray - if (material == Material.COAL_ORE) - return 0x7c7c7c; //Stone gray - if (material == Material.LAPIS_ORE) - return 0x9198a3; //Gray-azure - if (material == Material.LAPIS_BLOCK) - return 0x0060BA; //Dark blue - if (material == Material.DIAMOND_ORE) - return 0xa8bebf; //Gray-cyan - if (material == Material.NETHERRACK) - return 0x9b3131; //Pinkish-red - if (material == Material.QUARTZ_ORE) - return 0xb75656; //Pinkish-red - if (material == Material.QUARTZ_BLOCK) - return 0xfff4f4; //White - if (material == Material.STAINED_CLAY && damage == 0x0) - return 0xCFAFA0; //White Stained Clay - if (material == Material.STAINED_CLAY && damage == 0x1) - return 0xA75329; //Orange - if (material == Material.STAINED_CLAY && damage == 0x2) - return 0x95596E; //Magenta - if (material == Material.STAINED_CLAY && damage == 0x3) - return 0x736E8A; //Light blue - if (material == Material.STAINED_CLAY && damage == 0x4) - return 0xBA8825; //Yellow - if (material == Material.STAINED_CLAY && damage == 0x5) - return 0x6B7736; //Lime - if (material == Material.STAINED_CLAY && damage == 0x6) - return 0xA24D4F; //Pink - if (material == Material.STAINED_CLAY && damage == 0x7) - return 0x3A2923; //Gray - if (material == Material.STAINED_CLAY && damage == 0x8) - return 0x876A61; //Light Gray - if (material == Material.STAINED_CLAY && damage == 0x9) - return 0x575B5B; //Cyan - if (material == Material.STAINED_CLAY && damage == 0xA) - return 0x734453; //Purple - if (material == Material.STAINED_CLAY && damage == 0xB) - return 0x493A5A; //Blue - if (material == Material.STAINED_CLAY && damage == 0xC) - return 0x4C3223; //Brown - if (material == Material.STAINED_CLAY && damage == 0xD) - return 0x4B522A; //Green - if (material == Material.STAINED_CLAY && damage == 0xE) - return 0x8D3B2E; //Red - if (material == Material.STAINED_CLAY && damage == 0xF) - return 0x251610; //Black - - return 0x9e9e9e; //Stone - } - - @SuppressWarnings("deprecation") + public static int getColor(final Material material, final byte damage) { + if (material == Material.DIRT) { + return 0xa86e45; // Default dirt brown. + } + if (material == Material.GRASS) { + return 0xa86e45; // Default dirt brown. + } + if (material == Material.MYCEL) { + return 0xa86e45; // Default dirt brown. + } + if (material == Material.CLAY) { + return 0xBAC2D1; // Dull gray-brown. + } + if (material == Material.STONE && damage == 0x0) { + return 0x9e9e9e; // Gray. + } + if (material == Material.STONE && (damage == 0x1 || damage == 0x2)) { + return 0xc69489; // Pink. + } + if (material == Material.STONE && (damage == 0x3 || damage == 0x4)) { + return 0xe3e3e5; // White. + } + if (material == Material.STONE && (damage == 0x5 || damage == 0x6)) { + return 0xa3a3a3; // Gray. + } + if (material == Material.COBBLESTONE) { + return 0x6B6B6B; // Dark Gray. + } + if (material == Material.SAND && damage == 0x0) { + return 0xffffaf; // Sand yellow. + } + if (material == Material.SAND && damage == 0x1) { + return 0xb85f25; // Sand orange. + } + if (material == Material.SANDSTONE) { + return 0xffffaf; // Sand. + } + if (material == Material.RED_SANDSTONE) { + return 0xbc5a1a; // Red sandstone. + } + if (material == Material.GRAVEL) { + return 0xaaa49e; // Dark Gray. + } + if (material == Material.GOLD_ORE) { + return 0xa2a38f; // Gray-yellow. + } + if (material == Material.GOLD_BLOCK) { + return 0xF2F204; // Gold - Could be a tiny bit darker. + } + if (material == Material.IRON_ORE) { + return 0xa39d91; // Gray-brown. + } + if (material == Material.IRON_BLOCK) { + return 0xf4f4f4; // Silver/Gray. + } + if (material == Material.COAL_ORE) { + return 0x7c7c7c; // Stone gray. + } + if (material == Material.LAPIS_ORE) { + return 0x9198a3; // Gray-azure. + } + if (material == Material.LAPIS_BLOCK) { + return 0x0060BA; // Dark blue. + } + if (material == Material.DIAMOND_ORE) { + return 0xa8bebf; // Gray-cyan. + } + if (material == Material.NETHERRACK) { + return 0x9b3131; // Pinkish-red. + } + if (material == Material.QUARTZ_ORE) { + return 0xb75656; // Pinkish-red. + } + if (material == Material.QUARTZ_BLOCK) { + return 0xfff4f4; // White. + } + if (material == Material.STAINED_CLAY && damage == 0x0) { + return 0xCFAFA0; // White Stained Clay. + } + if (material == Material.STAINED_CLAY && damage == 0x1) { + return 0xA75329; // Orange. + } + if (material == Material.STAINED_CLAY && damage == 0x2) { + return 0x95596E; // Magenta. + } + if (material == Material.STAINED_CLAY && damage == 0x3) { + return 0x736E8A; // Light blue. + } + if (material == Material.STAINED_CLAY && damage == 0x4) { + return 0xBA8825; // Yellow. + } + if (material == Material.STAINED_CLAY && damage == 0x5) { + return 0x6B7736; // Lime. + } + if (material == Material.STAINED_CLAY && damage == 0x6) { + return 0xA24D4F; // Pink. + } + if (material == Material.STAINED_CLAY && damage == 0x7) { + return 0x3A2923; // Gray. + } + if (material == Material.STAINED_CLAY && damage == 0x8) { + return 0x876A61; // Light Gray. + } + if (material == Material.STAINED_CLAY && damage == 0x9) { + return 0x575B5B; // Cyan. + } + if (material == Material.STAINED_CLAY && damage == 0xA) { + return 0x734453; // Purple. + } + if (material == Material.STAINED_CLAY && damage == 0xB) { + return 0x493A5A; // Blue. + } + if (material == Material.STAINED_CLAY && damage == 0xC) { + return 0x4C3223; // Brown. + } + if (material == Material.STAINED_CLAY && damage == 0xD) { + return 0x4B522A; // Green. + } + if (material == Material.STAINED_CLAY && damage == 0xE) { + return 0x8D3B2E; // Red. + } + if (material == Material.STAINED_CLAY && damage == 0xF) { + return 0x251610; // Black. + } + + return 0x9e9e9e; // Stone. + } + public void click() { - if (!this.player.isSneaking()) + if (!this.player.isSneaking()) { return; + } - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - player.getLocation().getWorld().playSound(player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); + this.player.getLocation().getWorld().playSound(this.player.getLocation(), Sound.BLOCK_STONE_BREAK, 2, 1); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(headData.getItemType(), headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getEyeLocation(), 128); - ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(legsData.getItemType(), legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, player.getLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.headData.getItemType(), this.headData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, this.player.getEyeLocation(), 128); + ParticleEffect.BLOCK_CRACK.display(new ParticleEffect.BlockData(this.legsData.getItemType(), this.legsData.getData()), 0.1F, 0.1F, 0.1F, 1, 32, this.player.getLocation(), 128); - bPlayer.addCooldown(this); - remove(); + this.bPlayer.addCooldown(this); + this.remove(); } - + private boolean canBend() { - List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); - Location playerLoc = player.getLocation(); + final List disabledWorlds = getConfig().getStringList("Properties.DisabledWorlds"); + final Location playerLoc = this.player.getLocation(); - if (!player.isOnline() || player.isDead()) { + if (!this.player.isOnline() || this.player.isDead()) { return false; - } else if (bPlayer.isOnCooldown("EarthArmor")){ + } else if (this.bPlayer.isOnCooldown("EarthArmor")) { + return false; + } else if (!this.bPlayer.canBind(this)) { return false; - } else if (!bPlayer.canBind(this)) { - return false; - } else if (this.getPlayer() != null && this.getLocation() != null && !this.getLocation().getWorld().equals(player.getWorld())) { + } else if (this.getPlayer() != null && this.getLocation() != null && !this.getLocation().getWorld().equals(this.player.getWorld())) { return false; - } else if (disabledWorlds != null && disabledWorlds.contains(player.getWorld().getName())) { + } else if (disabledWorlds != null && disabledWorlds.contains(this.player.getWorld().getName())) { return false; - } else if (Commands.isToggledForAll || !bPlayer.isToggled() || !bPlayer.isElementToggled(this.getElement())) { + } else if (Commands.isToggledForAll || !this.bPlayer.isToggled() || !this.bPlayer.isElementToggled(this.getElement())) { return false; - } else if (player.getGameMode() == GameMode.SPECTATOR) { + } else if (this.player.getGameMode() == GameMode.SPECTATOR) { return false; } - if (GeneralMethods.isRegionProtectedFromBuild(player, this.getName(), playerLoc)) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.getName(), playerLoc)) { return false; } - + return true; } @@ -457,17 +495,17 @@ public String getName() { @Override public Location getLocation() { - return headBlockLocation; + return this.headBlockLocation; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public boolean isSneakAbility() { - return player != null; + return this.player != null; } @Override @@ -476,95 +514,95 @@ public boolean isHarmlessAbility() { } public boolean isFormed() { - return formed; + return this.formed; } - public void setFormed(boolean formed) { + public void setFormed(final boolean formed) { this.formed = formed; } public MaterialData getHeadData() { - return headData; + return this.headData; } - public void setHeadData(MaterialData materialdata) { + public void setHeadData(final MaterialData materialdata) { this.headData = materialdata; } public MaterialData getLegsData() { - return legsData; + return this.legsData; } - public void setLegsData(MaterialData materialdata) { + public void setLegsData(final MaterialData materialdata) { this.legsData = materialdata; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public Block getHeadBlock() { - return headBlock; + return this.headBlock; } - public void setHeadBlock(Block headBlock) { + public void setHeadBlock(final Block headBlock) { this.headBlock = headBlock; } public Block getLegsBlock() { - return legsBlock; + return this.legsBlock; } - public void setLegsBlock(Block legsBlock) { + public void setLegsBlock(final Block legsBlock) { this.legsBlock = legsBlock; } public Location getHeadBlockLocation() { - return headBlockLocation; + return this.headBlockLocation; } - public void setHeadBlockLocation(Location headBlockLocation) { + public void setHeadBlockLocation(final Location headBlockLocation) { this.headBlockLocation = headBlockLocation; } public Location getLegsBlockLocation() { - return legsBlockLocation; + return this.legsBlockLocation; } - public void setLegsBlockLocation(Location legsBlockLocation) { + public void setLegsBlockLocation(final Location legsBlockLocation) { this.legsBlockLocation = legsBlockLocation; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } public float getGoldHearts() { - return goldHearts; + return this.goldHearts; } public int getMaxGoldHearts() { - return maxGoldHearts; + return this.maxGoldHearts; } - public void setGoldHearts(float goldHearts) { + public void setGoldHearts(final float goldHearts) { this.goldHearts = goldHearts; } - public void setMaxGoldHearts(int maxGoldHearts) { + public void setMaxGoldHearts(final int maxGoldHearts) { this.maxGoldHearts = maxGoldHearts; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java b/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java index 9d898cce5..f681b87fc 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java @@ -15,13 +15,12 @@ import com.projectkorra.projectkorra.ability.AirAbility; import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.ability.util.Collision; -import com.projectkorra.projectkorra.earthbending.passive.EarthPassive; +import com.projectkorra.projectkorra.earthbending.passive.DensityShift; import com.projectkorra.projectkorra.util.BlockSource; import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.DamageHandler; public class EarthBlast extends EarthAbility { - private boolean isProgressing; private boolean isAtDestination; private boolean isSettingUp; @@ -43,7 +42,7 @@ public class EarthBlast extends EarthAbility { private Location firstDestination; private Block sourceBlock; - public EarthBlast(Player player) { + public EarthBlast(final Player player) { super(player); this.isProgressing = false; @@ -59,25 +58,25 @@ public EarthBlast(Player player) { this.pushFactor = getConfig().getDouble("Abilities.Earth.EarthBlast.Push"); this.selectRange = getConfig().getDouble("Abilities.Earth.EarthBlast.SelectRange"); this.time = System.currentTimeMillis(); - this.interval = (long) (1000.0 / speed); + this.interval = (long) (1000.0 / this.speed); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthBlast.Cooldown"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthBlast.Damage"); } - if (prepare()) { - start(); - time = System.currentTimeMillis(); + if (this.prepare()) { + this.start(); + this.time = System.currentTimeMillis(); } } private void checkForCollision() { - for (EarthBlast blast : getAbilities(EarthBlast.class)) { - if (blast.player.equals(player)) { + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { + if (blast.player.equals(this.player)) { continue; - } else if (!blast.location.getWorld().equals(player.getWorld())) { + } else if (!blast.location.getWorld().equals(this.player.getWorld())) { continue; } else if (!blast.isProgressing) { continue; @@ -85,65 +84,80 @@ private void checkForCollision() { continue; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = blast.location; - if (mloc.distanceSquared(location) <= range * range && GeneralMethods.getDistanceFromLine(vector, location, blast.location) < deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { + final Location location = this.player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = blast.location; + if (mloc.distanceSquared(location) <= this.range * this.range && GeneralMethods.getDistanceFromLine(vector, location, blast.location) < this.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { blast.remove(); - remove(); + this.remove(); return; } } } - @SuppressWarnings("deprecation") private void focusBlock() { - if (EarthPassive.isPassiveSand(sourceBlock)) { - EarthPassive.revertSand(sourceBlock); + if (DensityShift.isPassiveSand(this.sourceBlock)) { + DensityShift.revertSand(this.sourceBlock); } - sourceData = sourceBlock.getData(); - if (sourceBlock.getType() == Material.SAND) { - sourceType = Material.SAND; - if (sourceBlock.getData() == (byte) 0x1) { - sourceBlock.setType(Material.RED_SANDSTONE); + this.sourceData = this.sourceBlock.getData(); + if (this.sourceBlock.getType() == Material.SAND) { + this.sourceType = Material.SAND; + if (this.sourceBlock.getData() == (byte) 0x1) { + this.sourceBlock.setType(Material.RED_SANDSTONE); } else { - sourceBlock.setType(Material.SANDSTONE); + this.sourceBlock.setType(Material.SANDSTONE); } - } else if (sourceBlock.getType() == Material.STEP) { - sourceBlock.setType(Material.STEP); - sourceType = Material.STEP; - } else if (sourceBlock.getType() == Material.STONE) { - sourceBlock.setType(Material.COBBLESTONE); - sourceType = Material.STONE; + } else if (this.sourceBlock.getType() == Material.STEP) { + this.sourceBlock.setType(Material.STEP); + this.sourceType = Material.STEP; + } else if (this.sourceBlock.getType() == Material.STONE) { + this.sourceBlock.setType(Material.COBBLESTONE); + this.sourceType = Material.STONE; } else { - sourceType = sourceBlock.getType(); - sourceBlock.setType(Material.STONE); + this.sourceType = this.sourceBlock.getType(); + this.sourceBlock.setType(Material.STONE); } - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } private Location getTargetLocation() { - Entity target = GeneralMethods.getTargetedEntity(player, range, new ArrayList()); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range, new ArrayList()); Location location; + final Material[] trans = new Material[getTransparentMaterials().length + this.getEarthbendableBlocks().size()]; + int i = 0; + for (int j = 0; j < getTransparentMaterials().length; j++) { + trans[j] = getTransparentMaterials()[j]; + i++; + } + for (int j = 0; j < this.getEarthbendableBlocks().size(); j++) { + try { + trans[i] = Material.valueOf(this.getEarthbendableBlocks().get(j)); + } + catch (final IllegalArgumentException e) { + continue; + } + i++; + } if (target == null) { - location = GeneralMethods.getTargetedLocation(player, range); + location = GeneralMethods.getTargetedLocation(this.player, this.range, trans); } else { location = ((LivingEntity) target).getEyeLocation(); } + return location; } public boolean prepare() { - Block block = BlockSource.getEarthSourceBlock(player, range, ClickType.SHIFT_DOWN); - if (block == null || !isEarthbendable(block)) { + final Block block = BlockSource.getEarthSourceBlock(this.player, this.range, ClickType.SHIFT_DOWN); + if (block == null || !this.isEarthbendable(block)) { return false; } boolean selectedABlockInUse = false; - for (EarthBlast blast : getAbilities(player, EarthBlast.class)) { + for (final EarthBlast blast : getAbilities(this.player, EarthBlast.class)) { if (!blast.isProgressing) { blast.remove(); } else if (blast.isProgressing && block.equals(blast.sourceBlock)) { @@ -155,234 +169,239 @@ public boolean prepare() { return false; } - checkForCollision(); - if (block.getLocation().distanceSquared(player.getLocation()) > selectRange * selectRange) { + this.checkForCollision(); + + if (block.getLocation().distanceSquared(this.player.getLocation()) > this.selectRange * this.selectRange) { return false; } - sourceBlock = block; - focusBlock(); + + this.sourceBlock = block; + this.focusBlock(); return true; } - @SuppressWarnings("deprecation") @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); - if (isAtDestination) { - remove(); + if (this.isAtDestination) { + this.remove(); return; - } else if (!isEarthbendable(sourceBlock) && sourceBlock.getType() != Material.COBBLESTONE) { - remove(); + } else if (!this.isEarthbendable(this.sourceBlock) && this.sourceBlock.getType() != Material.COBBLESTONE) { + this.remove(); return; } - if (!isProgressing && !isAtDestination) { - if (sourceBlock == null || !bPlayer.getBoundAbilityName().equals(getName())) { - remove(); + if (!this.isProgressing && !this.isAtDestination) { + if (this.sourceBlock == null || !this.bPlayer.getBoundAbilityName().equals(this.getName())) { + this.remove(); return; - } else if (!player.getWorld().equals(sourceBlock.getWorld())) { - remove(); + } else if (!this.player.getWorld().equals(this.sourceBlock.getWorld())) { + this.remove(); return; - } else if (sourceBlock.getLocation().distanceSquared(player.getLocation()) > selectRange * selectRange) { - remove(); + } else if (this.sourceBlock.getLocation().distanceSquared(this.player.getLocation()) > this.selectRange * this.selectRange) { + this.remove(); return; } } - if (isAtDestination) { - remove(); + if (this.isAtDestination) { + this.remove(); return; } else { - if (!isProgressing) { + if (!this.isProgressing) { return; } - if (sourceBlock.getY() == firstDestination.getBlockY()) { - isSettingUp = false; + + if (this.sourceBlock.getY() == this.firstDestination.getBlockY()) { + this.isSettingUp = false; } Vector direction; - if (isSettingUp) { - direction = GeneralMethods.getDirection(location, firstDestination).normalize(); + if (this.isSettingUp) { + direction = GeneralMethods.getDirection(this.location, this.firstDestination).normalize(); } else { - direction = GeneralMethods.getDirection(location, destination).normalize(); + direction = GeneralMethods.getDirection(this.location, this.destination).normalize(); } - location = location.clone().add(direction); - Block block = location.getBlock(); + this.location = this.location.clone().add(direction); + Block block = this.location.getBlock(); - if (block.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block = location.getBlock(); + if (block.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); } - if (isTransparent(block) && !block.isLiquid()) { + if (this.isTransparent(block) && !block.isLiquid()) { GeneralMethods.breakBlock(block); - } else if (!isSettingUp) { - remove(); + } else if (!this.isSettingUp) { + this.remove(); return; } else { - location = location.clone().subtract(direction); - direction = GeneralMethods.getDirection(location, destination).normalize(); - location = location.clone().add(direction); - - Block block2 = location.getBlock(); - if (block2.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block2 = location.getBlock(); + this.location = this.location.clone().subtract(direction); + direction = GeneralMethods.getDirection(this.location, this.destination).normalize(); + this.location = this.location.clone().add(direction); + + Block block2 = this.location.getBlock(); + if (block2.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block2 = this.location.getBlock(); } - if (isTransparent(block) && !block.isLiquid()) { + if (this.isTransparent(block) && !block.isLiquid()) { GeneralMethods.breakBlock(block); } else { - remove(); + this.remove(); return; } } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } - if (entity instanceof LivingEntity && (entity.getEntityId() != player.getEntityId() || canHitSelf)) { + + if (entity instanceof LivingEntity && (entity.getEntityId() != this.player.getEntityId() || this.canHitSelf)) { AirAbility.breakBreathbendingHold(entity); - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - entity.setVelocity(vector.normalize().multiply(pushFactor)); + final Location location = this.player.getEyeLocation(); + final Vector vector = location.getDirection(); + entity.setVelocity(vector.normalize().multiply(this.pushFactor)); double damage = this.damage; - if (isMetal(sourceBlock) && bPlayer.canMetalbend()) { + if (isMetal(this.sourceBlock) && this.bPlayer.canMetalbend()) { damage = getMetalAugment(damage); } + DamageHandler.damageEntity(entity, damage, this); - isProgressing = false; + this.isProgressing = false; } } - if (!isProgressing) { - remove(); + if (!this.isProgressing) { + this.remove(); return; } if (isEarthRevertOn()) { - sourceBlock.setType(sourceType); - sourceBlock.setData(sourceData); - if (sourceBlock.getType() == Material.RED_SANDSTONE && sourceType == Material.SAND) { - sourceBlock.setData((byte) 0x1); + this.sourceBlock.setType(this.sourceType); + this.sourceBlock.setData(this.sourceData); + if (this.sourceBlock.getType() == Material.RED_SANDSTONE && this.sourceType == Material.SAND) { + this.sourceBlock.setData((byte) 0x1); } - moveEarthBlock(sourceBlock, block); + moveEarthBlock(this.sourceBlock, block); if (block.getType() == Material.SAND) { block.setType(Material.SANDSTONE); } + if (block.getType() == Material.GRAVEL) { block.setType(Material.STONE); } } else { - block.setType(sourceType); - sourceBlock.setType(Material.AIR); + block.setType(this.sourceType); + this.sourceBlock.setType(Material.AIR); } - sourceBlock = block; + this.sourceBlock = block; - if (location.distanceSquared(destination) < 1) { - if (sourceType == Material.SAND || sourceType == Material.GRAVEL) { - isProgressing = false; - if (sourceBlock.getType() == Material.RED_SANDSTONE) { - sourceType = Material.SAND; - sourceBlock.setType(sourceType); - sourceBlock.setData((byte) 0x1); + if (this.location.distanceSquared(this.destination) < 1) { + if (this.sourceType == Material.SAND || this.sourceType == Material.GRAVEL) { + this.isProgressing = false; + if (this.sourceBlock.getType() == Material.RED_SANDSTONE) { + this.sourceType = Material.SAND; + this.sourceBlock.setType(this.sourceType); + this.sourceBlock.setData((byte) 0x1); } else { - sourceBlock.setType(sourceType); + this.sourceBlock.setType(this.sourceType); } } - isAtDestination = true; - isProgressing = false; + this.isAtDestination = true; + this.isProgressing = false; } + return; } } } - private void redirect(Player player, Location targetlocation) { - if (isProgressing) { - if (location.distanceSquared(player.getLocation()) <= range * range) { - isSettingUp = false; - destination = targetlocation; + private void redirect(final Player player, final Location targetlocation) { + if (this.isProgressing) { + if (this.location.distanceSquared(player.getLocation()) <= this.range * this.range) { + this.isSettingUp = false; + this.destination = targetlocation; } } } - @SuppressWarnings("deprecation") @Override public void remove() { super.remove(); - if (destination != null && sourceBlock != null) { - sourceBlock.setType(Material.AIR); - } else if (sourceBlock != null) { - if (sourceBlock.getType() == Material.SAND) { - if (sourceBlock.getData() == (byte) 0x1) { - sourceBlock.setType(sourceType); - sourceBlock.setData((byte) 0x1); + if (this.destination != null && this.sourceBlock != null) { + this.sourceBlock.setType(Material.AIR); + } else if (this.sourceBlock != null) { + if (this.sourceBlock.getType() == Material.SAND) { + if (this.sourceBlock.getData() == (byte) 0x1) { + this.sourceBlock.setType(this.sourceType); + this.sourceBlock.setData((byte) 0x1); } else { - sourceBlock.setType(sourceType); + this.sourceBlock.setType(this.sourceType); } } else { - sourceBlock.setType(sourceType); - sourceBlock.setData(sourceData); + this.sourceBlock.setType(this.sourceType); + this.sourceBlock.setData(this.sourceData); } } } - @SuppressWarnings("deprecation") public void throwEarth() { - if (sourceBlock == null || !sourceBlock.getWorld().equals(player.getWorld())) { + if (this.sourceBlock == null || !this.sourceBlock.getWorld().equals(this.player.getWorld())) { return; } - if (getMovedEarth().containsKey(sourceBlock)) { + if (getMovedEarth().containsKey(this.sourceBlock)) { if (!isEarthRevertOn()) { - removeRevertIndex(sourceBlock); + removeRevertIndex(this.sourceBlock); } } - Entity target = GeneralMethods.getTargetedEntity(player, range, new ArrayList()); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range, new ArrayList()); if (target == null) { - destination = getTargetEarthBlock((int) range).getLocation(); - firstDestination = sourceBlock.getLocation().clone(); - firstDestination.setY(destination.getY()); + this.destination = this.getTargetEarthBlock((int) this.range).getLocation(); + this.firstDestination = this.sourceBlock.getLocation().clone(); + this.firstDestination.setY(this.destination.getY()); } else { - destination = ((LivingEntity) target).getEyeLocation(); - firstDestination = sourceBlock.getLocation().clone(); - firstDestination.setY(destination.getY()); - destination = GeneralMethods.getPointOnLine(firstDestination, destination, range); + this.destination = ((LivingEntity) target).getEyeLocation(); + this.firstDestination = this.sourceBlock.getLocation().clone(); + this.firstDestination.setY(this.destination.getY()); + this.destination = GeneralMethods.getPointOnLine(this.firstDestination, this.destination, this.range); } - if (destination.distanceSquared(location) <= 1) { - isProgressing = false; - destination = null; + if (this.destination.distanceSquared(this.location) <= 1) { + this.isProgressing = false; + this.destination = null; } else { - isProgressing = true; - playEarthbendingSound(sourceBlock.getLocation()); + this.isProgressing = true; + playEarthbendingSound(this.sourceBlock.getLocation()); - Material currentType = sourceBlock.getType(); - sourceBlock.setType(sourceType); - sourceBlock.setData(sourceData); + final Material currentType = this.sourceBlock.getType(); + this.sourceBlock.setType(this.sourceType); + this.sourceBlock.setData(this.sourceData); if (isEarthRevertOn()) { - addTempAirBlock(sourceBlock); + addTempAirBlock(this.sourceBlock); } else { - sourceBlock.breakNaturally(); + this.sourceBlock.breakNaturally(); } - sourceBlock.setType(currentType); + + this.sourceBlock.setType(currentType); } } @@ -391,9 +410,9 @@ public void throwEarth() { * {@link Collision} for the new system. */ @Deprecated - public static boolean annihilateBlasts(Location location, double radius, Player source) { + public static boolean annihilateBlasts(final Location location, final double radius, final Player source) { boolean broke = false; - for (EarthBlast blast : getAbilities(EarthBlast.class)) { + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { if (blast.location.getWorld().equals(location.getWorld()) && !source.equals(blast.player)) { if (blast.location.distanceSquared(location) <= radius * radius) { blast.remove(); @@ -401,32 +420,35 @@ public static boolean annihilateBlasts(Location location, double radius, Player } } } + return broke; } - public static ArrayList getAroundPoint(Location location, double radius) { - ArrayList list = new ArrayList(); - for (EarthBlast blast : getAbilities(EarthBlast.class)) { + public static ArrayList getAroundPoint(final Location location, final double radius) { + final ArrayList list = new ArrayList(); + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { if (blast.location.getWorld().equals(location.getWorld())) { if (blast.location.distanceSquared(location) <= radius * radius) { list.add(blast); } } } + return list; } - public static EarthBlast getBlastFromSource(Block block) { - for (EarthBlast blast : getAbilities(EarthBlast.class)) { + public static EarthBlast getBlastFromSource(final Block block) { + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { if (blast.sourceBlock.equals(block)) { return blast; } } + return null; } - private static void redirectTargettedBlasts(Player player, ArrayList ignore) { - for (EarthBlast blast : getAbilities(EarthBlast.class)) { + private static void redirectTargettedBlasts(final Player player, final ArrayList ignore) { + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { if (!blast.isProgressing || ignore.contains(blast)) { continue; } else if (!blast.location.getWorld().equals(player.getWorld())) { @@ -437,9 +459,9 @@ private static void redirectTargettedBlasts(Player player, ArrayList blast.redirect(player, blast.getTargetLocation()); } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = blast.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = blast.location; if (mloc.distanceSquared(location) <= blast.range * blast.range && GeneralMethods.getDistanceFromLine(vector, location, blast.location) < blast.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { blast.redirect(player, blast.getTargetLocation()); @@ -448,8 +470,8 @@ private static void redirectTargettedBlasts(Player player, ArrayList } } - public static void removeAroundPoint(Location location, double radius) { - for (EarthBlast blast : getAbilities(EarthBlast.class)) { + public static void removeAroundPoint(final Location location, final double radius) { + for (final EarthBlast blast : getAbilities(EarthBlast.class)) { if (blast.location.getWorld().equals(location.getWorld())) { if (blast.location.distanceSquared(location) <= radius * radius) { blast.remove(); @@ -458,16 +480,16 @@ public static void removeAroundPoint(Location location, double radius) { } } - public static void throwEarth(Player player) { - ArrayList ignore = new ArrayList(); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void throwEarth(final Player player) { + final ArrayList ignore = new ArrayList(); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); EarthBlast earthBlast = null; if (bPlayer == null) { return; } - for (EarthBlast blast : getAbilities(player, EarthBlast.class)) { + for (final EarthBlast blast : getAbilities(player, EarthBlast.class)) { if (!blast.isProgressing && bPlayer.canBend(blast)) { blast.throwEarth(); ignore.add(blast); @@ -478,6 +500,7 @@ public static void throwEarth(Player player) { if (earthBlast != null) { bPlayer.addCooldown(earthBlast); } + redirectTargettedBlasts(player, ignore); } @@ -488,12 +511,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -508,152 +531,151 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return isProgressing; + return this.isProgressing; } @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } public boolean isProgressing() { - return isProgressing; + return this.isProgressing; } - public void setProgressing(boolean isProgressing) { + public void setProgressing(final boolean isProgressing) { this.isProgressing = isProgressing; } public boolean isAtDestination() { - return isAtDestination; + return this.isAtDestination; } - public void setAtDestination(boolean isAtDestination) { + public void setAtDestination(final boolean isAtDestination) { this.isAtDestination = isAtDestination; } public boolean isSettingUp() { - return isSettingUp; + return this.isSettingUp; } - public void setSettingUp(boolean isSettingUp) { + public void setSettingUp(final boolean isSettingUp) { this.isSettingUp = isSettingUp; } public boolean isCanHitSelf() { - return canHitSelf; + return this.canHitSelf; } - public void setCanHitSelf(boolean canHitSelf) { + public void setCanHitSelf(final boolean canHitSelf) { this.canHitSelf = canHitSelf; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public double getDeflectRange() { - return deflectRange; + return this.deflectRange; } - public void setDeflectRange(double deflectRange) { + public void setDeflectRange(final double deflectRange) { this.deflectRange = deflectRange; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } public Material getSourcetype() { - return sourceType; + return this.sourceType; } - public void setSourcetype(Material sourcetype) { + public void setSourcetype(final Material sourcetype) { this.sourceType = sourcetype; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - } diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthDome.java b/src/com/projectkorra/projectkorra/earthbending/EarthDome.java new file mode 100644 index 000000000..6526fc00a --- /dev/null +++ b/src/com/projectkorra/projectkorra/earthbending/EarthDome.java @@ -0,0 +1,116 @@ +package com.projectkorra.projectkorra.earthbending; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; + +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.EarthAbility; + +public class EarthDome extends EarthAbility { + + public Location center; + public double radius; + public int height; + public Set checked = new HashSet<>(); + public Set corners = new HashSet<>(); + + public EarthDome(final Player player, final Location center) { + super(player); + + if (this.bPlayer.isOnCooldown("EarthDome")) { + return; + } + + this.center = center; + this.radius = getConfig().getDouble("Abilities.Earth.EarthDome.Radius"); + this.height = getConfig().getInt("Abilities.Earth.EarthDome.Height"); + + for (int i = 0; i < 2; i++) { + for (final Location check : this.getCircle(center, this.radius + i, 10)) { + Block b = check.getBlock(); + if (this.checked.contains(b)) { + continue; + } + + b = this.getAppropriateBlock(b); + if (b == null) { + continue; + } + + new RaiseEarth(player, b.getLocation(), Math.round(this.height - i)); + this.checked.add(b); + } + + } + + this.bPlayer.addCooldown("EarthDome", this.getCooldown()); + } + + public EarthDome(final Player player) { + this(player, player.getLocation().clone().subtract(0, 1, 0)); + } + + private Block getAppropriateBlock(final Block block) { + if (!GeneralMethods.isSolid(block.getRelative(BlockFace.UP)) && GeneralMethods.isSolid(block)) { + return block; + } + final Block top = GeneralMethods.getTopBlock(block.getLocation(), 2); + if (GeneralMethods.isSolid(top.getRelative(BlockFace.UP))) { + return null; + } + return top; + } + + private List getCircle(final Location center, final double radius, double interval) { + final List result = new ArrayList<>(); + interval = Math.toRadians(Math.abs(interval)); + for (double theta = 0; theta < 2 * Math.PI; theta += interval) { + final double x = Math.cos(theta) * (radius + (Math.random() / 3.1)); + final double z = Math.sin(theta) * (radius + (Math.random() / 3.1)); + result.add(center.clone().add(x, 0, z)); + } + return result; + } + + @Override + public void progress() { + } + + @Override + public boolean isSneakAbility() { + return false; + } + + @Override + public boolean isHarmlessAbility() { + return false; + } + + @Override + public long getCooldown() { + return getConfig().getLong("Abilities.Earth.EarthDome.Cooldown"); + } + + @Override + public String getName() { + return "EarthDomeHidden"; + } + + @Override + public Location getLocation() { + return this.center; + } + + @Override + public boolean isHiddenAbility() { + return true; + } + +} diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthGrab.java b/src/com/projectkorra/projectkorra/earthbending/EarthGrab.java index 57fa4fe88..bcf32e237 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthGrab.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthGrab.java @@ -1,269 +1,368 @@ package com.projectkorra.projectkorra.earthbending; -import java.util.ArrayList; -import java.util.Random; +import java.util.Arrays; +import java.util.List; +import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; +import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.entity.Skeleton; +import org.bukkit.entity.Zombie; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.avatar.AvatarState; +import com.projectkorra.projectkorra.util.MovementHandler; import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.ParticleEffect.BlockData; +import com.projectkorra.projectkorra.util.TempArmor; +import com.projectkorra.projectkorra.util.TempArmorStand; +import com.projectkorra.projectkorra.util.TempBlock; public class EarthGrab extends EarthAbility { - private long cooldown; - private double lowestDistance; - private double selectRange; - private int height; - private int radius; + private LivingEntity target; + private long cooldown, lastHit = 0, interval; + private double range, dragSpeed, trapHP, trappedHP, damageThreshold; + private GrabMode mode; + private boolean initiated = false; + private MovementHandler mHandler; + private ArmorStand trap; private Location origin; private Vector direction; - private Entity closestEntity; - private Location startLoc; - private Location loc; - private Vector dir; - private Block groundBlock; - private Material blockType; - private Byte blockByte; - private Random random; - - public EarthGrab(Player player) { + private TempArmor armor; + private final Material[] crops = new Material[] { Material.BEETROOT_BLOCK, Material.CARROT, Material.POTATO, Material.SUGAR_CANE_BLOCK, Material.CROPS, Material.MELON_BLOCK, Material.PUMPKIN }; + + public static enum GrabMode { + TRAP, DRAG, PROJECTING; + } + + public EarthGrab(final Player player, final GrabMode mode) { super(player); - this.selectRange = getConfig().getDouble("Abilities.Earth.EarthGrab.SelectRange"); - this.height = getConfig().getInt("Abilities.Earth.EarthGrab.Height"); - this.cooldown = getConfig().getLong("Abilities.Earth.EarthGrab.Cooldown"); - this.radius = getConfig().getInt("Abilities.Earth.EarthGrab.Radius"); - this.origin = player.getEyeLocation(); - this.direction = origin.getDirection(); - this.lowestDistance = selectRange + 1; - this.closestEntity = null; - this.startLoc = player.getLocation(); - this.loc = player.getLocation(); - this.dir = player.getLocation().getDirection().clone().normalize().multiply(1.5); - this.random = new Random(); - - if (!bPlayer.canBend(this)) { - return; - } else if (player.getLocation().clone().add(0, -1, 0).getBlock().getType().isTransparent()) { + if (hasAbility(player, EarthGrab.class)) { + getAbility(player, EarthGrab.class).remove(); return; } - if (bPlayer.isAvatarState()) { - this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthGrab.Cooldown"); - this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.EarthGrab.Height"); - this.radius = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.EarthGrab.Radius"); + if (this.bPlayer.isOnCooldown(this)) { + return; } - if (player.isSneaking()) { - start(); - } else { - Location targetLocation = GeneralMethods.getTargetedLocation(player, 1); - Block block = GeneralMethods.getTopBlock(targetLocation, 1, 1); - if (isEarthbendable(block) && block.getWorld().equals(player.getWorld()) && block.getLocation().distance(player.getLocation()) <= 1.6) { - earthGrabSelf(); - remove(); - } + if (!this.isEarthbendable(player.getLocation().getBlock().getRelative(BlockFace.DOWN))) { + return; } + + this.mode = mode; + this.setFields(); + this.start(); } - public void formDome() { - if (closestEntity != null) { - ArrayList blocks = new ArrayList(); - Location location = closestEntity.getLocation().clone().subtract(0, 1, 0); - location.setPitch(0); - for (float theta = -180; theta < 180; theta += 1) { - Location loc = location.clone(); - loc.setYaw(theta); - Vector dir = loc.getDirection(); - Block a = GeneralMethods.getTopBlock(loc.add(dir.clone().multiply(radius)), height/2); - while (!GeneralMethods.isSolid(a) && !isEarthbendable(a.getType(), true, true, false) && a.getY() > 0 && a.getY() < 256) { - a = a.getRelative(BlockFace.DOWN); - } - if (!blocks.contains(a)) { - blocks.add(a); - new RaiseEarth(player, a.getLocation(), (int) height); - } - - Block b = GeneralMethods.getTopBlock(loc.add(dir.clone().multiply(1)), height/2); - while (!GeneralMethods.isSolid(b) && !isEarthbendable(b.getType(), true, true, false) && b.getY() > 0 && b.getY() < 256) { - b = b.getRelative(BlockFace.DOWN); - } - if (!blocks.contains(b)) { - blocks.add(b); - new RaiseEarth(player, b.getLocation(), (int) height/2); + private void setFields() { + this.range = getConfig().getDouble("Abilities.Earth.EarthGrab.Range"); + this.cooldown = getConfig().getLong("Abilities.Earth.EarthGrab.Cooldown"); + this.dragSpeed = getConfig().getDouble("Abilities.Earth.EarthGrab.DragSpeed"); + this.interval = getConfig().getLong("Abilities.Earth.EarthGrab.TrapHitInterval"); + this.trapHP = getConfig().getDouble("Abilities.Earth.EarthGrab.TrapHP"); + this.damageThreshold = getConfig().getDouble("Abilities.Earth.EarthGrab.DamageThreshold"); + this.origin = this.player.getLocation().clone(); + this.direction = this.player.getLocation().getDirection().setY(0).normalize(); + } + + @Override + public void progress() { + if (!this.player.isOnline() || this.player.isDead()) { + this.remove(); + return; + } + + if (this.target != null) { + if (this.target instanceof Player) { + final Player pt = (Player) this.target; + if (!pt.isOnline()) { + this.remove(); + return; } } - bPlayer.addCooldown(this); + if (this.target.isDead()) { + this.remove(); + return; + } } - } - public void earthGrabSelf() { - closestEntity = player; - getGround(); - ParticleEffect.BLOCK_CRACK.display((ParticleEffect.ParticleData) new ParticleEffect.BlockData(blockType, blockByte), 1F, 1F, 1F, 0.1F, 100, player.getLocation(), 500); - formDome(); + switch (this.mode) { + case PROJECTING: + this.project(); + break; + case TRAP: + this.trap(); + break; + case DRAG: + this.drag(); + break; + } } - @Override - public String getName() { - return "EarthGrab"; - } + public void project() { + this.origin = this.origin.add(this.direction); + Block top = GeneralMethods.getTopBlock(this.origin, 2); + if (this.origin.distance(this.player.getLocation()) > this.range) { + this.remove(); + return; + } - @SuppressWarnings("deprecation") - private Block getGround() { - Block b = GeneralMethods.getTopBlock(loc, 3); - if (isEarthbendable(b)) { - blockType = b.getType(); - blockByte = b.getData(); - return b; - } else { - while (!isEarthbendable(b)) { - b = b.getRelative(BlockFace.DOWN); - if (player.getLocation().getBlockY() - b.getY() > 5) { - break; - } + if (!this.isTransparent(top.getRelative(BlockFace.UP))) { + this.remove(); + return; + } + + if (top.getType() == Material.FIRE) { + top.setType(Material.AIR); + } + + while (!this.isEarthbendable(top)) { + if (this.isTransparent(top)) { + top = top.getRelative(BlockFace.DOWN); + } else { + this.remove(); + return; } - if (isEarthbendable(b)) { - blockType = b.getType(); - blockByte = b.getData(); - return b; + } + + if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.origin)) { + this.remove(); + return; + } + + this.origin.setY(top.getY() + 1); + + ParticleEffect.BLOCK_DUST.display(new BlockData(this.origin.getBlock().getRelative(BlockFace.DOWN).getType(), (byte) 0), 0.2f, 0.5f, 0.2f, 0, 27, this.origin, 256); + playEarthbendingSound(this.origin); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.origin, 1)) { + if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId() && this.isEarthbendable(entity.getLocation().getBlock().getRelative(BlockFace.DOWN))) { + if (entity instanceof Player && BendingPlayer.getBendingPlayer((Player) entity) != null) { + if (CoreAbility.hasAbility((Player) entity, AvatarState.class)) { + continue; + } + } + this.target = (LivingEntity) entity; + this.trappedHP = this.target.getHealth(); + this.mode = GrabMode.TRAP; + this.origin = this.target.getLocation().clone(); } } - return null; } - @Override - public void progress() { - groundBlock = getGround(); - if (groundBlock == null) { - remove(); - return; + public void trap() { + if (!this.initiated) { + final Material m = this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(); + final TempArmorStand tas = new TempArmorStand(this.target.getLocation()); + this.trap = tas.getArmorStand(); + this.trap.setVisible(false); + this.trap.setInvulnerable(false); + this.trap.setSmall(true); + this.trap.setHelmet(new ItemStack(m)); + this.trap.setHealth(this.trapHP); + this.trap.setMetadata("earthgrab:trap", new FixedMetadataValue(ProjectKorra.plugin, this)); + + new TempBlock(this.target.getLocation().clone().subtract(0, 1, 0).getBlock(), this.target.getLocation().clone().subtract(0, 1, 0).getBlock().getType(), (byte) 0); + + this.mHandler = new MovementHandler(this.target, this); + this.mHandler.stop(Element.EARTH.getColor() + "* Trapped *"); + + if (this.target instanceof Player || this.target instanceof Zombie || this.target instanceof Skeleton) { + final ItemStack legs = new ItemStack(Material.LEATHER_LEGGINGS); + final LeatherArmorMeta legmeta = (LeatherArmorMeta) legs.getItemMeta(); + legmeta.setColor(Color.fromRGB(EarthArmor.getColor(m))); + legs.setItemMeta(legmeta); + + final ItemStack feet = new ItemStack(Material.LEATHER_BOOTS); + final LeatherArmorMeta footmeta = (LeatherArmorMeta) feet.getItemMeta(); + footmeta.setColor(Color.fromRGB(EarthArmor.getColor(m))); + feet.setItemMeta(footmeta); + + final ItemStack[] pieces = { (this.target.getEquipment().getArmorContents()[0] == null || this.target.getEquipment().getArmorContents()[0].getType() == Material.AIR) ? feet : null, (this.target.getEquipment().getArmorContents()[1] == null || this.target.getEquipment().getArmorContents()[1].getType() == Material.AIR) ? legs : null, null, null }; + this.armor = new TempArmor(this.target, 36000000L, this, pieces); + } + + playEarthbendingSound(this.target.getLocation()); + this.initiated = true; } - bPlayer.addCooldown(this); - dir = dir.clone().normalize().multiply(1.5); - dir.setY(0); - double distance = loc.getY() - (double) groundBlock.getY(); - double dx = Math.abs(distance - 2.4); - if (distance > 1.75) { - dir.setY(-.50 * dx * dx); - } else if (distance < 1) { - dir.setY(.50 * dx * dx); + + ParticleEffect.BLOCK_DUST.display(new BlockData(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(), (byte) 0), 0.3f, 0.6f, 0.3f, 0, 36, this.target.getLocation(), 256); + + if (this.trap.getLocation().clone().subtract(0, 0.1, 0).getBlock().getType() != Material.AIR) { + this.trap.setGravity(false); } else { - dir.setY(0); + this.trap.setGravity(true); } - loc.add(dir); - if (player.isDead() || !player.isOnline()) { - remove(); + + if (!this.isEarthbendable(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN))) { + this.remove(); return; } - if (!player.isSneaking()) { - remove(); + + if (this.trap.getLocation().distance(this.target.getLocation()) > 2) { + this.remove(); return; } - if (loc.getWorld().equals(startLoc.getWorld()) && loc.distance(startLoc) >= selectRange) { - remove(); + + if (this.trappedHP - this.target.getHealth() >= this.damageThreshold) { + this.remove(); return; } - if (blockType == null) { + + if (this.trapHP <= 0) { + this.remove(); return; - } else if (blockByte == null) { + } + + if (this.trap.isDead()) { + this.remove(); return; } - ParticleEffect.BLOCK_CRACK.display((ParticleEffect.ParticleData) new ParticleEffect.BlockData(blockType, blockByte), 1F, 0.1F, 1F, 0.1F, 100, loc.add(0, -1, 0), 500); - for (Entity e : GeneralMethods.getEntitiesAroundPoint(loc, 2.5)) { - if (e.getEntityId() != player.getEntityId() && e instanceof LivingEntity) { - closestEntity = e; - formDome(); - remove(); - return; - } + if (this.player.getLocation().distance(this.target.getLocation()) > this.range) { + this.remove(); + return; } - if (random.nextInt(2) == 0) { - playEarthbendingSound(loc); + + if (!GeneralMethods.isSolid(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN))) { + this.remove(); + return; } + if (GeneralMethods.isSolid(this.target.getLocation().getBlock())) { + this.remove(); + return; + } } - @Override - public Location getLocation() { - return origin; - } + public void drag() { + if (!this.player.isOnGround()) { + return; + } - @Override - public long getCooldown() { - return cooldown; - } + if (!this.player.isSneaking()) { + this.remove(); + return; + } - @Override - public boolean isSneakAbility() { - return true; - } + if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.player.getLocation())) { + this.remove(); + return; + } - @Override - public boolean isHarmlessAbility() { - return false; - } + for (final Location l : GeneralMethods.getCircle(this.player.getLocation(), (int) Math.floor(this.range), 2, false, false, 0)) { + if (!Arrays.asList(this.crops).contains(l.getBlock().getType())) { + continue; + } - public double getLowestDistance() { - return lowestDistance; - } + final Block b = l.getBlock(); + if (b.getData() == (byte) 7 || b.getType() == Material.MELON_BLOCK || b.getType() == Material.PUMPKIN) { + b.breakNaturally(); + } + } - public void setLowestDistance(double lowestDistance) { - this.lowestDistance = lowestDistance; - } + final List ents = GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.range); + if (ents.isEmpty()) { + this.remove(); + return; + } - public double getRange() { - return selectRange; - } + for (Entity entity : ents) { + if (!isEarth(entity.getLocation().clone().subtract(0, 1, 0).getBlock()) && (this.bPlayer.canSandbend() && !isSand(entity.getLocation().clone().subtract(0, 1, 0).getBlock())) && entity.getLocation().clone().subtract(0, 1, 0).getBlock().getType() != Material.SOIL) { + continue; + } - public void setRange(double range) { - this.selectRange = range; + if (entity instanceof Arrow) { + final Location l = entity.getLocation(); + entity.remove(); + entity = l.getWorld().dropItem(l, new ItemStack(Material.ARROW, 1)); + } else if (!(entity instanceof Item)) { + continue; + } + final Block b = entity.getLocation().getBlock().getRelative(BlockFace.DOWN); + entity.setVelocity(GeneralMethods.getDirection(entity.getLocation(), this.player.getLocation()).normalize().multiply(this.dragSpeed)); + ParticleEffect.BLOCK_CRACK.display(new BlockData(b.getType(), b.getData()), 0, 0, 0, 0, 1, entity.getLocation(), 256); + playEarthbendingSound(entity.getLocation()); + } } - public int getHeight() { - return height; + public void damageTrap() { + if (System.currentTimeMillis() >= this.lastHit + this.interval) { + this.trapHP -= 1; + this.lastHit = System.currentTimeMillis(); + ParticleEffect.BLOCK_CRACK.display(new BlockData(this.target.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(), (byte) 0), 0.1f, 0.5f, 0.1f, 0, 17, this.target.getLocation().clone().add(0, 1, 0), 256); + playEarthbendingSound(this.target.getLocation()); + } } - public void setHeight(int height) { - this.height = height; + @Override + public void remove() { + super.remove(); + if (this.mode == GrabMode.TRAP) { + this.bPlayer.addCooldown(this); + this.mHandler.reset(); + this.trap.remove(); + if (TempArmor.getTempArmorList(this.target).contains(this.armor)) { + this.armor.revert(); + } + } + this.bPlayer.addCooldown(this); } - public Location getOrigin() { - return origin; + @Override + public boolean isSneakAbility() { + return true; } - public void setOrigin(Location origin) { - this.origin = origin; + @Override + public boolean isHarmlessAbility() { + return false; } - public Vector getDirection() { - return direction; + @Override + public long getCooldown() { + return this.cooldown; } - public void setDirection(Vector direction) { - this.direction = direction; + @Override + public String getName() { + return "EarthGrab"; } - public Entity getClosestEntity() { - return closestEntity; + @Override + public Location getLocation() { + return this.target == null ? null : this.target.getLocation(); } - public void setClosestEntity(Entity closestEntity) { - this.closestEntity = closestEntity; + public GrabMode getMode() { + return this.mode; } - public void setCooldown(long cooldown) { - this.cooldown = cooldown; + public double getRange() { + return this.range; } -} \ No newline at end of file + public LivingEntity getTarget() { + return this.target; + } +} diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java b/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java index 7da1c4c91..1e0e3a8b6 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java @@ -13,6 +13,7 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.util.ClickType; @@ -59,61 +60,33 @@ public static enum State { private ArrayList currentBlocks; private ArrayList affectedBlocks; - public EarthSmash(Player player, ClickType type) { + public EarthSmash(final Player player, final ClickType type) { super(player); this.state = State.START; this.requiredBendableBlocks = getConfig().getInt("Abilities.Earth.EarthSmash.RequiredBendableBlocks"); this.maxBlocksToPassThrough = getConfig().getInt("Abilities.Earth.EarthSmash.MaxBlocksToPassThrough"); - this.shootAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.ShootAnimationInterval"); - this.flightAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.FlightAnimationInterval"); - this.liftAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.LiftAnimationInterval"); - this.grabDetectionRadius = getConfig().getDouble("Abilities.Earth.EarthSmash.GrabDetectionRadius"); - this.flightDetectionRadius = getConfig().getDouble("Abilities.Earth.EarthSmash.FlightDetectionRadius"); - this.allowGrab = getConfig().getBoolean("Abilities.Earth.EarthSmash.AllowGrab"); - this.allowFlight = getConfig().getBoolean("Abilities.Earth.EarthSmash.AllowFlight"); - this.selectRange = getConfig().getDouble("Abilities.Earth.EarthSmash.SelectRange"); - this.grabRange = getConfig().getDouble("Abilities.Earth.EarthSmash.GrabRange"); - this.shootRange = getConfig().getDouble("Abilities.Earth.EarthSmash.ShootRange"); - this.damage = getConfig().getDouble("Abilities.Earth.EarthSmash.Damage"); - this.knockback = getConfig().getDouble("Abilities.Earth.EarthSmash.Knockback"); - this.knockup = getConfig().getDouble("Abilities.Earth.EarthSmash.Knockup"); - this.flightSpeed = getConfig().getDouble("Abilities.Earth.EarthSmash.FlightSpeed"); - this.chargeTime = getConfig().getLong("Abilities.Earth.EarthSmash.ChargeTime"); - this.cooldown = getConfig().getLong("Abilities.Earth.EarthSmash.Cooldown"); - this.flightRemoveTimer = getConfig().getLong("Abilities.Earth.EarthSmash.FlightTimer"); - this.removeTimer = getConfig().getLong("Abilities.Earth.EarthSmash.RemoveTimer"); + this.setFields(); this.affectedEntities = new ArrayList<>(); this.currentBlocks = new ArrayList<>(); this.affectedBlocks = new ArrayList<>(); if (type == ClickType.SHIFT_DOWN || type == ClickType.SHIFT_UP && !player.isSneaking()) { - if (bPlayer.isAvatarState()) { - this.selectRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.SelectRange"); - this.grabRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.GrabRange"); - this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.ChargeTime"); - this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.Cooldown"); - this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Damage"); - this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Knockback"); - this.flightSpeed = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightSpeed"); - this.flightRemoveTimer = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightTimer"); - this.shootRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.ShootRange"); - } - - EarthSmash flySmash = flyingInSmashCheck(player); + final EarthSmash flySmash = flyingInSmashCheck(player); if (flySmash != null) { flySmash.state = State.FLYING; flySmash.player = player; + flySmash.setFields(); flySmash.flightStartTime = System.currentTimeMillis(); return; } - EarthSmash grabbedSmash = aimingAtSmashCheck(player, State.LIFTED); + EarthSmash grabbedSmash = this.aimingAtSmashCheck(player, State.LIFTED); if (grabbedSmash == null) { - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } - grabbedSmash = aimingAtSmashCheck(player, State.SHOT); + grabbedSmash = this.aimingAtSmashCheck(player, State.SHOT); } if (grabbedSmash != null) { @@ -123,12 +96,13 @@ public EarthSmash(Player player, ClickType type) { grabbedSmash.grabbedDistance = grabbedSmash.location.distance(player.getEyeLocation()); } grabbedSmash.player = player; + grabbedSmash.setFields(); return; } - start(); + this.start(); } else if (type == ClickType.LEFT_CLICK && player.isSneaking()) { - for (EarthSmash smash : getAbilities(EarthSmash.class)) { + for (final EarthSmash smash : getAbilities(EarthSmash.class)) { if (smash.state == State.GRABBED && smash.player == player) { smash.state = State.SHOT; smash.destination = player.getEyeLocation().clone().add(player.getEyeLocation().getDirection().normalize().multiply(smash.shootRange)); @@ -137,149 +111,184 @@ public EarthSmash(Player player, ClickType type) { } return; } else if (type == ClickType.RIGHT_CLICK && player.isSneaking()) { - EarthSmash grabbedSmash = aimingAtSmashCheck(player, State.GRABBED); + final EarthSmash grabbedSmash = this.aimingAtSmashCheck(player, State.GRABBED); if (grabbedSmash != null) { player.teleport(grabbedSmash.location.clone().add(0, 2, 0)); grabbedSmash.state = State.FLYING; grabbedSmash.player = player; + grabbedSmash.setFields(); grabbedSmash.flightStartTime = System.currentTimeMillis(); } return; } } + public void setFields() { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(this.player); + this.shootAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.ShootAnimationInterval"); + this.flightAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.FlightAnimationInterval"); + this.liftAnimationInterval = getConfig().getLong("Abilities.Earth.EarthSmash.LiftAnimationInterval"); + this.grabDetectionRadius = getConfig().getDouble("Abilities.Earth.EarthSmash.GrabDetectionRadius"); + this.flightDetectionRadius = getConfig().getDouble("Abilities.Earth.EarthSmash.FlightDetectionRadius"); + this.allowGrab = getConfig().getBoolean("Abilities.Earth.EarthSmash.AllowGrab"); + this.allowFlight = getConfig().getBoolean("Abilities.Earth.EarthSmash.AllowFlight"); + this.selectRange = getConfig().getDouble("Abilities.Earth.EarthSmash.SelectRange"); + this.grabRange = getConfig().getDouble("Abilities.Earth.EarthSmash.GrabRange"); + this.shootRange = getConfig().getDouble("Abilities.Earth.EarthSmash.ShootRange"); + this.damage = getConfig().getDouble("Abilities.Earth.EarthSmash.Damage"); + this.knockback = getConfig().getDouble("Abilities.Earth.EarthSmash.Knockback"); + this.knockup = getConfig().getDouble("Abilities.Earth.EarthSmash.Knockup"); + this.flightSpeed = getConfig().getDouble("Abilities.Earth.EarthSmash.FlightSpeed"); + this.chargeTime = getConfig().getLong("Abilities.Earth.EarthSmash.ChargeTime"); + this.cooldown = getConfig().getLong("Abilities.Earth.EarthSmash.Cooldown"); + this.flightRemoveTimer = getConfig().getLong("Abilities.Earth.EarthSmash.FlightTimer"); + this.removeTimer = getConfig().getLong("Abilities.Earth.EarthSmash.RemoveTimer"); + + if (bPlayer.isAvatarState()) { + this.selectRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.SelectRange"); + this.grabRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.GrabRange"); + this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.ChargeTime"); + this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.Cooldown"); + this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Damage"); + this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Knockback"); + this.flightSpeed = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightSpeed"); + this.flightRemoveTimer = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightTimer"); + this.shootRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.ShootRange"); + } + } + @Override public void progress() { - progressCounter++; - if (state == State.LIFTED && removeTimer > 0 && System.currentTimeMillis() - getStartTime() > removeTimer) { - remove(); + this.progressCounter++; + if (this.state == State.LIFTED && this.removeTimer > 0 && System.currentTimeMillis() - this.getStartTime() > this.removeTimer) { + this.remove(); return; } - if (state == State.START) { - if (!bPlayer.canBend(this)) { - remove(); + if (this.state == State.START) { + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } - } else if (state == State.START || state == State.FLYING || state == State.GRABBED) { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + } else if (this.state == State.START || this.state == State.FLYING || this.state == State.GRABBED) { + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } } - if (state == State.START && progressCounter > 1) { - if (!player.isSneaking()) { - if (System.currentTimeMillis() - getStartTime() >= chargeTime) { - origin = getEarthSourceBlock(selectRange); - if (origin == null) { - remove(); + if (this.state == State.START && this.progressCounter > 1) { + if (!this.player.isSneaking()) { + if (System.currentTimeMillis() - this.getStartTime() >= this.chargeTime) { + this.origin = this.getEarthSourceBlock(this.selectRange); + if (this.origin == null) { + this.remove(); return; } - bPlayer.addCooldown(this); - location = origin.getLocation(); - state = State.LIFTING; + this.bPlayer.addCooldown(this); + this.location = this.origin.getLocation(); + this.state = State.LIFTING; } else { - remove(); + this.remove(); return; } - } else if (System.currentTimeMillis() - getStartTime() > chargeTime) { - Location tempLoc = player.getEyeLocation().add(player.getEyeLocation().getDirection().normalize().multiply(1.2)); + } else if (System.currentTimeMillis() - this.getStartTime() > this.chargeTime) { + final Location tempLoc = this.player.getEyeLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(1.2)); tempLoc.add(0, 0.3, 0); ParticleEffect.SMOKE.display(tempLoc, 0.3F, 0.1F, 0.3F, 0, 4); } - } else if (state == State.LIFTING) { - if (System.currentTimeMillis() - delay >= liftAnimationInterval) { - delay = System.currentTimeMillis(); - animateLift(); + } else if (this.state == State.LIFTING) { + if (System.currentTimeMillis() - this.delay >= this.liftAnimationInterval) { + this.delay = System.currentTimeMillis(); + this.animateLift(); } - } else if (state == State.GRABBED) { - if (player.isSneaking()) { - revert(); - Location oldLoc = location.clone(); - location = player.getEyeLocation().add(player.getEyeLocation().getDirection().normalize().multiply(grabbedDistance)); - - // Check to make sure the new location is available to move to - for (Block block : getBlocks()) { - if (block.getType() != Material.AIR && !isTransparent(block)) { - location = oldLoc; + } else if (this.state == State.GRABBED) { + if (this.player.isSneaking()) { + this.revert(); + final Location oldLoc = this.location.clone(); + this.location = this.player.getEyeLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(this.grabbedDistance)); + + // Check to make sure the new location is available to move to. + for (final Block block : this.getBlocks()) { + if (block.getType() != Material.AIR && !this.isTransparent(block)) { + this.location = oldLoc; break; } } - draw(); + this.draw(); return; } else { - state = State.LIFTED; + this.state = State.LIFTED; return; } - } else if (state == State.SHOT) { - if (System.currentTimeMillis() - delay >= shootAnimationInterval) { - delay = System.currentTimeMillis(); - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + } else if (this.state == State.SHOT) { + if (System.currentTimeMillis() - this.delay >= this.shootAnimationInterval) { + this.delay = System.currentTimeMillis(); + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } - revert(); - location.add(GeneralMethods.getDirection(location, destination).normalize().multiply(1)); - if (location.distanceSquared(destination) < 4) { - remove(); + this.revert(); + this.location.add(GeneralMethods.getDirection(this.location, this.destination).normalize().multiply(1)); + if (this.location.distanceSquared(this.destination) < 4) { + this.remove(); return; } - // If an earthsmash runs into too many blocks we should remove it + // If an earthsmash runs into too many blocks we should remove it. int badBlocksFound = 0; - for (Block block : getBlocks()) { - if (block.getType() != Material.AIR && (!isTransparent(block) || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER)) { + for (final Block block : this.getBlocks()) { + if (block.getType() != Material.AIR && (!this.isTransparent(block) || block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER)) { badBlocksFound++; } } - if (badBlocksFound > maxBlocksToPassThrough) { - remove(); + if (badBlocksFound > this.maxBlocksToPassThrough) { + this.remove(); return; } - shootingCollisionDetection(); - draw(); - smashToSmashCollisionDetection(); + this.shootingCollisionDetection(); + this.draw(); + this.smashToSmashCollisionDetection(); } return; - } else if (state == State.FLYING) { - if (!player.isSneaking()) { - remove(); + } else if (this.state == State.FLYING) { + if (!this.player.isSneaking()) { + this.remove(); return; - } else if (System.currentTimeMillis() - delay >= flightAnimationInterval) { - delay = System.currentTimeMillis(); - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + } else if (System.currentTimeMillis() - this.delay >= this.flightAnimationInterval) { + this.delay = System.currentTimeMillis(); + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } - revert(); - destination = player.getEyeLocation().clone().add(player.getEyeLocation().getDirection().normalize().multiply(shootRange)); - Vector direction = GeneralMethods.getDirection(location, destination).normalize(); + this.revert(); + this.destination = this.player.getEyeLocation().clone().add(this.player.getEyeLocation().getDirection().normalize().multiply(this.shootRange)); + final Vector direction = GeneralMethods.getDirection(this.location, this.destination).normalize(); - List entities = GeneralMethods.getEntitiesAroundPoint(location.clone().add(0, 2, 0), flightDetectionRadius); + final List entities = GeneralMethods.getEntitiesAroundPoint(this.location.clone().add(0, 2, 0), this.flightDetectionRadius); if (entities.size() == 0) { - remove(); + this.remove(); return; } - for (Entity entity : entities) { - entity.setVelocity(direction.clone().multiply(flightSpeed)); + for (final Entity entity : entities) { + entity.setVelocity(direction.clone().multiply(this.flightSpeed)); } // These values tend to work well when dealing with a person aiming upward or downward. if (direction.getY() < -0.35) { - location = player.getLocation().clone().add(0, -3.2, 0); + this.location = this.player.getLocation().clone().add(0, -3.2, 0); } else if (direction.getY() > 0.35) { - location = player.getLocation().clone().add(0, -1.7, 0); + this.location = this.player.getLocation().clone().add(0, -1.7, 0); } else { - location = player.getLocation().clone().add(0, -2.2, 0); + this.location = this.player.getLocation().clone().add(0, -2.2, 0); } - draw(); + this.draw(); } - if (System.currentTimeMillis() - flightStartTime > flightRemoveTimer) { - remove(); + if (System.currentTimeMillis() - this.flightStartTime > this.flightRemoveTimer) { + this.remove(); return; } } @@ -292,67 +301,66 @@ public void progress() { * there is a clear path for the EarthSmash to rise, and that there is * enough Earthbendable material for it to be created. */ - @SuppressWarnings("deprecation") public void animateLift() { - if (animationCounter < 4) { - revert(); - location.add(0, 1, 0); - //Remove the blocks underneath the rising smash - if (animationCounter == 0) { - //Check all of the blocks and make sure that they can be removed AND make sure there is enough dirt + if (this.animationCounter < 4) { + this.revert(); + this.location.add(0, 1, 0); + // Remove the blocks underneath the rising smash. + if (this.animationCounter == 0) { + // Check all of the blocks and make sure that they can be removed AND make sure there is enough dirt. int totalBendableBlocks = 0; for (int x = -1; x <= 1; x++) { for (int y = -2; y <= -1; y++) { for (int z = -1; z <= 1; z++) { - Block block = location.clone().add(x, y, z).getBlock(); + final Block block = this.location.clone().add(x, y, z).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - remove(); + this.remove(); return; } - if (isEarthbendable(block)) { + if (this.isEarthbendable(block)) { totalBendableBlocks++; } } } } - if (totalBendableBlocks < requiredBendableBlocks) { - remove(); + if (totalBendableBlocks < this.requiredBendableBlocks) { + this.remove(); return; } - //Make sure there is a clear path upward otherwise remove + // Make sure there is a clear path upward otherwise remove. for (int y = 0; y <= 3; y++) { - Block tempBlock = location.clone().add(0, y, 0).getBlock(); - if (!isTransparent(tempBlock) && tempBlock.getType() != Material.AIR) { - remove(); + final Block tempBlock = this.location.clone().add(0, y, 0).getBlock(); + if (!this.isTransparent(tempBlock) && tempBlock.getType() != Material.AIR) { + this.remove(); return; } } - //Design what this EarthSmash looks like by using BlockRepresenters - Location tempLoc = location.clone().add(0, -2, 0); + // Design what this EarthSmash looks like by using BlockRepresenters. + final Location tempLoc = this.location.clone().add(0, -2, 0); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { if ((Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2 == 0) { - Block block = tempLoc.clone().add(x, y, z).getBlock(); - currentBlocks.add(new BlockRepresenter(x, y, z, selectMaterialForRepresenter(block.getType()), block.getData())); + final Block block = tempLoc.clone().add(x, y, z).getBlock(); + this.currentBlocks.add(new BlockRepresenter(x, y, z, this.selectMaterialForRepresenter(block.getType()), block.getData())); } } } } - //Remove the design of the second level of removed dirt + // Remove the design of the second level of removed dirt. for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { if ((Math.abs(x) + Math.abs(z)) % 2 == 1) { - Block block = location.clone().add(x, -2, z).getBlock(); - if (isEarthbendable(block)) { + final Block block = this.location.clone().add(x, -2, z).getBlock(); + if (this.isEarthbendable(block)) { addTempAirBlock(block); } } - //Remove the first level of dirt - Block block = location.clone().add(x, -1, z).getBlock(); - if (isEarthbendable(block)) { + // Remove the first level of dirt. + final Block block = this.location.clone().add(x, -1, z).getBlock(); + if (this.isEarthbendable(block)) { addTempAirBlock(block); } } @@ -364,50 +372,50 @@ public void animateLift() { * want to animate it starting from the original bending block. * We must readjust the location back to what it originally was. */ - location.add(0, -1, 0); + this.location.add(0, -1, 0); } - //Move any entities that are above the rock - List entities = GeneralMethods.getEntitiesAroundPoint(location, 2.5); - for (Entity entity : entities) { - org.bukkit.util.Vector velocity = entity.getVelocity(); + // Move any entities that are above the rock. + final List entities = GeneralMethods.getEntitiesAroundPoint(this.location, 2.5); + for (final Entity entity : entities) { + final org.bukkit.util.Vector velocity = entity.getVelocity(); entity.setVelocity(velocity.add(new Vector(0, 0.36, 0))); } - location.getWorld().playEffect(location, Effect.GHAST_SHOOT, 0, 7); - draw(); + this.location.getWorld().playEffect(this.location, Effect.GHAST_SHOOT, 0, 7); + this.draw(); } else { - state = State.LIFTED; + this.state = State.LIFTED; } - animationCounter++; + this.animationCounter++; } /** * Redraws the blocks for this instance of EarthSmash. */ public void draw() { - if (currentBlocks.size() == 0) { - remove(); + if (this.currentBlocks.size() == 0) { + this.remove(); return; } - for (BlockRepresenter blockRep : currentBlocks) { - Block block = location.clone().add(blockRep.getX(), blockRep.getY(), blockRep.getZ()).getBlock(); - if (block.getType().equals(Material.SAND) || block.getType().equals(Material.GRAVEL)) { //Check if block can be affected by gravity. + for (final BlockRepresenter blockRep : this.currentBlocks) { + final Block block = this.location.clone().add(blockRep.getX(), blockRep.getY(), blockRep.getZ()).getBlock(); + if (block.getType().equals(Material.SAND) || block.getType().equals(Material.GRAVEL)) { // Check if block can be affected by gravity. } - if (player != null && isTransparent(block)) { - affectedBlocks.add(new TempBlock(block, blockRep.getType(), blockRep.getData())); + if (this.player != null && this.isTransparent(block)) { + this.affectedBlocks.add(new TempBlock(block, blockRep.getType(), blockRep.getData())); getPreventEarthbendingBlocks().add(block); } } } public void revert() { - checkRemainingBlocks(); - for (int i = 0; i < affectedBlocks.size(); i++) { - TempBlock tblock = affectedBlocks.get(i); + this.checkRemainingBlocks(); + for (int i = 0; i < this.affectedBlocks.size(); i++) { + final TempBlock tblock = this.affectedBlocks.get(i); getPreventEarthbendingBlocks().remove(tblock.getBlock()); tblock.revertBlock(); - affectedBlocks.remove(i); + this.affectedBlocks.remove(i); i--; } } @@ -416,27 +424,28 @@ public void revert() { * Checks to see which of the blocks are still attached to the EarthSmash, * remember that blocks can be broken or used in other abilities so we need * to double check and remove any that are not still attached. - * + * * Also when we remove the blocks from instances, movedearth, or tempair we * should do it on a delay because tempair takes a couple seconds before the * block shows up in that map. */ public void checkRemainingBlocks() { - for (int i = 0; i < currentBlocks.size(); i++) { - BlockRepresenter brep = currentBlocks.get(i); - final Block block = location.clone().add(brep.getX(), brep.getY(), brep.getZ()).getBlock(); + for (int i = 0; i < this.currentBlocks.size(); i++) { + final BlockRepresenter brep = this.currentBlocks.get(i); + final Block block = this.location.clone().add(brep.getX(), brep.getY(), brep.getZ()).getBlock(); // Check for grass because sometimes the dirt turns into grass. if (block.getType() != brep.getType() && (block.getType() != Material.GRASS) && (block.getType() != Material.COBBLESTONE)) { - currentBlocks.remove(i); + this.currentBlocks.remove(i); i--; } } } + @Override public void remove() { super.remove(); - state = State.REMOVED; - revert(); + this.state = State.REMOVED; + this.revert(); } /** @@ -444,13 +453,13 @@ public void remove() { * blocks that should be Air, and only returns the ones that are dirt. */ public List getBlocks() { - List blocks = new ArrayList(); + final List blocks = new ArrayList(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { - if ((Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2 == 0) { //Give it the cool shape - if (location != null) { - blocks.add(location.getWorld().getBlockAt(location.clone().add(x, y, z))); + if ((Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2 == 0) { // Give it the cool shape. + if (this.location != null) { + blocks.add(this.location.getWorld().getBlockAt(this.location.clone().add(x, y, z))); } } } @@ -464,12 +473,12 @@ public List getBlocks() { * the blocks surrounding the loc, including dirt and air. */ public List getBlocksIncludingInner() { - List blocks = new ArrayList(); + final List blocks = new ArrayList(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { for (int z = -1; z <= 1; z++) { - if (location != null) { - blocks.add(location.getWorld().getBlockAt(location.clone().add(x, y, z))); + if (this.location != null) { + blocks.add(this.location.getWorld().getBlockAt(this.location.clone().add(x, y, z))); } } } @@ -481,7 +490,7 @@ public List getBlocksIncludingInner() { * Switches the Sand Material and Gravel to SandStone and stone * respectively, since gravel and sand cannot be bent due to gravity. */ - public static Material selectMaterial(Material mat) { + public static Material selectMaterial(final Material mat) { if (mat == Material.SAND) { return Material.SANDSTONE; } else if (mat == Material.GRAVEL) { @@ -491,14 +500,14 @@ public static Material selectMaterial(Material mat) { } } - public Material selectMaterialForRepresenter(Material mat) { - Material tempMat = selectMaterial(mat); - Random rand = new Random(); - if (!isEarthbendable(tempMat, true, true, true) && !isMetalbendable(tempMat)) { - if (currentBlocks.size() < 1) { + public Material selectMaterialForRepresenter(final Material mat) { + final Material tempMat = selectMaterial(mat); + final Random rand = new Random(); + if (!isEarthbendable(tempMat, true, true, true) && !this.isMetalbendable(tempMat)) { + if (this.currentBlocks.size() < 1) { return Material.DIRT; } else { - return currentBlocks.get(rand.nextInt(currentBlocks.size())).getType(); + return this.currentBlocks.get(rand.nextInt(this.currentBlocks.size())).getType(); } } return tempMat; @@ -508,19 +517,19 @@ public Material selectMaterialForRepresenter(Material mat) { * Determines if a player is trying to grab an EarthSmash. A player is * trying to grab an EarthSmash if they are staring at it and holding shift. */ - private EarthSmash aimingAtSmashCheck(Player player, State reqState) { - if (!allowGrab) { + private EarthSmash aimingAtSmashCheck(final Player player, final State reqState) { + if (!this.allowGrab) { return null; } - List blocks = GeneralMethods.getBlocksAroundPoint(GeneralMethods.getTargetedLocation(player, grabRange, getTransparentMaterials()), 1); - for (EarthSmash smash : getAbilities(EarthSmash.class)) { + final List blocks = GeneralMethods.getBlocksAroundPoint(GeneralMethods.getTargetedLocation(player, this.grabRange, getTransparentMaterials()), 1); + for (final EarthSmash smash : getAbilities(EarthSmash.class)) { if (reqState == null || smash.state == reqState) { - for (Block block : blocks) { + for (final Block block : blocks) { if (block == null || smash.getLocation() == null) { continue; } - if (block.getLocation().getWorld() == smash.location.getWorld() && block.getLocation().distanceSquared(smash.location) <= Math.pow(grabDetectionRadius, 2)) { + if (block.getLocation().getWorld() == smash.location.getWorld() && block.getLocation().distanceSquared(smash.location) <= Math.pow(this.grabDetectionRadius, 2)) { return smash; } } @@ -535,14 +544,14 @@ private EarthSmash aimingAtSmashCheck(Player player, State reqState) { * already been shot. */ public void shootingCollisionDetection() { - List entities = GeneralMethods.getEntitiesAroundPoint(location, flightDetectionRadius); - for (Entity entity : entities) { - if (entity instanceof LivingEntity && entity != player && !affectedEntities.contains(entity)) { - affectedEntities.add(entity); - double damage = currentBlocks.size() / 13.0 * this.damage; + final List entities = GeneralMethods.getEntitiesAroundPoint(this.location, this.flightDetectionRadius); + for (final Entity entity : entities) { + if (entity instanceof LivingEntity && entity != this.player && !this.affectedEntities.contains(entity)) { + this.affectedEntities.add(entity); + final double damage = this.currentBlocks.size() / 13.0 * this.damage; DamageHandler.damageEntity(entity, damage, this); - Vector travelVec = GeneralMethods.getDirection(location, entity.getLocation()); - entity.setVelocity(travelVec.setY(knockup).normalize().multiply(knockback)); + final Vector travelVec = GeneralMethods.getDirection(this.location, entity.getLocation()); + entity.setVelocity(travelVec.setY(this.knockup).normalize().multiply(this.knockback)); } } } @@ -554,10 +563,10 @@ public void shootingCollisionDetection() { * time. */ public void smashToSmashCollisionDetection() { - for (EarthSmash smash : getAbilities(EarthSmash.class)) { - if (smash.location != null && smash != this && smash.location.getWorld() == location.getWorld() && smash.location.distanceSquared(location) < Math.pow(flightDetectionRadius, 2)) { + for (final EarthSmash smash : getAbilities(EarthSmash.class)) { + if (smash.location != null && smash != this && smash.location.getWorld() == this.location.getWorld() && smash.location.distanceSquared(this.location) < Math.pow(this.flightDetectionRadius, 2)) { smash.remove(); - remove(); + this.remove(); return; } } @@ -568,12 +577,12 @@ public void smashToSmashCollisionDetection() { * EarthSmash. A player is considered "flying" if they are standing ontop of * the earthsmash and holding shift. */ - private static EarthSmash flyingInSmashCheck(Player player) { - for (EarthSmash smash : getAbilities(EarthSmash.class)) { + private static EarthSmash flyingInSmashCheck(final Player player) { + for (final EarthSmash smash : getAbilities(EarthSmash.class)) { if (!smash.allowFlight) { continue; } - //Check to see if the player is standing on top of the smash. + // Check to see if the player is standing on top of the smash. if (smash.state == State.LIFTED) { if (smash.location.getWorld().equals(player.getWorld()) && smash.location.clone().add(0, 2, 0).distanceSquared(player.getLocation()) <= Math.pow(smash.flightDetectionRadius, 2)) { return smash; @@ -595,7 +604,7 @@ public class BlockRepresenter { private Material type; private byte data; - public BlockRepresenter(int x, int y, int z, Material type, byte data) { + public BlockRepresenter(final int x, final int y, final int z, final Material type, final byte data) { this.x = x; this.y = y; this.z = z; @@ -604,73 +613,74 @@ public BlockRepresenter(int x, int y, int z, Material type, byte data) { } public int getX() { - return x; + return this.x; } public int getY() { - return y; + return this.y; } public int getZ() { - return z; + return this.z; } public Material getType() { - return type; + return this.type; } public byte getData() { - return data; + return this.data; } - public void setX(int x) { + public void setX(final int x) { this.x = x; } - public void setY(int y) { + public void setY(final int y) { this.y = y; } - public void setZ(int z) { + public void setZ(final int z) { this.z = z; } - public void setType(Material type) { + public void setType(final Material type) { this.type = type; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } + @Override public String toString() { - return x + ", " + y + ", " + z + ", " + type.toString(); + return this.x + ", " + this.y + ", " + this.z + ", " + this.type.toString(); } } public class Pair { - private F first; //first member of pair - private S second; //second member of pair + private F first; // first member of pair. + private S second; // second member of pair. - public Pair(F first, S second) { + public Pair(final F first, final S second) { this.first = first; this.second = second; } - public void setFirst(F first) { + public void setFirst(final F first) { this.first = first; } - public void setSecond(S second) { + public void setSecond(final S second) { this.second = second; } public F getFirst() { - return first; + return this.first; } public S getSecond() { - return second; + return this.second; } } @@ -681,12 +691,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -701,246 +711,246 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (TempBlock tblock : affectedBlocks) { + final ArrayList locations = new ArrayList<>(); + for (final TempBlock tblock : this.affectedBlocks) { locations.add(tblock.getLocation()); } return locations; } public boolean isAllowGrab() { - return allowGrab; + return this.allowGrab; } - public void setAllowGrab(boolean allowGrab) { + public void setAllowGrab(final boolean allowGrab) { this.allowGrab = allowGrab; } public boolean isAllowFlight() { - return allowFlight; + return this.allowFlight; } - public void setAllowFlight(boolean allowFlight) { + public void setAllowFlight(final boolean allowFlight) { this.allowFlight = allowFlight; } public int getAnimationCounter() { - return animationCounter; + return this.animationCounter; } - public void setAnimationCounter(int animationCounter) { + public void setAnimationCounter(final int animationCounter) { this.animationCounter = animationCounter; } public int getProgressCounter() { - return progressCounter; + return this.progressCounter; } - public void setProgressCounter(int progressCounter) { + public void setProgressCounter(final int progressCounter) { this.progressCounter = progressCounter; } public int getRequiredBendableBlocks() { - return requiredBendableBlocks; + return this.requiredBendableBlocks; } - public void setRequiredBendableBlocks(int requiredBendableBlocks) { + public void setRequiredBendableBlocks(final int requiredBendableBlocks) { this.requiredBendableBlocks = requiredBendableBlocks; } public int getMaxBlocksToPassThrough() { - return maxBlocksToPassThrough; + return this.maxBlocksToPassThrough; } - public void setMaxBlocksToPassThrough(int maxBlocksToPassThrough) { + public void setMaxBlocksToPassThrough(final int maxBlocksToPassThrough) { this.maxBlocksToPassThrough = maxBlocksToPassThrough; } public long getDelay() { - return delay; + return this.delay; } - public void setDelay(long delay) { + public void setDelay(final long delay) { this.delay = delay; } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public long getRemoveTimer() { - return removeTimer; + return this.removeTimer; } - public void setRemoveTimer(long removeTimer) { + public void setRemoveTimer(final long removeTimer) { this.removeTimer = removeTimer; } public long getFlightRemoveTimer() { - return flightRemoveTimer; + return this.flightRemoveTimer; } - public void setFlightRemoveTimer(long flightRemoveTimer) { + public void setFlightRemoveTimer(final long flightRemoveTimer) { this.flightRemoveTimer = flightRemoveTimer; } public long getFlightStartTime() { - return flightStartTime; + return this.flightStartTime; } - public void setFlightStartTime(long flightStartTime) { + public void setFlightStartTime(final long flightStartTime) { this.flightStartTime = flightStartTime; } public long getShootAnimationInterval() { - return shootAnimationInterval; + return this.shootAnimationInterval; } - public void setShootAnimationInterval(long shootAnimationInterval) { + public void setShootAnimationInterval(final long shootAnimationInterval) { this.shootAnimationInterval = shootAnimationInterval; } public long getFlightAnimationInterval() { - return flightAnimationInterval; + return this.flightAnimationInterval; } - public void setFlightAnimationInterval(long flightAnimationInterval) { + public void setFlightAnimationInterval(final long flightAnimationInterval) { this.flightAnimationInterval = flightAnimationInterval; } public long getLiftAnimationInterval() { - return liftAnimationInterval; + return this.liftAnimationInterval; } - public void setLiftAnimationInterval(long liftAnimationInterval) { + public void setLiftAnimationInterval(final long liftAnimationInterval) { this.liftAnimationInterval = liftAnimationInterval; } public double getGrabRange() { - return grabRange; + return this.grabRange; } - public void setGrabRange(double grabRange) { + public void setGrabRange(final double grabRange) { this.grabRange = grabRange; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public double getShootRange() { - return shootRange; + return this.shootRange; } - public void setShootRange(double shootRange) { + public void setShootRange(final double shootRange) { this.shootRange = shootRange; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getKnockback() { - return knockback; + return this.knockback; } - public void setKnockback(double knockback) { + public void setKnockback(final double knockback) { this.knockback = knockback; } public double getKnockup() { - return knockup; + return this.knockup; } - public void setKnockup(double knockup) { + public void setKnockup(final double knockup) { this.knockup = knockup; } public double getFlightSpeed() { - return flightSpeed; + return this.flightSpeed; } - public void setFlightSpeed(double flightSpeed) { + public void setFlightSpeed(final double flightSpeed) { this.flightSpeed = flightSpeed; } public double getGrabbedDistance() { - return grabbedDistance; + return this.grabbedDistance; } - public void setGrabbedDistance(double grabbedDistance) { + public void setGrabbedDistance(final double grabbedDistance) { this.grabbedDistance = grabbedDistance; } public double getGrabDetectionRadius() { - return grabDetectionRadius; + return this.grabDetectionRadius; } - public void setGrabDetectionRadius(double grabDetectionRadius) { + public void setGrabDetectionRadius(final double grabDetectionRadius) { this.grabDetectionRadius = grabDetectionRadius; } public double getFlightDetectionRadius() { - return flightDetectionRadius; + return this.flightDetectionRadius; } - public void setFlightDetectionRadius(double flightDetectionRadius) { + public void setFlightDetectionRadius(final double flightDetectionRadius) { this.flightDetectionRadius = flightDetectionRadius; } public State getState() { - return state; + return this.state; } - public void setState(State state) { + public void setState(final State state) { this.state = state; } public Block getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Block origin) { + public void setOrigin(final Block origin) { this.origin = origin; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getCurrentBlocks() { - return currentBlocks; + return this.currentBlocks; } public ArrayList getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthTunnel.java b/src/com/projectkorra/projectkorra/earthbending/EarthTunnel.java index 2cbec7c32..0921bac1e 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthTunnel.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthTunnel.java @@ -15,6 +15,7 @@ import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.util.TempBlock; @@ -30,7 +31,7 @@ public class EarthTunnel extends EarthAbility { private double range; private double radiusIncrement; private boolean revert; - private boolean dropLootIfNotRevert; + private boolean dropLootIfNotRevert; private Block block; private Location origin; private Location location; @@ -38,7 +39,7 @@ public class EarthTunnel extends EarthAbility { public static Map airBlocks = new ConcurrentHashMap(); - public EarthTunnel(Player player) { + public EarthTunnel(final Player player) { super(player); this.cooldown = getConfig().getLong("Abilities.Earth.EarthTunnel.Cooldown"); @@ -48,82 +49,91 @@ public EarthTunnel(Player player) { this.interval = getConfig().getLong("Abilities.Earth.EarthTunnel.Interval"); this.revert = getConfig().getBoolean("Abilities.Earth.EarthTunnel.Revert"); this.dropLootIfNotRevert = getConfig().getBoolean("Abilities.Earth.EarthTunnel.DropLootIfNotRevert"); - + this.time = System.currentTimeMillis(); this.location = player.getEyeLocation().clone(); - this.origin = player.getTargetBlock((HashSet) null, (int) range).getLocation(); - this.block = origin.getBlock(); - this.direction = location.getDirection().clone().normalize(); + this.origin = player.getTargetBlock((HashSet) null, (int) this.range).getLocation(); + this.block = this.origin.getBlock(); + this.direction = this.location.getDirection().clone().normalize(); this.depth = 0; - if (origin.getWorld().equals(location.getWorld())) { - this.depth = Math.max(0, origin.distance(location) - 1); + if (this.origin.getWorld().equals(this.location.getWorld())) { + this.depth = Math.max(0, this.origin.distance(this.location) - 1); } this.angle = 0; - if (!bPlayer.canBend(this) || !EarthAbility.isEarthbendable(player, block)) { + if (!this.bPlayer.canBend(this) || (!EarthAbility.isEarthbendable(player, this.block) && !ElementalAbility.isTransparent(player, "EarthTunnel", this.block))) { + return; + } + if (GeneralMethods.isRegionProtectedFromBuild(this, this.block.getLocation())) { return; } - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.maxRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthTunnel.Radius"); } - this.radiusIncrement = radius; - - start(); + this.radiusIncrement = this.radius; + + this.start(); } @Override public void progress() { - if (!bPlayer.canBend(this)) { - bPlayer.addCooldown(this); - remove(); + if (!this.bPlayer.canBend(this)) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - if (Math.abs(Math.toDegrees(player.getEyeLocation().getDirection().angle(direction))) > 20 || !player.isSneaking()) { - bPlayer.addCooldown(this); - remove(); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + if (Math.abs(Math.toDegrees(this.player.getEyeLocation().getDirection().angle(this.direction))) > 20 || !this.player.isSneaking()) { + this.bPlayer.addCooldown(this); + this.remove(); return; } else { - while ((!isEarth(block) && !isSand(block))) { - if (!isTransparent(block)) { - remove(); + while ((!isEarth(this.block) && !isSand(this.block))) { + if (!this.isTransparent(this.block)) { + this.remove(); return; } - if (angle >= 360) { - angle = 0; - if (radius >= maxRadius) { - radius = radiusIncrement; - if (depth >= range) { - bPlayer.addCooldown(this); - remove(); + if (this.angle >= 360) { + this.angle = 0; + if (this.radius >= this.maxRadius) { + this.radius = this.radiusIncrement; + if (this.depth >= this.range) { + this.bPlayer.addCooldown(this); + this.remove(); return; } else { - depth += 0.5; + this.depth += 0.5; } } else { - radius += radiusIncrement; + this.radius += this.radiusIncrement; } } else { - angle += 20; + this.angle += 20; } - Vector vec = GeneralMethods.getOrthogonalVector(direction, angle, radius); - block = location.clone().add(direction.clone().normalize().multiply(depth)).add(vec).getBlock(); + final Vector vec = GeneralMethods.getOrthogonalVector(this.direction, this.angle, this.radius); + this.block = this.location.clone().add(this.direction.clone().normalize().multiply(this.depth)).add(vec).getBlock(); + } + + if (GeneralMethods.isRegionProtectedFromBuild(this, this.block.getLocation())) { + this.bPlayer.addCooldown(this); + this.remove(); + return; } - if (revert) { - if (getMovedEarth().containsKey(block)) { - block.setType(Material.AIR); + if (this.revert) { + if (getMovedEarth().containsKey(this.block)) { + this.block.setType(Material.AIR); } else { - airBlocks.put(new TempBlock(block, Material.AIR, (byte) 0), System.currentTimeMillis()); - if (isPlant(block.getRelative(BlockFace.UP)) || isSnow(block.getRelative(BlockFace.UP))) { - Block above = block.getRelative(BlockFace.UP); - Block above2 = above.getRelative(BlockFace.UP); + airBlocks.put(new TempBlock(this.block, Material.AIR, (byte) 0), System.currentTimeMillis()); + if (isPlant(this.block.getRelative(BlockFace.UP)) || isSnow(this.block.getRelative(BlockFace.UP))) { + final Block above = this.block.getRelative(BlockFace.UP); + final Block above2 = above.getRelative(BlockFace.UP); if (isPlant(above) || isSnow(above)) { airBlocks.put(new TempBlock(above, Material.AIR, (byte) 0), System.currentTimeMillis()); if (isPlant(above2) && above2.getType().equals(Material.DOUBLE_PLANT)) { @@ -133,10 +143,10 @@ public void progress() { } } } else { - if (dropLootIfNotRevert) { - block.breakNaturally(); + if (this.dropLootIfNotRevert) { + this.block.breakNaturally(); } else { - block.setType(Material.AIR); + this.block.setType(Material.AIR); } } } @@ -150,12 +160,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -170,108 +180,108 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (TempBlock tblock : airBlocks.keySet()) { + final ArrayList locations = new ArrayList<>(); + for (final TempBlock tblock : airBlocks.keySet()) { locations.add(tblock.getLocation()); } return locations; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getDepth() { - return depth; + return this.depth; } - public void setDepth(double depth) { + public void setDepth(final double depth) { this.depth = depth; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getAngle() { - return angle; + return this.angle; } - public void setAngle(double angle) { + public void setAngle(final double angle) { this.angle = angle; } public double getMaxRadius() { - return maxRadius; + return this.maxRadius; } - public void setMaxRadius(double maxRadius) { + public void setMaxRadius(final double maxRadius) { this.maxRadius = maxRadius; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadiusIncrement() { - return radiusIncrement; + return this.radiusIncrement; } - public void setRadiusIncrement(double radiusIncrement) { + public void setRadiusIncrement(final double radiusIncrement) { this.radiusIncrement = radiusIncrement; } public Block getBlock() { - return block; + return this.block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public static void revertAirBlocks() { if (ConfigManager.defaultConfig.get().getBoolean("Abilities.Earth.EarthTunnel.Revert")) { - for (TempBlock tempBlock : EarthTunnel.airBlocks.keySet()) { + for (final TempBlock tempBlock : EarthTunnel.airBlocks.keySet()) { if (EarthTunnel.airBlocks.get(tempBlock) + ConfigManager.defaultConfig.get().getLong("Properties.Earth.RevertCheckTime") <= System.currentTimeMillis()) { tempBlock.revertBlock(); EarthTunnel.airBlocks.remove(tempBlock); diff --git a/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java b/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java index 5b60f22d3..779600c4d 100644 --- a/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java +++ b/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java @@ -34,59 +34,59 @@ public class RaiseEarth extends EarthAbility { private Location location; private ConcurrentHashMap affectedBlocks; - public RaiseEarth(Player player) { + public RaiseEarth(final Player player) { super(player); - setFields(); + this.setFields(); - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("RaiseEarthPillar")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("RaiseEarthPillar")) { return; } try { - if (bPlayer.isAvatarState()) { - height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Column.Height"); + if (this.bPlayer.isAvatarState()) { + this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Column.Height"); } - block = BlockSource.getEarthSourceBlock(player, selectRange, ClickType.LEFT_CLICK); - if (block == null) { + this.block = BlockSource.getEarthSourceBlock(player, this.selectRange, ClickType.LEFT_CLICK); + if (this.block == null) { return; } - origin = block.getLocation(); - location = origin.clone(); - distance = getEarthbendableBlocksLength(block, direction.clone().multiply(-1), height); + this.origin = this.block.getLocation(); + this.location = this.origin.clone(); + this.distance = this.getEarthbendableBlocksLength(this.block, this.direction.clone().multiply(-1), this.height); } - catch (IllegalStateException e) { + catch (final IllegalStateException e) { return; } - loadAffectedBlocks(); + this.loadAffectedBlocks(); - if (distance != 0 && canInstantiate()) { - bPlayer.addCooldown("RaiseEarthPillar", cooldown); - time = System.currentTimeMillis() - interval; - start(); + if (this.distance != 0 && this.canInstantiate()) { + this.bPlayer.addCooldown("RaiseEarthPillar", this.cooldown); + this.time = System.currentTimeMillis() - this.interval; + this.start(); } } - public RaiseEarth(Player player, Location origin) { + public RaiseEarth(final Player player, final Location origin) { this(player, origin, ConfigManager.getConfig().getInt("Abilities.Earth.RaiseEarth.Column.Height")); } - public RaiseEarth(Player player, Location origin, int height) { + public RaiseEarth(final Player player, final Location origin, final int height) { super(player); - setFields(); + this.setFields(); this.height = height; this.origin = origin; this.location = origin.clone(); - this.block = location.getBlock(); - this.distance = getEarthbendableBlocksLength(block, direction.clone().multiply(-1), height); + this.block = this.location.getBlock(); + this.distance = this.getEarthbendableBlocksLength(this.block, this.direction.clone().multiply(-1), height); - loadAffectedBlocks(); + this.loadAffectedBlocks(); - if (distance != 0 && canInstantiate()) { - time = System.currentTimeMillis() - interval; - start(); + if (this.distance != 0 && this.canInstantiate()) { + this.time = System.currentTimeMillis() - this.interval; + this.start(); } } @@ -96,17 +96,17 @@ private void setFields() { this.selectRange = getConfig().getDouble("Abilities.Earth.RaiseEarth.Column.SelectRange"); this.cooldown = getConfig().getLong("Abilities.Earth.RaiseEarth.Column.Cooldown"); this.direction = new Vector(0, 1, 0); - this.interval = (long) (1000.0 / speed); + this.interval = (long) (1000.0 / this.speed); this.affectedBlocks = new ConcurrentHashMap<>(); } private boolean canInstantiate() { - if (location.getBlock().getRelative(BlockFace.UP).getType() == Material.STATIONARY_LAVA) { + if (this.location.getBlock().getRelative(BlockFace.UP).getType() == Material.STATIONARY_LAVA) { return false; } - for (Block block : affectedBlocks.keySet()) { - if (!isEarthbendable(block) || ALL_AFFECTED_BLOCKS.containsKey(block)) { + for (final Block block : this.affectedBlocks.keySet()) { + if (!this.isEarthbendable(block) || ALL_AFFECTED_BLOCKS.containsKey(block)) { return false; } } @@ -114,11 +114,11 @@ private boolean canInstantiate() { } private void loadAffectedBlocks() { - affectedBlocks.clear(); + this.affectedBlocks.clear(); Block thisBlock; - for (int i = 0; i <= distance; i++) { - thisBlock = block.getWorld().getBlockAt(location.clone().add(direction.clone().multiply(-i))); - affectedBlocks.put(thisBlock, thisBlock); + for (int i = 0; i <= this.distance; i++) { + thisBlock = this.block.getWorld().getBlockAt(this.location.clone().add(this.direction.clone().multiply(-i))); + this.affectedBlocks.put(thisBlock, thisBlock); if (Collapse.blockInAllAffectedBlocks(thisBlock)) { Collapse.revert(thisBlock); } @@ -127,30 +127,30 @@ private void loadAffectedBlocks() { @Override public void progress() { - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - Block block = location.getBlock(); - location = location.add(direction); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + final Block block = this.location.getBlock(); + this.location = this.location.add(this.direction); if (!block.isLiquid()) { - moveEarth(block, direction, distance); + this.moveEarth(block, this.direction, this.distance); } - loadAffectedBlocks(); + this.loadAffectedBlocks(); - if (location.distanceSquared(origin) >= distance * distance) { - remove(); + if (this.location.distanceSquared(this.origin) >= this.distance * this.distance) { + this.remove(); return; } } } - public static boolean blockInAllAffectedBlocks(Block block) { + public static boolean blockInAllAffectedBlocks(final Block block) { return ALL_AFFECTED_BLOCKS.containsKey(block); } - public static void revertAffectedBlock(Block block) { + public static void revertAffectedBlock(final Block block) { ALL_AFFECTED_BLOCKS.remove(block); - for (RaiseEarth raiseEarth : getAbilities(RaiseEarth.class)) { + for (final RaiseEarth raiseEarth : getAbilities(RaiseEarth.class)) { raiseEarth.affectedBlocks.remove(block); } } @@ -162,12 +162,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -182,94 +182,94 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (Block block : affectedBlocks.values()) { + final ArrayList locations = new ArrayList<>(); + for (final Block block : this.affectedBlocks.values()) { locations.add(block.getLocation()); } return locations; } public int getDistance() { - return distance; + return this.distance; } - public void setDistance(int distance) { + public void setDistance(final int distance) { this.distance = distance; } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public Block getBlock() { - return block; + return this.block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public ConcurrentHashMap getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } diff --git a/src/com/projectkorra/projectkorra/earthbending/RaiseEarthWall.java b/src/com/projectkorra/projectkorra/earthbending/RaiseEarthWall.java index 7cff19fbc..081e872db 100644 --- a/src/com/projectkorra/projectkorra/earthbending/RaiseEarthWall.java +++ b/src/com/projectkorra/projectkorra/earthbending/RaiseEarthWall.java @@ -19,23 +19,23 @@ public class RaiseEarthWall extends EarthAbility { private long cooldown; private Location location; - public RaiseEarthWall(Player player) { + public RaiseEarthWall(final Player player) { super(player); this.selectRange = getConfig().getInt("Abilities.Earth.RaiseEarth.Wall.SelectRange"); this.height = getConfig().getInt("Abilities.Earth.RaiseEarth.Wall.Height"); this.width = getConfig().getInt("Abilities.Earth.RaiseEarth.Wall.Width"); this.cooldown = getConfig().getLong("Abilities.Earth.RaiseEarth.Wall.Cooldown"); - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("RaiseEarthWall")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("RaiseEarthWall")) { return; } - if (bPlayer.isAvatarState()) { - height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Wall.Height"); - width = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Wall.Width"); + if (this.bPlayer.isAvatarState()) { + this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Wall.Height"); + this.width = getConfig().getInt("Abilities.Avatar.AvatarState.Earth.RaiseEarth.Wall.Width"); } - Vector direction = player.getEyeLocation().getDirection().normalize(); + final Vector direction = player.getEyeLocation().getDirection().normalize(); double ox, oy, oz; direction.setY(0); ox = -direction.getZ(); @@ -46,66 +46,66 @@ public RaiseEarthWall(Player player) { orth = orth.normalize(); orth = getDegreeRoundedVector(orth, 0.25); - Block sblock = BlockSource.getEarthSourceBlock(player, selectRange, ClickType.SHIFT_DOWN); + final Block sblock = BlockSource.getEarthSourceBlock(player, this.selectRange, ClickType.SHIFT_DOWN); if (sblock == null) { - location = getTargetEarthBlock(selectRange).getLocation(); + this.location = this.getTargetEarthBlock(this.selectRange).getLocation(); } else { - location = sblock.getLocation(); + this.location = sblock.getLocation(); } - World world = location.getWorld(); + final World world = this.location.getWorld(); boolean shouldAddCooldown = false; - for (int i = 0; i < width; i++) { - double adjustedI = i - width / 2.0; - Block block = world.getBlockAt(location.clone().add(orth.clone().multiply(adjustedI))); + for (int i = 0; i < this.width; i++) { + final double adjustedI = i - this.width / 2.0; + Block block = world.getBlockAt(this.location.clone().add(orth.clone().multiply(adjustedI))); - if (isTransparent(block)) { - for (int j = 1; j < height; j++) { + if (this.isTransparent(block)) { + for (int j = 1; j < this.height; j++) { block = block.getRelative(BlockFace.DOWN); - if (isEarthbendable(block)) { + if (this.isEarthbendable(block)) { shouldAddCooldown = true; - new RaiseEarth(player, block.getLocation(), height); - } else if (!isTransparent(block)) { + new RaiseEarth(player, block.getLocation(), this.height); + } else if (!this.isTransparent(block)) { break; } } - } else if (isEarthbendable(block.getRelative(BlockFace.UP))) { - for (int j = 1; j < height; j++) { + } else if (this.isEarthbendable(block.getRelative(BlockFace.UP))) { + for (int j = 1; j < this.height; j++) { block = block.getRelative(BlockFace.UP); - if (isTransparent(block)) { + if (this.isTransparent(block)) { shouldAddCooldown = true; - new RaiseEarth(player, block.getRelative(BlockFace.DOWN).getLocation(), height); - } else if (!isEarthbendable(block)) { + new RaiseEarth(player, block.getRelative(BlockFace.DOWN).getLocation(), this.height); + } else if (!this.isEarthbendable(block)) { break; } } - } else if (isEarthbendable(block)) { + } else if (this.isEarthbendable(block)) { shouldAddCooldown = true; - new RaiseEarth(player, block.getLocation(), height); + new RaiseEarth(player, block.getLocation(), this.height); } } if (shouldAddCooldown) { - bPlayer.addCooldown("RaiseEarthWall", cooldown); + this.bPlayer.addCooldown("RaiseEarthWall", this.cooldown); } } - private static Vector getDegreeRoundedVector(Vector vec, double degreeIncrement) { + private static Vector getDegreeRoundedVector(Vector vec, final double degreeIncrement) { if (vec == null) { return null; } vec = vec.normalize(); - double[] dims = { vec.getX(), vec.getY(), vec.getZ() }; + final double[] dims = { vec.getX(), vec.getY(), vec.getZ() }; for (int i = 0; i < dims.length; i++) { - double dim = dims[i]; - int sign = dim >= 0 ? 1 : -1; - int dimDivIncr = (int) (dim / degreeIncrement); + final double dim = dims[i]; + final int sign = dim >= 0 ? 1 : -1; + final int dimDivIncr = (int) (dim / degreeIncrement); - double lowerBound = dimDivIncr * degreeIncrement; - double upperBound = (dimDivIncr + (1 * sign)) * degreeIncrement; + final double lowerBound = dimDivIncr * degreeIncrement; + final double upperBound = (dimDivIncr + (1 * sign)) * degreeIncrement; if (Math.abs(dim - lowerBound) < Math.abs(dim - upperBound)) { dims[i] = lowerBound; @@ -127,12 +127,12 @@ public void progress() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -146,42 +146,42 @@ public boolean isHarmlessAbility() { } public int getRange() { - return selectRange; + return this.selectRange; } - public void setRange(int range) { + public void setRange(final int range) { this.selectRange = range; } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public int getWidth() { - return width; + return this.width; } - public void setWidth(int width) { + public void setWidth(final int width) { this.width = width; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public int getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(int selectRange) { + public void setSelectRange(final int selectRange) { this.selectRange = selectRange; } diff --git a/src/com/projectkorra/projectkorra/earthbending/Ripple.java b/src/com/projectkorra/projectkorra/earthbending/Ripple.java index c0e1ad76b..d46932f12 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Ripple.java +++ b/src/com/projectkorra/projectkorra/earthbending/Ripple.java @@ -39,17 +39,17 @@ public class Ripple extends EarthAbility { private ArrayList locations = new ArrayList(); private ArrayList entities = new ArrayList(); - public Ripple(Player player, Vector direction) { + public Ripple(final Player player, final Vector direction) { super(player); - initialize(player, getInitialLocation(player, direction), direction); + this.initialize(player, this.getInitialLocation(player, direction), direction); } - public Ripple(Player player, Location origin, Vector direction) { + public Ripple(final Player player, final Location origin, final Vector direction) { super(player); - initialize(player, origin, direction); + this.initialize(player, origin, direction); } - private void initialize(Player player, Location origin, Vector direction) { + private void initialize(final Player player, final Location origin, final Vector direction) { if (origin == null) { return; } @@ -63,36 +63,36 @@ private void initialize(Player player, Location origin, Vector direction) { this.locations = new ArrayList<>(); this.entities = new ArrayList<>(); - if (bPlayer.isAvatarState()) { - range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Range"); - damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Damage"); - knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Knockback"); + if (this.bPlayer.isAvatarState()) { + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Range"); + this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Damage"); + this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Knockback"); } - initializeLocations(); - maxStep = locations.size(); + this.initializeLocations(); + this.maxStep = this.locations.size(); - if (isEarthbendable(origin.getBlock())) { - start(); + if (this.isEarthbendable(origin.getBlock())) { + this.start(); } } - private Location getInitialLocation(Player player, Vector direction) { + private Location getInitialLocation(final Player player, Vector direction) { Location location = player.getLocation().clone().add(0, -1, 0); direction = direction.normalize(); - Block block1 = location.getBlock(); + final Block block1 = location.getBlock(); while (location.getBlock().equals(block1)) { location = location.clone().add(direction); } - for (int i : new int[] { 1, 2, 3, 0, -1 }) { + for (final int i : new int[] { 1, 2, 3, 0, -1 }) { Location loc; loc = location.clone().add(0, i, 0); - Block topBlock = loc.getBlock(); - Block botBlock = loc.clone().add(0, -1, 0).getBlock(); + final Block topBlock = loc.getBlock(); + final Block botBlock = loc.clone().add(0, -1, 0).getBlock(); - if (isTransparent(topBlock) && isEarthbendable(botBlock)) { + if (this.isTransparent(topBlock) && this.isEarthbendable(botBlock)) { location = loc.clone().add(0, -1, 0); return location; } @@ -103,116 +103,120 @@ private Location getInitialLocation(Player player, Vector direction) { @Override public void progress() { - if (step < maxStep) { - Location newlocation = locations.get(step); - Block block = location.getBlock(); - location = newlocation.clone(); + if (this.step < this.maxStep) { + final Location newlocation = this.locations.get(this.step); + final Block block = this.location.getBlock(); + this.location = newlocation.clone(); if (!newlocation.getBlock().equals(block)) { - block1 = block2; - block2 = block3; - block3 = block4; - block4 = newlocation.getBlock(); - - if (block1 != null) - if (hasAnyMoved(block1)) { - block1 = null; + this.block1 = this.block2; + this.block2 = this.block3; + this.block3 = this.block4; + this.block4 = newlocation.getBlock(); + + if (this.block1 != null) { + if (hasAnyMoved(this.block1)) { + this.block1 = null; } - if (block2 != null) - if (hasAnyMoved(block2)) { - block2 = null; + } + if (this.block2 != null) { + if (hasAnyMoved(this.block2)) { + this.block2 = null; } - if (block3 != null) - if (hasAnyMoved(block3)) { - block3 = null; + } + if (this.block3 != null) { + if (hasAnyMoved(this.block3)) { + this.block3 = null; } - if (block4 != null) - if (hasAnyMoved(block4)) { - block4 = null; + } + if (this.block4 != null) { + if (hasAnyMoved(this.block4)) { + this.block4 = null; } + } - if (step == 0) { - if (increase(block4)) { - block4 = block4.getRelative(BlockFace.UP); + if (this.step == 0) { + if (this.increase(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.UP); } - } else if (step == 1) { - if (increase(block3)) { - block3 = block3.getRelative(BlockFace.UP); + } else if (this.step == 1) { + if (this.increase(this.block3)) { + this.block3 = this.block3.getRelative(BlockFace.UP); } - if (increase(block4)) { - block4 = block4.getRelative(BlockFace.UP); + if (this.increase(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.UP); } - } else if (step == 2) { - if (decrease(block2)) { - block2 = block2.getRelative(BlockFace.DOWN); + } else if (this.step == 2) { + if (this.decrease(this.block2)) { + this.block2 = this.block2.getRelative(BlockFace.DOWN); } - if (increase(block3)) { - block3 = block3.getRelative(BlockFace.UP); + if (this.increase(this.block3)) { + this.block3 = this.block3.getRelative(BlockFace.UP); } - if (increase(block4)) { - block4 = block4.getRelative(BlockFace.UP); + if (this.increase(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.UP); } } else { - if (decrease(block1)) { - block1 = block1.getRelative(BlockFace.DOWN); + if (this.decrease(this.block1)) { + this.block1 = this.block1.getRelative(BlockFace.DOWN); } - if (decrease(block2)) { - block2 = block2.getRelative(BlockFace.DOWN); + if (this.decrease(this.block2)) { + this.block2 = this.block2.getRelative(BlockFace.DOWN); } - if (increase(block3)) { - block3 = block3.getRelative(BlockFace.UP); + if (this.increase(this.block3)) { + this.block3 = this.block3.getRelative(BlockFace.UP); } - if (increase(block4)) { - block4 = block4.getRelative(BlockFace.UP); + if (this.increase(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.UP); } } } - } else if (step == maxStep) { - if (decrease(block2)) { - block2 = block2.getRelative(BlockFace.DOWN); + } else if (this.step == this.maxStep) { + if (this.decrease(this.block2)) { + this.block2 = this.block2.getRelative(BlockFace.DOWN); } - if (decrease(block3)) { - block3 = block3.getRelative(BlockFace.DOWN); + if (this.decrease(this.block3)) { + this.block3 = this.block3.getRelative(BlockFace.DOWN); } - if (increase(block4)) { - block4 = block4.getRelative(BlockFace.UP); + if (this.increase(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.UP); } - } else if (step == maxStep + 1) { - if (decrease(block3)) { - block3 = block3.getRelative(BlockFace.DOWN); + } else if (this.step == this.maxStep + 1) { + if (this.decrease(this.block3)) { + this.block3 = this.block3.getRelative(BlockFace.DOWN); } - if (decrease(block4)) { - block4 = block4.getRelative(BlockFace.DOWN); + if (this.decrease(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.DOWN); } - } else if (step == maxStep + 2) { - if (decrease(block4)) { - block4 = block4.getRelative(BlockFace.DOWN); + } else if (this.step == this.maxStep + 2) { + if (this.decrease(this.block4)) { + this.block4 = this.block4.getRelative(BlockFace.DOWN); } - remove(); + this.remove(); } - step += 1; - for (Entity entity : entities) { - affect(entity); + this.step += 1; + for (final Entity entity : this.entities) { + this.affect(entity); } - entities.clear(); + this.entities.clear(); } private void initializeLocations() { - Location location = origin.clone(); - locations.add(location); + Location location = this.origin.clone(); + this.locations.add(location); - while (location.distanceSquared(origin) < range * range) { - location = location.clone().add(direction); - for (int i : new int[] { 1, 2, 3, 0, -1 }) { + while (location.distanceSquared(this.origin) < this.range * this.range) { + location = location.clone().add(this.direction); + for (final int i : new int[] { 1, 2, 3, 0, -1 }) { Location loc; loc = location.clone().add(0, i, 0); - Block topblock = loc.getBlock(); - Block botblock = loc.clone().add(0, -1, 0).getBlock(); + final Block topblock = loc.getBlock(); + final Block botblock = loc.clone().add(0, -1, 0).getBlock(); - if (isTransparent(topblock) && !topblock.isLiquid() && isEarthbendable(botblock) && botblock.getType() != Material.STATIONARY_LAVA) { + if (this.isTransparent(topblock) && !topblock.isLiquid() && this.isEarthbendable(botblock) && botblock.getType() != Material.STATIONARY_LAVA) { location = loc.clone().add(0, -1, 0); - locations.add(location); + this.locations.add(location); break; } else if (i == -1) { return; @@ -229,17 +233,17 @@ private boolean decrease(Block block) { } setMoved(block); - Block botBlock = block.getRelative(BlockFace.DOWN); + final Block botBlock = block.getRelative(BlockFace.DOWN); int length = 1; - if (isEarthbendable(botBlock)) { + if (this.isEarthbendable(botBlock)) { length = 2; block = botBlock; } - return moveEarth(block, new Vector(0, -1, 0), length, false); + return this.moveEarth(block, new Vector(0, -1, 0), length, false); } - private boolean increase(Block block) { + private boolean increase(final Block block) { if (block == null) { return false; } else if (hasAnyMoved(block)) { @@ -247,17 +251,17 @@ private boolean increase(Block block) { } setMoved(block); - Block botblock = block.getRelative(BlockFace.DOWN); + final Block botblock = block.getRelative(BlockFace.DOWN); int length = 1; - if (isEarthbendable(botblock)) { + if (this.isEarthbendable(botblock)) { length = 2; } - if (moveEarth(block, new Vector(0, 1, 0), length, false)) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(block.getLocation().clone().add(0, 1, 0), 2)) { - if (entity.getEntityId() != player.getEntityId() && !entities.contains(entity)) { + if (this.moveEarth(block, new Vector(0, 1, 0), length, false)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(block.getLocation().clone().add(0, 1, 0), 2)) { + if (entity.getEntityId() != this.player.getEntityId() && !this.entities.contains(entity)) { if (!(entity instanceof FallingBlock)) { - entities.add(entity); + this.entities.add(entity); } } } @@ -266,29 +270,29 @@ private boolean increase(Block block) { return false; } - private void affect(Entity entity) { + private void affect(final Entity entity) { if (entity instanceof LivingEntity) { - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } - Vector vector = direction.clone(); + final Vector vector = this.direction.clone(); vector.setY(.5); - double knock = bPlayer.isAvatarState() ? AvatarState.getValue(knockback) : knockback; + final double knock = this.bPlayer.isAvatarState() ? AvatarState.getValue(this.knockback) : this.knockback; entity.setVelocity(vector.clone().normalize().multiply(knock)); AirAbility.breakBreathbendingHold(entity); } - private static void setMoved(Block block) { - int x = block.getX(); - int z = block.getZ(); - Integer[] pair = new Integer[] { x, z }; + private static void setMoved(final Block block) { + final int x = block.getX(); + final int z = block.getZ(); + final Integer[] pair = new Integer[] { x, z }; BLOCKS.put(pair, block); } - private static boolean hasAnyMoved(Block block) { - int x = block.getX(); - int z = block.getZ(); - Integer[] pair = new Integer[] { x, z }; + private static boolean hasAnyMoved(final Block block) { + final int x = block.getX(); + final int z = block.getZ(); + final Integer[] pair = new Integer[] { x, z }; if (BLOCKS.containsKey(pair)) { return true; } @@ -310,7 +314,7 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override @@ -330,102 +334,102 @@ public boolean isHarmlessAbility() { @Override public ArrayList getLocations() { - return locations; + return this.locations; } public int getStep() { - return step; + return this.step; } - public void setStep(int step) { + public void setStep(final int step) { this.step = step; } public int getMaxStep() { - return maxStep; + return this.maxStep; } - public void setMaxStep(int maxStep) { + public void setMaxStep(final int maxStep) { this.maxStep = maxStep; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getKnockback() { - return knockback; + return this.knockback; } - public void setKnockback(double knockback) { + public void setKnockback(final double knockback) { this.knockback = knockback; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Block getBlock1() { - return block1; + return this.block1; } - public void setBlock1(Block block1) { + public void setBlock1(final Block block1) { this.block1 = block1; } public Block getBlock2() { - return block2; + return this.block2; } - public void setBlock2(Block block2) { + public void setBlock2(final Block block2) { this.block2 = block2; } public Block getBlock3() { - return block3; + return this.block3; } - public void setBlock3(Block block3) { + public void setBlock3(final Block block3) { this.block3 = block3; } public Block getBlock4() { - return block4; + return this.block4; } - public void setBlock4(Block block4) { + public void setBlock4(final Block block4) { this.block4 = block4; } public ArrayList getEntities() { - return entities; + return this.entities; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/earthbending/Shockwave.java b/src/com/projectkorra/projectkorra/earthbending/Shockwave.java index c8f232042..c7417018f 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Shockwave.java +++ b/src/com/projectkorra/projectkorra/earthbending/Shockwave.java @@ -1,13 +1,13 @@ package com.projectkorra.projectkorra.earthbending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.EarthAbility; - import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.EarthAbility; + public class Shockwave extends EarthAbility { private boolean charged; @@ -17,7 +17,7 @@ public class Shockwave extends EarthAbility { private double threshold; private double range; - public Shockwave(Player player, boolean fall) { + public Shockwave(final Player player, final boolean fall) { super(player); this.angle = Math.toRadians(getConfig().getDouble("Abilities.Earth.Shockwave.Angle")); @@ -26,61 +26,61 @@ public Shockwave(Player player, boolean fall) { this.threshold = getConfig().getDouble("Abilities.Earth.Shockwave.FallThreshold"); this.range = getConfig().getDouble("Abilities.Earth.Shockwave.Range"); - if (bPlayer.isAvatarState()) { - range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Range"); - cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.Shockwave.Cooldown"); - chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.Shockwave.ChargeTime"); + if (this.bPlayer.isAvatarState()) { + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.Shockwave.Range"); + this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.Shockwave.Cooldown"); + this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.Shockwave.ChargeTime"); } - if (!bPlayer.canBend(this) || hasAbility(player, Shockwave.class)) { + if (!this.bPlayer.canBend(this) || hasAbility(player, Shockwave.class)) { return; } if (fall) { - fallShockwave(); + this.fallShockwave(); return; } - start(); + this.start(); } public void fallShockwave() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { return; - } else if (player.getFallDistance() < threshold || !isEarthbendable(player.getLocation().clone().subtract(0, 1, 0).getBlock())) { + } else if (this.player.getFallDistance() < this.threshold || !this.isEarthbendable(this.player.getLocation().clone().subtract(0, 1, 0).getBlock())) { return; - } else if (bPlayer.isOnCooldown("Shockwave")) { + } else if (this.bPlayer.isOnCooldown("Shockwave")) { return; } - areaShockwave(); - bPlayer.addCooldown(this); - remove(); + this.areaShockwave(); + this.bPlayer.addCooldown(this); + this.remove(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() > getStartTime() + chargeTime && !charged) { - charged = true; + if (System.currentTimeMillis() > this.getStartTime() + this.chargeTime && !this.charged) { + this.charged = true; } - if (!player.isSneaking()) { - if (charged) { - areaShockwave(); - remove(); + if (!this.player.isSneaking()) { + if (this.charged) { + this.areaShockwave(); + this.remove(); return; } else { - remove(); + this.remove(); return; } - } else if (charged) { - Location location = player.getEyeLocation(); - location.getWorld().playEffect(location, Effect.SMOKE, GeneralMethods.getIntCardinalDirection(player.getEyeLocation().getDirection()), 3); + } else if (this.charged) { + final Location location = this.player.getEyeLocation(); + location.getWorld().playEffect(location, Effect.SMOKE, GeneralMethods.getIntCardinalDirection(this.player.getEyeLocation().getDirection()), 3); } } @@ -89,24 +89,24 @@ public static void progressAll() { } public void areaShockwave() { - double dtheta = 360.0 / (2 * Math.PI * this.range) - 1; + final double dtheta = 360.0 / (2 * Math.PI * this.range) - 1; for (double theta = 0; theta < 360; theta += dtheta) { - double rtheta = Math.toRadians(theta); - Vector vector = new Vector(Math.cos(rtheta), 0, Math.sin(rtheta)); - new Ripple(player, vector.normalize()); + final double rtheta = Math.toRadians(theta); + final Vector vector = new Vector(Math.cos(rtheta), 0, Math.sin(rtheta)); + new Ripple(this.player, vector.normalize()); } - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } - public static void coneShockwave(Player player) { - Shockwave shockWave = getAbility(player, Shockwave.class); + public static void coneShockwave(final Player player) { + final Shockwave shockWave = getAbility(player, Shockwave.class); if (shockWave != null) { if (shockWave.charged) { - double dtheta = 360.0 / (2 * Math.PI * shockWave.range) - 1; + final double dtheta = 360.0 / (2 * Math.PI * shockWave.range) - 1; for (double theta = 0; theta < 360; theta += dtheta) { - double rtheta = Math.toRadians(theta); - Vector vector = new Vector(Math.cos(rtheta), 0, Math.sin(rtheta)); + final double rtheta = Math.toRadians(theta); + final Vector vector = new Vector(Math.cos(rtheta), 0, Math.sin(rtheta)); if (vector.angle(player.getEyeLocation().getDirection()) < shockWave.angle) { new Ripple(player, vector.normalize()); } @@ -124,12 +124,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -143,46 +143,46 @@ public boolean isHarmlessAbility() { } public boolean isCharged() { - return charged; + return this.charged; } - public void setCharged(boolean charged) { + public void setCharged(final boolean charged) { this.charged = charged; } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public double getAngle() { - return angle; + return this.angle; } - public void setAngle(double angle) { + public void setAngle(final double angle) { this.angle = angle; } public double getThreshold() { - return threshold; + return this.threshold; } - public void setThreshold(double threshold) { + public void setThreshold(final double threshold) { this.threshold = threshold; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/earthbending/Tremorsense.java b/src/com/projectkorra/projectkorra/earthbending/Tremorsense.java index 146ccfb47..c5811fd97 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Tremorsense.java +++ b/src/com/projectkorra/projectkorra/earthbending/Tremorsense.java @@ -1,8 +1,7 @@ package com.projectkorra.projectkorra.earthbending; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.EarthAbility; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; @@ -12,11 +11,13 @@ import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.EarthAbility; public class Tremorsense extends EarthAbility { + @Deprecated private static final Map BLOCKS = new ConcurrentHashMap(); private byte lightThreshold; @@ -24,23 +25,24 @@ public class Tremorsense extends EarthAbility { private int radius; private long cooldown; private Block block; + private int stickyRange; - public Tremorsense(Player player, boolean clicked) { + public Tremorsense(final Player player, final boolean clicked) { super(player); - if (!bPlayer.canBendIgnoreBinds(this)) { + if (!this.bPlayer.canBendIgnoreBinds(this)) { return; } - setFields(); - byte lightLevel = player.getLocation().getBlock().getLightLevel(); + this.setFields(); + final byte lightLevel = player.getLocation().getBlock().getLightLevel(); - if (lightLevel < this.lightThreshold && isEarthbendable(player.getLocation().getBlock().getRelative(BlockFace.DOWN))) { + if (lightLevel < this.lightThreshold && this.isEarthbendable(player.getLocation().getBlock().getRelative(BlockFace.DOWN))) { if (clicked) { - bPlayer.addCooldown(this); - activate(); + this.bPlayer.addCooldown(this); + this.activate(); } - start(); + this.start(); } } @@ -49,93 +51,99 @@ private void setFields() { this.radius = getConfig().getInt("Abilities.Earth.Tremorsense.Radius"); this.lightThreshold = (byte) getConfig().getInt("Abilities.Earth.Tremorsense.LightThreshold"); this.cooldown = getConfig().getLong("Abilities.Earth.Tremorsense.Cooldown"); + this.stickyRange = getConfig().getInt("Abilities.Earth.Tremorsense.StickyRange"); } private void activate() { - Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN); - for (int i = -radius; i <= radius; i++) { - for (int j = -radius; j <= radius; j++) { + final Block block = this.player.getLocation().getBlock().getRelative(BlockFace.DOWN); + for (int i = -this.radius; i <= this.radius; i++) { + for (int j = -this.radius; j <= this.radius; j++) { boolean earth = false; boolean foundAir = false; Block smokeBlock = null; - for (int k = 0; k <= maxDepth; k++) { - Block blocki = block.getRelative(BlockFace.EAST, i).getRelative(BlockFace.NORTH, j).getRelative(BlockFace.DOWN, k); + for (int k = 0; k <= this.maxDepth; k++) { + final Block blocki = block.getRelative(BlockFace.EAST, i).getRelative(BlockFace.NORTH, j).getRelative(BlockFace.DOWN, k); if (GeneralMethods.isRegionProtectedFromBuild(this, blocki.getLocation())) { continue; } - if (isEarthbendable(blocki) && !earth) { + if (this.isEarthbendable(blocki) && !earth) { earth = true; smokeBlock = blocki; - } else if (!isEarthbendable(blocki) && earth) { + } else if (!this.isEarthbendable(blocki) && earth) { foundAir = true; break; - } else if (!isEarthbendable(blocki) && !earth && blocki.getType() != Material.AIR) { + } else if (!this.isEarthbendable(blocki) && !earth && blocki.getType() != Material.AIR) { break; } } if (foundAir) { - smokeBlock.getWorld().playEffect(smokeBlock.getRelative(BlockFace.UP).getLocation(), Effect.SMOKE, 4, radius); + smokeBlock.getWorld().playEffect(smokeBlock.getRelative(BlockFace.UP).getLocation(), Effect.SMOKE, 4, this.radius); } } } } - @SuppressWarnings("deprecation") private void tryToSetGlowBlock() { - Block standBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN); - if (!bPlayer.isTremorSensing()) { - if (block != null) { - remove(); + final Block standBlock = this.player.getLocation().getBlock().getRelative(BlockFace.DOWN); + if (!this.bPlayer.isTremorSensing()) { + if (this.block != null) { + this.remove(); } return; } - boolean isBendable = isEarthbendable(standBlock); + final boolean isBendable = this.isEarthbendable(standBlock); - if (isBendable && block == null) { - block = standBlock; - player.sendBlockChange(block.getLocation(), 89, (byte) 1); - } else if (isBendable && !block.equals(standBlock)) { - revertGlowBlock(); - block = standBlock; - player.sendBlockChange(block.getLocation(), 89, (byte) 1); - } else if (block == null) { + if (isBendable && this.block == null) { + this.block = standBlock; + this.player.sendBlockChange(this.block.getLocation(), 89, (byte) 1); + } else if (isBendable && !this.block.equals(standBlock)) { + this.revertGlowBlock(); + this.block = standBlock; + this.player.sendBlockChange(this.block.getLocation(), 89, (byte) 1); + } else if (this.block == null) { return; - } else if (!player.getWorld().equals(block.getWorld())) { - remove(); + } else if (!this.player.getWorld().equals(this.block.getWorld())) { + this.remove(); return; } else if (!isBendable) { - revertGlowBlock(); + if (this.stickyRange > 0) { + if (standBlock.getLocation().distanceSquared(this.block.getLocation()) > this.stickyRange * this.stickyRange) { + this.revertGlowBlock(); + } + } else { + this.revertGlowBlock(); + } + return; } } - @SuppressWarnings("deprecation") public void revertGlowBlock() { - if (block != null) { - player.sendBlockChange(block.getLocation(), block.getTypeId(), block.getData()); + if (this.block != null) { + this.player.sendBlockChange(this.block.getLocation(), this.block.getTypeId(), this.block.getData()); } } @Override public void remove() { super.remove(); - revertGlowBlock(); + this.revertGlowBlock(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this) || player.getLocation().getBlock().getLightLevel() > lightThreshold) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this) || this.player.getLocation().getBlock().getLightLevel() > this.lightThreshold) { + this.remove(); return; } else { - tryToSetGlowBlock(); + this.tryToSetGlowBlock(); } } - public static void manage(Server server) { - for (Player player : server.getOnlinePlayers()) { + public static void manage(final Server server) { + for (final Player player : server.getOnlinePlayers()) { if (canTremorSense(player) && !hasAbility(player, Tremorsense.class)) { new Tremorsense(player, false); @@ -143,8 +151,8 @@ public static void manage(Server server) { } } - public static boolean canTremorSense(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean canTremorSense(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer != null && bPlayer.canBendIgnoreBindsCooldowns(getAbility("Tremorsense"))) { return true; @@ -153,6 +161,8 @@ public static boolean canTremorSense(Player player) { return false; } + @Deprecated + /** No longer used; will be removed in the next version. */ public static Map getBlocks() { return BLOCKS; } @@ -164,12 +174,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -183,38 +193,38 @@ public boolean isHarmlessAbility() { } public byte getLightThreshold() { - return lightThreshold; + return this.lightThreshold; } - public void setLightThreshold(byte lightThreshold) { + public void setLightThreshold(final byte lightThreshold) { this.lightThreshold = lightThreshold; } public int getMaxDepth() { - return maxDepth; + return this.maxDepth; } - public void setMaxDepth(int maxDepth) { + public void setMaxDepth(final int maxDepth) { this.maxDepth = maxDepth; } public int getRadius() { - return radius; + return this.radius; } - public void setRadius(int radius) { + public void setRadius(final int radius) { this.radius = radius; } public Block getBlock() { - return block; + return this.block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeOthers.java b/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeOthers.java new file mode 100644 index 000000000..ac62f043e --- /dev/null +++ b/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeOthers.java @@ -0,0 +1,127 @@ +package com.projectkorra.projectkorra.earthbending.combo; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.earthbending.EarthDome; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.ParticleEffect.BlockData; + +public class EarthDomeOthers extends EarthAbility { + + public Vector direction; + public double range = 0, maxRange; + public Location loc; + + public EarthDomeOthers(final Player player) { + super(player); + + if (this.bPlayer.isOnCooldown("EarthDome")) { + return; + } + this.loc = player.getLocation().clone(); + + if (GeneralMethods.isRegionProtectedFromBuild(player, this.loc)) { + return; + } + if (!isEarthbendable(this.loc.getBlock().getRelative(BlockFace.DOWN).getType(), true, true, true)) { + return; + } + this.direction = this.loc.getDirection().setY(0); + this.maxRange = getConfig().getDouble("Abilities.Earth.EarthDome.Range"); + this.start(); + } + + @Override + public void progress() { + if (!this.player.isOnline() || this.player.isDead()) { + this.remove(true); + return; + } + if (this.range >= this.maxRange) { + this.remove(true); + return; + } + if (GeneralMethods.isRegionProtectedFromBuild(this.player, this.loc)) { + this.remove(true); + return; + } + + this.range++; + this.loc.add(this.direction.normalize()); + Block top = GeneralMethods.getTopBlock(this.loc, 2); + + while (!this.isEarthbendable(top)) { + if (this.isTransparent(top)) { + top = top.getRelative(BlockFace.DOWN); + } else { + this.remove(true); + return; + } + } + + if (!this.isTransparent(top.getRelative(BlockFace.UP))) { + this.remove(true); + return; + } + + this.loc.setY(top.getY() + 1); + + ParticleEffect.CRIT.display(this.loc, 0.4f, 0, 0.4f, 0.001f, 9); + ParticleEffect.BLOCK_DUST.display(new BlockData(this.loc.getBlock().getRelative(BlockFace.DOWN).getType(), (byte) 0), 0.2f, 0.1f, 0.2f, 0.001f, 7, this.loc, 255); + + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.loc, 2)) { + if (!(entity instanceof LivingEntity) || entity.getEntityId() == this.player.getEntityId()) { + continue; + } + + new EarthDome(this.player, entity.getLocation().clone().subtract(0, 1, 0)); + this.remove(false); + return; + } + } + + public void remove(final boolean cooldown) { + super.remove(); + if (cooldown) { + this.bPlayer.addCooldown("EarthDome", getConfig().getLong("Abilities.Earth.EarthDome.Cooldown")); + } + } + + @Override + public boolean isSneakAbility() { + return false; + } + + @Override + public boolean isHarmlessAbility() { + return false; + } + + @Override + public long getCooldown() { + return 0; + } + + @Override + public String getName() { + return "EarthDome"; + } + + @Override + public Location getLocation() { + return this.loc != null ? this.loc : null; + } + + @Override + public boolean isHiddenAbility() { + return true; + } +} diff --git a/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeSelf.java b/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeSelf.java new file mode 100644 index 000000000..349198716 --- /dev/null +++ b/src/com/projectkorra/projectkorra/earthbending/combo/EarthDomeSelf.java @@ -0,0 +1,68 @@ +package com.projectkorra.projectkorra.earthbending.combo; + +import java.util.ArrayList; + +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import com.projectkorra.projectkorra.ability.ComboAbility; +import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.earthbending.EarthDome; +import com.projectkorra.projectkorra.util.ClickType; + +public class EarthDomeSelf extends EarthAbility implements ComboAbility { + + public EarthDomeSelf(final Player player) { + super(player); + + new EarthDome(player); + } + + @Override + public void progress() { + } + + @Override + public boolean isSneakAbility() { + return false; + } + + @Override + public boolean isHarmlessAbility() { + return false; + } + + @Override + public long getCooldown() { + return 0; + } + + @Override + public String getName() { + return "EarthDome"; + } + + @Override + public Location getLocation() { + return null; + } + + @Override + public Object createNewComboInstance(final Player player) { + return new EarthDomeSelf(player); + } + + @Override + public ArrayList getCombination() { + final ArrayList combo = new ArrayList<>(); + combo.add(new AbilityInformation("RaiseEarth", ClickType.RIGHT_CLICK_BLOCK)); + combo.add(new AbilityInformation("Shockwave", ClickType.RIGHT_CLICK_BLOCK)); + return combo; + } + + @Override + public String getInstructions() { + return "\n(Self) RaiseEarth (Right click) > Shockwave (Right click)\n(Projection) RaiseEarth(Right click) > Shockwave (Left click)"; + } +} diff --git a/src/com/projectkorra/projectkorra/earthbending/combo/EarthPillars.java b/src/com/projectkorra/projectkorra/earthbending/combo/EarthPillars.java new file mode 100644 index 000000000..122a12e43 --- /dev/null +++ b/src/com/projectkorra/projectkorra/earthbending/combo/EarthPillars.java @@ -0,0 +1,155 @@ +package com.projectkorra.projectkorra.earthbending.combo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bukkit.Location; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.ComboAbility; +import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.earthbending.RaiseEarth; +import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.ParticleEffect.BlockData; + +public class EarthPillars extends EarthAbility implements ComboAbility { + public double radius, damage, power, fallThreshold; + public boolean damaging; + public Map entities; + + public EarthPillars(final Player player, final boolean fall) { + super(player); + this.setFields(fall); + + if (!this.bPlayer.canBendIgnoreBinds(this) || !isEarthbendable(player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(), true, true, false)) { + return; + } + + if (fall) { + if (player.getFallDistance() < this.fallThreshold) { + return; + } + } + + for (final Entity e : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), this.radius)) { + if (e instanceof LivingEntity && e.getEntityId() != player.getEntityId() && isEarthbendable(e.getLocation().getBlock().getRelative(BlockFace.DOWN).getType(), true, true, false)) { + ParticleEffect.BLOCK_DUST.display(new BlockData(e.getLocation().clone().subtract(0, 1, 0).getBlock().getType(), (byte) 0), 1f, 0.1f, 1f, 0, 6, e.getLocation(), 255); + this.affect((LivingEntity) e); + } + } + + if (this.entities.isEmpty()) { + return; + } + + this.start(); + } + + private void setFields(final boolean fall) { + this.radius = getConfig().getDouble("Abilities.Earth.EarthPillars.Radius"); + this.damage = getConfig().getDouble("Abilities.Earth.EarthPillars.Damage.Value"); + this.power = getConfig().getDouble("Abilities.Earth.EarthPillars.Power"); + this.damaging = getConfig().getBoolean("Abilities.Earth.EarthPillars.Damage.Enabled"); + this.entities = new HashMap<>(); + + if (fall) { + this.fallThreshold = getConfig().getDouble("Abilities.Earth.EarthPillars.FallThreshold"); + this.damaging = true; + this.damage *= this.power; + this.radius = this.fallThreshold; + this.power += (this.player.getFallDistance() > this.fallThreshold ? this.player.getFallDistance() : this.fallThreshold) / 100; + } + } + + public void affect(final LivingEntity lent) { + final RaiseEarth re = new RaiseEarth(this.player, lent.getLocation().clone().subtract(0, 1, 0), 3); + this.entities.put(re, lent); + } + + @Override + public void progress() { + final List removal = new ArrayList<>(); + for (final RaiseEarth abil : this.entities.keySet()) { + if (abil.isRemoved() && abil.isStarted()) { + final LivingEntity lent = this.entities.get(abil); + if (!lent.isDead()) { + if (lent instanceof Player && !((Player) lent).isOnline()) { + continue; + } + + lent.setVelocity(new Vector(0, this.power, 0)); + } + if (this.damaging) { + DamageHandler.damageEntity(lent, this.damage, this); + } + + removal.add(abil); + } + } + + for (final RaiseEarth remove : removal) { + this.entities.remove(remove); + } + + if (this.entities.isEmpty()) { + this.bPlayer.addCooldown(this); + this.remove(); + return; + } + } + + @Override + public boolean isSneakAbility() { + return true; + } + + @Override + public boolean isHarmlessAbility() { + return false; + } + + @Override + public long getCooldown() { + return getConfig().getLong("Abilities.Earth.EarthPillars.Cooldown"); + } + + @Override + public String getName() { + return "EarthPillars"; + } + + @Override + public Location getLocation() { + return null; + } + + @Override + public Object createNewComboInstance(final Player player) { + return new EarthPillars(player, false); + } + + @Override + public ArrayList getCombination() { + final ArrayList earthPillars = new ArrayList<>(); + earthPillars.add(new AbilityInformation("Shockwave", ClickType.SHIFT_DOWN)); + earthPillars.add(new AbilityInformation("Shockwave", ClickType.SHIFT_UP)); + earthPillars.add(new AbilityInformation("Shockwave", ClickType.SHIFT_DOWN)); + earthPillars.add(new AbilityInformation("Catapult", ClickType.SHIFT_UP)); + return earthPillars; + } + + @Override + public String getInstructions() { + return "Shockwave (Tap sneak) > Shockwave (Hold sneak) > Catapult (Release sneak)"; + } +} diff --git a/src/com/projectkorra/projectkorra/earthbending/lava/LavaFlow.java b/src/com/projectkorra/projectkorra/earthbending/lava/LavaFlow.java index c0ad5f6a2..d87540310 100644 --- a/src/com/projectkorra/projectkorra/earthbending/lava/LavaFlow.java +++ b/src/com/projectkorra/projectkorra/earthbending/lava/LavaFlow.java @@ -8,11 +8,11 @@ import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.World; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; @@ -30,11 +30,8 @@ public static enum AbilityType { } private static final Map TEMP_LAVA_BLOCKS = new ConcurrentHashMap<>(); - public static final Map TEMP_LAVA_BLOCKS_BY_TEMPBLOCK = new ConcurrentHashMap<>(); private static final Map TEMP_LAND_BLOCKS = new ConcurrentHashMap<>(); - private static final Map TEMP_LAND_BLOCKS_BY_TEMPBLOCK = new ConcurrentHashMap<>(); private static final Map TEMP_AIR_BLOCKS = new ConcurrentHashMap<>(); - private static final Map TEMP_AIR_BLOCKS_BY_TEMPBLOCK = new ConcurrentHashMap<>(); private boolean removing; private boolean makeLava; @@ -77,13 +74,13 @@ public static enum AbilityType { * cooldowns. The ability is not guaranteed to continue, it may be the case * that the player doesn't have the correct permissions to bend this * ability. - * + * * @param player the player that bended the ability * @param type either shift or sneak */ - public LavaFlow(Player player, AbilityType type) { + public LavaFlow(final Player player, final AbilityType type) { super(player); - if (!bPlayer.canLavabend()) { + if (!this.bPlayer.canLavabend()) { return; } @@ -122,46 +119,46 @@ public LavaFlow(Player player, AbilityType type) { this.downwardFlow = getConfig().getInt("Abilities.Earth.LavaFlow.DownwardFlow"); this.allowNaturalFlow = getConfig().getBoolean("Abilities.Earth.LavaFlow.AllowNaturalFlow"); - if (bPlayer.isAvatarState()) { - shiftCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftCooldown"); - clickLavaCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickLavaCooldown"); - clickLandCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickLandCooldown"); - shiftPlatformRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftPlatformRadius"); - clickLavaRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickRadius"); - shiftMaxRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftRadius"); + if (this.bPlayer.isAvatarState()) { + this.shiftCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftCooldown"); + this.clickLavaCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickLavaCooldown"); + this.clickLandCooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickLandCooldown"); + this.shiftPlatformRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftPlatformRadius"); + this.clickLavaRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ClickRadius"); + this.shiftMaxRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.LavaFlow.ShiftRadius"); } if (type == AbilityType.SHIFT) { - // Update the shift counter for all the player's LavaFlows - ArrayList shiftFlows = LavaFlow.getLavaFlow(player, LavaFlow.AbilityType.SHIFT); + // Update the shift counter for all the player's LavaFlows. + final ArrayList shiftFlows = LavaFlow.getLavaFlow(player, LavaFlow.AbilityType.SHIFT); if (shiftFlows.size() > 0 && !player.isSneaking()) { - for (LavaFlow lavaFlow : shiftFlows) { + for (final LavaFlow lavaFlow : shiftFlows) { lavaFlow.shiftCounter++; } } - if (bPlayer.isOnCooldown("LavaFlow")) { - removeSlowly(); + if (this.bPlayer.isOnCooldown("LavaFlow")) { + this.removeSlowly(); return; } - start(); + this.start(); } else if (type == AbilityType.CLICK) { - Block sourceBlock = BlockSource.getEarthOrLavaSourceBlock(player, clickRange, ClickType.LEFT_CLICK); + final Block sourceBlock = BlockSource.getEarthOrLavaSourceBlock(player, this.clickRange, ClickType.LEFT_CLICK); if (sourceBlock == null) { - removeSlowly(); + this.removeSlowly(); return; } - long cooldown = makeLava ? clickLavaCooldown : clickLandCooldown; - origin = sourceBlock.getLocation(); - makeLava = !isLava(sourceBlock); - if (bPlayer.isOnCooldown("LavaFlow")) { - removeSlowly(); + final long cooldown = this.makeLava ? this.clickLavaCooldown : this.clickLandCooldown; + this.origin = sourceBlock.getLocation(); + this.makeLava = !isLava(sourceBlock); + if (this.bPlayer.isOnCooldown("LavaFlow")) { + this.removeSlowly(); return; } else { - bPlayer.addCooldown("LavaFlow", cooldown); + this.bPlayer.addCooldown("LavaFlow", cooldown); } - start(); + this.start(); } } @@ -172,128 +169,129 @@ public LavaFlow(Player player, AbilityType type) { */ @Override public void progress() { - if (shiftCounter > 0 && type == AbilityType.SHIFT) { - removeSlowly(); + if (this.shiftCounter > 0 && this.type == AbilityType.SHIFT) { + this.removeSlowly(); return; - } else if (removing) { + } else if (this.removing) { return; - } else if (player.isDead() || !player.isOnline() || player.getWorld() != this.world) { - removeSlowly(); + } else if (this.player.isDead() || !this.player.isOnline() || this.player.getWorld() != this.world) { + this.removeSlowly(); return; } - Random random = new Random(); + final Random random = new Random(); - if (type == AbilityType.SHIFT) { - if (System.currentTimeMillis() - time > shiftRemoveDelay) { - removeSlowly(); + if (this.type == AbilityType.SHIFT) { + if (System.currentTimeMillis() - this.time > this.shiftRemoveDelay) { + this.removeSlowly(); return; } - if (!player.isSneaking() && !removing) { - if (affectedBlocks.size() > 0) { - removeOnDelay(); - removing = true; - bPlayer.addCooldown("LavaFlow", shiftCooldown); + if (!this.player.isSneaking() && !this.removing) { + if (this.affectedBlocks.size() > 0) { + this.removeOnDelay(); + this.removing = true; + this.bPlayer.addCooldown("LavaFlow", this.shiftCooldown); } else { - removeSlowly(); + this.removeSlowly(); } return; } - if (!bPlayer.canBendIgnoreCooldowns(this)) { - removeSlowly(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.removeSlowly(); return; - } else if (origin == null) { - origin = player.getLocation().clone().add(0, -1, 0); - if (!isEarthbendable(origin.getBlock()) && origin.getBlock().getType() != Material.GLOWSTONE) { - removeSlowly(); + } else if (this.origin == null) { + this.origin = this.player.getLocation().clone().add(0, -1, 0); + if (!this.isEarthbendable(this.origin.getBlock()) && this.origin.getBlock().getType() != Material.GLOWSTONE) { + this.removeSlowly(); return; } } - for (double x = -currentRadius; x <= currentRadius + particleOffset; x++) { - for (double z = -currentRadius; z < currentRadius + particleOffset; z++) { - Location loc = origin.clone().add(x, 0, z); - Block block = GeneralMethods.getTopBlock(loc, upwardFlow, downwardFlow); + for (double x = -this.currentRadius; x <= this.currentRadius + this.particleOffset; x++) { + for (double z = -this.currentRadius; z < this.currentRadius + this.particleOffset; z++) { + final Location loc = this.origin.clone().add(x, 0, z); + final Block block = GeneralMethods.getTopBlock(loc, this.upwardFlow, this.downwardFlow); if (block == null) { continue; } - double dSquared = distanceSquaredXZ(block.getLocation(), origin); - if (dSquared > Math.pow(shiftPlatformRadius, 2)) { - if (dSquared < Math.pow(currentRadius, 2) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - if (dSquared < shiftPlatformRadius * 4 || getAdjacentLavaBlocks(block.getLocation()).size() > 0) { + final double dSquared = distanceSquaredXZ(block.getLocation(), this.origin); + if (dSquared > Math.pow(this.shiftPlatformRadius, 2)) { + if (dSquared < Math.pow(this.currentRadius, 2) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { + if (dSquared < this.shiftPlatformRadius * 4 || this.getAdjacentLavaBlocks(block.getLocation()).size() > 0) { if (!isLava(block)) { if (isPlant(block) || isSnow(block)) { - Block lower = block.getRelative(BlockFace.DOWN); + final Block lower = block.getRelative(BlockFace.DOWN); if (isPlant(lower) || isSnow(lower)) { - Block lower2 = lower.getRelative(BlockFace.DOWN); + final Block lower2 = lower.getRelative(BlockFace.DOWN); if (!isEarth(lower2) && !isSand(lower2) && !isMetal(lower2)) { continue; } - createLava(lower2); + this.createLava(lower2); } else { if (!isEarth(lower) && !isSand(lower) && !isMetal(lower)) { continue; } - createLava(lower); + this.createLava(lower); } } else { if (!isEarth(block) && !isSand(block) && !isMetal(block)) { continue; } - createLava(block); + this.createLava(block); } } } - } else if (Math.random() < particleDensity && dSquared < Math.pow(currentRadius + particleDensity, 2) && currentRadius + particleDensity < shiftMaxRadius && random.nextInt(3) == 0) { + } else if (Math.random() < this.particleDensity && dSquared < Math.pow(this.currentRadius + this.particleDensity, 2) && this.currentRadius + this.particleDensity < this.shiftMaxRadius && random.nextInt(3) == 0) { ParticleEffect.LAVA.display(loc, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 1); } } } - if (!shiftIsFinished) { + if (!this.shiftIsFinished) { if (random.nextInt(10) == 0) { - ParticleEffect.LAVA.display(player.getLocation(), (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 1); + ParticleEffect.LAVA.display(this.player.getLocation(), (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 1); } } - currentRadius += shiftFlowSpeed; - if (currentRadius > shiftMaxRadius) { - currentRadius = shiftMaxRadius; - shiftIsFinished = true; + this.currentRadius += this.shiftFlowSpeed; + if (this.currentRadius > this.shiftMaxRadius) { + this.currentRadius = this.shiftMaxRadius; + this.shiftIsFinished = true; } } - } else if (type == AbilityType.CLICK) { + } else if (this.type == AbilityType.CLICK) { /* * The variable makeLava refers to whether or not the ability is * trying to remove land in place of lava or if makeLava = false * then lava is being replaced with land. - * + * * Notice we have separate variables between both versions, because * most of the time making lava will have longer delays and longer * cooldowns. */ - long curTime = System.currentTimeMillis() - time; - double delay = makeLava ? clickLavaDelay : clickLandDelay; + final long curTime = System.currentTimeMillis() - this.time; + final double delay = this.makeLava ? this.clickLavaDelay : this.clickLandDelay; - if (makeLava && curTime > clickLavaCleanupDelay) { - removeSlowly(); + if (this.makeLava && curTime > this.clickLavaCleanupDelay) { + this.makeLava = false; + this.removeSlowly(); return; - } else if (!makeLava && curTime > clickLandCleanupDelay) { - removeSlowly(); + } else if (!this.makeLava && curTime > this.clickLandCleanupDelay) { + this.removeSlowly(); return; - } else if (!makeLava && curTime < delay) { + } else if (!this.makeLava && curTime < delay) { return; - } else if (makeLava && curTime < delay) { - for (double x = -clickLavaRadius; x <= clickLavaRadius; x++) { - for (double z = -clickLavaRadius; z <= clickLavaRadius; z++) { - Location loc = origin.clone().add(x, 0, z); - Block tempBlock = GeneralMethods.getTopBlock(loc, upwardFlow, downwardFlow); + } else if (this.makeLava && curTime < delay) { + for (double x = -this.clickLavaRadius; x <= this.clickLavaRadius; x++) { + for (double z = -this.clickLavaRadius; z <= this.clickLavaRadius; z++) { + final Location loc = this.origin.clone().add(x, 0, z); + final Block tempBlock = GeneralMethods.getTopBlock(loc, this.upwardFlow, this.downwardFlow); if (!isWater(tempBlock)) { - if (tempBlock != null && !isLava(tempBlock) && Math.random() < particleDensity && tempBlock.getLocation().distanceSquared(origin) <= Math.pow(clickLavaRadius, 2)) { - if (random.nextInt(3) == 0) { + if (tempBlock != null && !isLava(tempBlock) && Math.random() < this.particleDensity && tempBlock.getLocation().distanceSquared(this.origin) <= Math.pow(this.clickLavaRadius, 2)) { + if (random.nextInt(5) == 0) { ParticleEffect.LAVA.display(loc, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 1); } } @@ -308,56 +306,56 @@ public void progress() { * created then we are finished with this instance of LavaFlow, but * we need to keep it running so that we can revert the blocks. */ - if (!clickIsFinished) { - clickIsFinished = true; - double radius = makeLava ? clickLavaRadius : clickLandRadius; + if (!this.clickIsFinished) { + this.clickIsFinished = true; + final double radius = this.makeLava ? this.clickLavaRadius : this.clickLandRadius; for (double x = -radius; x <= radius; x++) { for (double z = -radius; z <= radius; z++) { - Location loc = origin.clone().add(x, 0, z); - Block tempBlock = GeneralMethods.getTopBlock(loc, upwardFlow, downwardFlow); + final Location loc = this.origin.clone().add(x, 0, z); + final Block tempBlock = GeneralMethods.getTopBlock(loc, this.upwardFlow, this.downwardFlow); - double dSquared = distanceSquaredXZ(tempBlock.getLocation(), origin); + final double dSquared = distanceSquaredXZ(tempBlock.getLocation(), this.origin); if (dSquared < Math.pow(radius, 2) && !GeneralMethods.isRegionProtectedFromBuild(this, loc)) { - if (makeLava && !isLava(tempBlock)) { - clickIsFinished = false; - if (Math.random() < lavaCreateSpeed) { + if (this.makeLava && !isLava(tempBlock)) { + this.clickIsFinished = false; + if (Math.random() < this.lavaCreateSpeed) { if (!isLava(tempBlock) || isSnow(tempBlock)) { if (isPlant(tempBlock) || isSnow(tempBlock)) { - Block lower = tempBlock.getRelative(BlockFace.DOWN); + final Block lower = tempBlock.getRelative(BlockFace.DOWN); if (isPlant(lower) || isSnow(lower)) { - Block lower2 = lower.getRelative(BlockFace.DOWN); + final Block lower2 = lower.getRelative(BlockFace.DOWN); if (!isEarth(lower2) && !isSand(lower2) && !isMetal(lower2)) { continue; } - createLava(lower2); + this.createLava(lower2); } else { if (!isEarth(lower) && !isSand(lower) && !isMetal(lower)) { continue; } - createLava(lower); + this.createLava(lower); } } else { if (!isEarth(tempBlock) && !isSand(tempBlock) && !isMetal(tempBlock)) { continue; } - createLava(tempBlock); + this.createLava(tempBlock); } } } else { if (random.nextInt(4) == 0) { - Block block = loc.getBlock(); - Block above = block.getRelative(BlockFace.UP); - Block above2 = above.getRelative(BlockFace.UP); - if (!isWater(block) && !isWater(above) && !isWater(above2)) { + final Block block = loc.getBlock(); + final Block above = block.getRelative(BlockFace.UP); + + if ((isEarth(block) || isSand(block) || isMetal(block)) && !isWater(above)) { ParticleEffect.LAVA.display(loc, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 1); } } } - } else if (!makeLava && isLava(tempBlock)) { - clickIsFinished = false; - if (Math.random() < landCreateSpeed) { - removeLava(tempBlock); + } else if (!this.makeLava && isLava(tempBlock)) { + this.clickIsFinished = false; + if (Math.random() < this.landCreateSpeed) { + this.removeLava(tempBlock); } } } @@ -371,45 +369,42 @@ public void progress() { /** * Creates a LavaBlock and appends the TempBlock to our arraylist called * TEMP_LAVA_BLOCKS. - * + * * If ALLOW_NATURAL_FLOW is turned on then this method will remove the block * from TempBlock.instances, which will allow the lava to flow naturally. - * + * * @param block the block that will be turned to lava */ - public void createLava(Block block) { + public void createLava(final Block block) { if (isEarth(block) || isSand(block) || isMetal(block)) { if (isPlant(block.getRelative(BlockFace.UP)) || isSnow(block.getRelative(BlockFace.UP))) { - Block above = block.getRelative(BlockFace.UP); - Block above2 = above.getRelative(BlockFace.UP); + final Block above = block.getRelative(BlockFace.UP); + final Block above2 = above.getRelative(BlockFace.UP); if (isPlant(above) || isSnow(above)) { - TempBlock tb = new TempBlock(above, Material.AIR, (byte) 0); + final TempBlock tb = new TempBlock(above, Material.AIR, (byte) 0); TEMP_AIR_BLOCKS.put(above, tb); - TEMP_AIR_BLOCKS_BY_TEMPBLOCK.put(tb, above); - affectedBlocks.add(tb); + this.affectedBlocks.add(tb); if (isPlant(above2) && above2.getType().equals(Material.DOUBLE_PLANT)) { - TempBlock tb2 = new TempBlock(above2, Material.AIR, (byte) 0); + final TempBlock tb2 = new TempBlock(above2, Material.AIR, (byte) 0); TEMP_AIR_BLOCKS.put(above2, tb2); - TEMP_AIR_BLOCKS_BY_TEMPBLOCK.put(tb2, above2); - affectedBlocks.add(tb); + this.affectedBlocks.add(tb); } - } else + } else { return; + } } TempBlock tblock; - if(allowNaturalFlow) { + if (this.allowNaturalFlow) { tblock = new TempBlock(block, Material.LAVA, (byte) 0); - } - else { + } else { tblock = new TempBlock(block, Material.STATIONARY_LAVA, (byte) 0); } - - if(tblock!=null) { + + if (tblock != null) { TEMP_LAVA_BLOCKS.put(block, tblock); - TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.put(tblock, block); - affectedBlocks.add(tblock); + this.affectedBlocks.add(tblock); - if (allowNaturalFlow) { + if (this.allowNaturalFlow) { TempBlock.removeBlock(block); } } @@ -418,24 +413,50 @@ public void createLava(Block block) { /** * Removes a lava block if it is inside of our ArrayList of TempBlocks. - * + * * @param testBlock the block to attempt to remove */ - @SuppressWarnings("deprecation") - public void removeLava(Block testBlock) { + public void removeLava(final Block testBlock) { if (TEMP_LAVA_BLOCKS.containsKey(testBlock)) { - TempBlock tb = TEMP_LAVA_BLOCKS.get(testBlock); + final TempBlock tb = TEMP_LAVA_BLOCKS.get(testBlock); tb.revertBlock(); TEMP_LAVA_BLOCKS.remove(testBlock); - TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.remove(tb); - affectedBlocks.remove(tb); + this.affectedBlocks.remove(tb); return; } - TempBlock tblock = new TempBlock(testBlock, revertMaterial, testBlock.getData()); - affectedBlocks.add(tblock); + final TempBlock tblock = new TempBlock(testBlock, this.revertMaterial, testBlock.getData()); + this.affectedBlocks.add(tblock); TEMP_LAND_BLOCKS.put(testBlock, tblock); - TEMP_LAND_BLOCKS_BY_TEMPBLOCK.put(tblock, testBlock); + } + + public static boolean isLavaFlowBlock(final Block block) { + return isLavaFlowBlock(TEMP_AIR_BLOCKS, block) || isLavaFlowBlock(TEMP_LAND_BLOCKS, block) || isLavaFlowBlock(TEMP_LAVA_BLOCKS, block); + } + + private static boolean isLavaFlowBlock(final Map map, final Block block) { + return map.containsKey(block); + } + + public static boolean removeBlock(final Block block) { + return removeBlock(TEMP_AIR_BLOCKS, block) || removeBlock(TEMP_LAND_BLOCKS, block) || removeBlock(TEMP_LAVA_BLOCKS, block); + } + + private static boolean removeBlock(final Map map, final Block block) { + if (map.containsKey(block)) { + final TempBlock tb = map.get(block); + map.remove(block); + + for (final LavaFlow lavaflow : CoreAbility.getAbilities(LavaFlow.class)) { + lavaflow.getAffectedBlocks().remove(tb); + } + + tb.revertBlock(); + + return true; + } + + return false; } /** @@ -444,59 +465,57 @@ public void removeLava(Block testBlock) { * automatically clean up over time. */ public void removeOnDelay() { - BukkitRunnable br = new BukkitRunnable() { + final BukkitRunnable br = new BukkitRunnable() { @Override public void run() { - removeSlowly(); + LavaFlow.this.removeSlowly(); } }; - br.runTaskLater(ProjectKorra.plugin, (long) (shiftRemoveDelay / 1000.0 * 20.0)); - tasks.add(br); + br.runTaskLater(ProjectKorra.plugin, (long) (this.shiftRemoveDelay / 1000.0 * 20.0)); + this.tasks.add(br); } /** * Removes this instance of LavaFlow, cleans up any blocks that are * remaining in TEMP_LAVA_BLOCKS, and cancels any remaining tasks. - * + * * This version of remove will create tasks that remove each lava block with * an animation. */ public void removeSlowly() { super.remove(); - for (int i = affectedBlocks.size() - 1; i > -1; i--) { - final TempBlock tblock = affectedBlocks.get(i); + for (int i = this.affectedBlocks.size() - 1; i > -1; i--) { + final TempBlock tblock = this.affectedBlocks.get(i); final boolean isTempAir = TEMP_AIR_BLOCKS.values().contains(tblock); + new BukkitRunnable() { - @SuppressWarnings("deprecation") + @Override public void run() { tblock.revertBlock(); + + if (TEMP_LAVA_BLOCKS.values().contains(tblock)) { + LavaFlow.this.affectedBlocks.remove(tblock); + TEMP_LAVA_BLOCKS.remove(tblock.getBlock()); + } + if (TEMP_LAND_BLOCKS.values().contains(tblock)) { + LavaFlow.this.affectedBlocks.remove(tblock); + TEMP_LAND_BLOCKS.remove(tblock.getBlock()); + } + if (TEMP_AIR_BLOCKS.values().contains(tblock)) { + LavaFlow.this.affectedBlocks.remove(tblock); + TEMP_AIR_BLOCKS.remove(tblock.getBlock()); + } + if (isTempAir && tblock.getState().getType() == Material.DOUBLE_PLANT) { tblock.getBlock().getRelative(BlockFace.UP).setType(Material.DOUBLE_PLANT); tblock.getBlock().getRelative(BlockFace.UP).setData((byte) (tblock.getState().getRawData() + 8)); } - } - }.runTaskLater(ProjectKorra.plugin, (long) (i / shiftRemoveSpeed)); - - if (TEMP_LAVA_BLOCKS.values().contains(tblock)) { - affectedBlocks.remove(tblock); - TEMP_LAVA_BLOCKS.remove(TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.get(tblock)); - TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.remove(tblock); - } - if (TEMP_LAND_BLOCKS.values().contains(tblock)) { - affectedBlocks.remove(tblock); - TEMP_LAND_BLOCKS.remove(TEMP_LAND_BLOCKS_BY_TEMPBLOCK.get(tblock)); - TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.remove(tblock); - } - if (TEMP_AIR_BLOCKS.values().contains(tblock)) { - affectedBlocks.remove(tblock); - TEMP_AIR_BLOCKS.remove(TEMP_AIR_BLOCKS_BY_TEMPBLOCK.get(tblock)); - TEMP_AIR_BLOCKS_BY_TEMPBLOCK.remove(tblock); - } + }.runTaskLater(ProjectKorra.plugin, (long) (i / this.shiftRemoveSpeed)); } - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } @@ -508,22 +527,20 @@ public void run() { @Override public void remove() { super.remove(); - for (int i = affectedBlocks.size() - 1; i > -1; i--) { - final TempBlock tblock = affectedBlocks.get(i); + for (int i = this.affectedBlocks.size() - 1; i > -1; i--) { + final TempBlock tblock = this.affectedBlocks.get(i); tblock.revertBlock(); if (TEMP_LAVA_BLOCKS.values().contains(tblock)) { - affectedBlocks.remove(tblock); - TEMP_LAVA_BLOCKS.remove(TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.get(tblock)); - TEMP_LAVA_BLOCKS_BY_TEMPBLOCK.remove(tblock); + this.affectedBlocks.remove(tblock); + TEMP_LAVA_BLOCKS.remove(tblock.getBlock()); } if (TEMP_LAND_BLOCKS.values().contains(tblock)) { - affectedBlocks.remove(tblock); - TEMP_LAND_BLOCKS.remove(TEMP_LAND_BLOCKS_BY_TEMPBLOCK.get(tblock)); - TEMP_LAND_BLOCKS_BY_TEMPBLOCK.remove(tblock); + this.affectedBlocks.remove(tblock); + TEMP_LAND_BLOCKS.remove(tblock.getBlock()); } } - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } @@ -531,14 +548,14 @@ public void remove() { /** * Returns a list of all the Lava blocks that are adjacent to the block at * loc. - * + * * @param loc the middle location of the adjacent blocks * @return a list of the adjacent blocks */ - public ArrayList getAdjacentLavaBlocks(Location loc) { - ArrayList list = getAdjacentBlocks(loc); + public ArrayList getAdjacentLavaBlocks(final Location loc) { + final ArrayList list = getAdjacentBlocks(loc); for (int i = 0; i < list.size(); i++) { - Block block = list.get(i); + final Block block = list.get(i); if (!isLava(block)) { list.remove(i); i--; @@ -550,13 +567,13 @@ public ArrayList getAdjacentLavaBlocks(Location loc) { /** * Returns an ArrayList of all the surrounding blocks for loc, but it * excludes the block that is contained at Loc. - * + * * @param loc the middle block location * @return a list of adjacent blocks */ - public static ArrayList getAdjacentBlocks(Location loc) { - ArrayList list = new ArrayList(); - Block block = loc.getBlock(); + public static ArrayList getAdjacentBlocks(final Location loc) { + final ArrayList list = new ArrayList(); + final Block block = loc.getBlock(); for (int x = -1; x <= 1; x++) { for (int y = -2; y <= 1; y++) { @@ -575,14 +592,14 @@ public static ArrayList getAdjacentBlocks(Location loc) { * was useful in allowing the flow of lava to look more natural and not be * substantially shortened by the Y distance if it is flowing upward or * downward. - * + * * @param l1 the first location * @param l2 the second location * @return the distance squared between l1 and l2 */ - public static double distanceSquaredXZ(Location l1, Location l2) { - Location temp1 = l1.clone(); - Location temp2 = l2.clone(); + public static double distanceSquaredXZ(final Location l1, final Location l2) { + final Location temp1 = l1.clone(); + final Location temp2 = l2.clone(); temp1.setY(0); temp2.setY(0); return temp1.distanceSquared(temp2); @@ -591,14 +608,14 @@ public static double distanceSquaredXZ(Location l1, Location l2) { /** * Returns all of the LavaFlows created by a specific player but filters the * abilities based on shift or click. - * + * * @param player the player that created the ability instance * @param type the specific type of ability we are looking for * @return a list of all the LavaFlow instances */ - public static ArrayList getLavaFlow(Player player, AbilityType type) { - ArrayList list = new ArrayList(); - for (LavaFlow lf : getAbilities(LavaFlow.class)) { + public static ArrayList getLavaFlow(final Player player, final AbilityType type) { + final ArrayList list = new ArrayList(); + for (final LavaFlow lf : getAbilities(LavaFlow.class)) { if (lf.player != null && lf.player == player && lf.type != null && lf.type == type) { list.add(lf); } @@ -608,7 +625,7 @@ public static ArrayList getLavaFlow(Player player, AbilityType type) { public static Material getRevertMaterial() { Material m = Material.STONE; - LavaFlow lf = (LavaFlow) CoreAbility.getAbility("LavaFlow"); + final LavaFlow lf = (LavaFlow) CoreAbility.getAbility("LavaFlow"); m = lf.revertMaterial; return m; } @@ -628,17 +645,17 @@ public String getName() { @Override public Location getLocation() { - if (origin != null) { - return origin; - } else if (player != null) { - return player.getLocation(); + if (this.origin != null) { + return this.origin; + } else if (this.player != null) { + return this.player.getLocation(); } return null; } @Override public long getCooldown() { - return type == AbilityType.CLICK ? clickLandCooldown : shiftCooldown; + return this.type == AbilityType.CLICK ? this.clickLandCooldown : this.shiftCooldown; } @Override @@ -653,267 +670,267 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (TempBlock tblock : affectedBlocks) { + final ArrayList locations = new ArrayList<>(); + for (final TempBlock tblock : this.affectedBlocks) { locations.add(tblock.getLocation()); } return locations; } public boolean isRemoving() { - return removing; + return this.removing; } - public void setRemoving(boolean removing) { + public void setRemoving(final boolean removing) { this.removing = removing; } public boolean isMakeLava() { - return makeLava; + return this.makeLava; } - public void setMakeLava(boolean makeLava) { + public void setMakeLava(final boolean makeLava) { this.makeLava = makeLava; } public boolean isClickIsFinished() { - return clickIsFinished; + return this.clickIsFinished; } - public void setClickIsFinished(boolean clickIsFinished) { + public void setClickIsFinished(final boolean clickIsFinished) { this.clickIsFinished = clickIsFinished; } public boolean isShiftIsFinished() { - return shiftIsFinished; + return this.shiftIsFinished; } - public void setShiftIsFinished(boolean shiftIsFinished) { + public void setShiftIsFinished(final boolean shiftIsFinished) { this.shiftIsFinished = shiftIsFinished; } public boolean isAllowNaturalFlow() { - return allowNaturalFlow; + return this.allowNaturalFlow; } - public void setAllowNaturalFlow(boolean allowNaturalFlow) { + public void setAllowNaturalFlow(final boolean allowNaturalFlow) { this.allowNaturalFlow = allowNaturalFlow; } public int getShiftCounter() { - return shiftCounter; + return this.shiftCounter; } - public void setShiftCounter(int shiftCounter) { + public void setShiftCounter(final int shiftCounter) { this.shiftCounter = shiftCounter; } public int getUpwardFlow() { - return upwardFlow; + return this.upwardFlow; } - public void setUpwardFlow(int upwardFlow) { + public void setUpwardFlow(final int upwardFlow) { this.upwardFlow = upwardFlow; } public int getDownwardFlow() { - return downwardFlow; + return this.downwardFlow; } - public void setDownwardFlow(int downwardFlow) { + public void setDownwardFlow(final int downwardFlow) { this.downwardFlow = downwardFlow; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getClickLavaDelay() { - return clickLavaDelay; + return this.clickLavaDelay; } - public void setClickLavaDelay(long clickLavaDelay) { + public void setClickLavaDelay(final long clickLavaDelay) { this.clickLavaDelay = clickLavaDelay; } public long getClickLandDelay() { - return clickLandDelay; + return this.clickLandDelay; } - public void setClickLandDelay(long clickLandDelay) { + public void setClickLandDelay(final long clickLandDelay) { this.clickLandDelay = clickLandDelay; } public long getClickLavaCooldown() { - return clickLavaCooldown; + return this.clickLavaCooldown; } - public void setClickLavaCooldown(long clickLavaCooldown) { + public void setClickLavaCooldown(final long clickLavaCooldown) { this.clickLavaCooldown = clickLavaCooldown; } public long getClickLandCooldown() { - return clickLandCooldown; + return this.clickLandCooldown; } - public void setClickLandCooldown(long clickLandCooldown) { + public void setClickLandCooldown(final long clickLandCooldown) { this.clickLandCooldown = clickLandCooldown; } public long getShiftCooldown() { - return shiftCooldown; + return this.shiftCooldown; } - public void setShiftCooldown(long shiftCooldown) { + public void setShiftCooldown(final long shiftCooldown) { this.shiftCooldown = shiftCooldown; } public long getClickLavaCleanupDelay() { - return clickLavaCleanupDelay; + return this.clickLavaCleanupDelay; } - public void setClickLavaCleanupDelay(long clickLavaCleanupDelay) { + public void setClickLavaCleanupDelay(final long clickLavaCleanupDelay) { this.clickLavaCleanupDelay = clickLavaCleanupDelay; } public long getClickLandCleanupDelay() { - return clickLandCleanupDelay; + return this.clickLandCleanupDelay; } - public void setClickLandCleanupDelay(long clickLandCleanupDelay) { + public void setClickLandCleanupDelay(final long clickLandCleanupDelay) { this.clickLandCleanupDelay = clickLandCleanupDelay; } public double getParticleDensity() { - return particleDensity; + return this.particleDensity; } - public void setParticleDensity(double particleDensity) { + public void setParticleDensity(final double particleDensity) { this.particleDensity = particleDensity; } public double getParticleOffset() { - return particleOffset; + return this.particleOffset; } - public void setParticleOffset(double particleOffset) { + public void setParticleOffset(final double particleOffset) { this.particleOffset = particleOffset; } public double getCurrentRadius() { - return currentRadius; + return this.currentRadius; } - public void setCurrentRadius(double currentRadius) { + public void setCurrentRadius(final double currentRadius) { this.currentRadius = currentRadius; } public double getShiftPlatformRadius() { - return shiftPlatformRadius; + return this.shiftPlatformRadius; } - public void setShiftPlatformRadius(double shiftPlatformRadius) { + public void setShiftPlatformRadius(final double shiftPlatformRadius) { this.shiftPlatformRadius = shiftPlatformRadius; } public double getShiftMaxRadius() { - return shiftMaxRadius; + return this.shiftMaxRadius; } - public void setShiftMaxRadius(double shiftMaxRadius) { + public void setShiftMaxRadius(final double shiftMaxRadius) { this.shiftMaxRadius = shiftMaxRadius; } public double getShiftFlowSpeed() { - return shiftFlowSpeed; + return this.shiftFlowSpeed; } - public void setShiftFlowSpeed(double shiftFlowSpeed) { + public void setShiftFlowSpeed(final double shiftFlowSpeed) { this.shiftFlowSpeed = shiftFlowSpeed; } public double getShiftRemoveSpeed() { - return shiftRemoveSpeed; + return this.shiftRemoveSpeed; } - public void setShiftRemoveSpeed(double shiftRemoveSpeed) { + public void setShiftRemoveSpeed(final double shiftRemoveSpeed) { this.shiftRemoveSpeed = shiftRemoveSpeed; } public double getShiftRemoveDelay() { - return shiftRemoveDelay; + return this.shiftRemoveDelay; } - public void setShiftRemoveDelay(double shiftRemoveDelay) { + public void setShiftRemoveDelay(final double shiftRemoveDelay) { this.shiftRemoveDelay = shiftRemoveDelay; } public double getClickRange() { - return clickRange; + return this.clickRange; } - public void setClickRange(double clickRange) { + public void setClickRange(final double clickRange) { this.clickRange = clickRange; } public double getClickLavaRadius() { - return clickLavaRadius; + return this.clickLavaRadius; } - public void setClickLavaRadius(double clickLavaRadius) { + public void setClickLavaRadius(final double clickLavaRadius) { this.clickLavaRadius = clickLavaRadius; } public double getClickLandRadius() { - return clickLandRadius; + return this.clickLandRadius; } - public void setClickLandRadius(double clickLandRadius) { + public void setClickLandRadius(final double clickLandRadius) { this.clickLandRadius = clickLandRadius; } public double getLavaCreateSpeed() { - return lavaCreateSpeed; + return this.lavaCreateSpeed; } - public void setLavaCreateSpeed(double lavaCreateSpeed) { + public void setLavaCreateSpeed(final double lavaCreateSpeed) { this.lavaCreateSpeed = lavaCreateSpeed; } public double getLandCreateSpeed() { - return landCreateSpeed; + return this.landCreateSpeed; } - public void setLandCreateSpeed(double landCreateSpeed) { + public void setLandCreateSpeed(final double landCreateSpeed) { this.landCreateSpeed = landCreateSpeed; } public AbilityType getType() { - return type; + return this.type; } - public void setType(AbilityType type) { + public void setType(final AbilityType type) { this.type = type; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public ArrayList getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } public ArrayList getTasks() { - return tasks; + return this.tasks; } } diff --git a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurge.java b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurge.java index a1ce50f08..8d2954cd2 100644 --- a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurge.java +++ b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurge.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.earthbending.lava; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.LavaAbility; -import com.projectkorra.projectkorra.util.BlockSource; -import com.projectkorra.projectkorra.util.ClickType; -import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.ParticleEffect; -import com.projectkorra.projectkorra.util.TempBlock; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -18,13 +18,13 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.LavaAbility; +import com.projectkorra.projectkorra.util.BlockSource; +import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.TempBlock; public class LavaSurge extends LavaAbility { @@ -55,7 +55,7 @@ public class LavaSurge extends LavaAbility { private Map lavaBlocks; private ListIterator listIterator; - public LavaSurge(Player player) { + public LavaSurge(final Player player) { super(player); this.impactDamage = getConfig().getInt("Abilities.Earth.LavaSurge.Damage"); @@ -75,38 +75,38 @@ public LavaSurge(Player player) { this.movingLava = new ArrayList<>(); this.lavaBlocks = new ConcurrentHashMap<>(); - if (!isEligible()) { + if (!this.isEligible()) { return; - } else if (bPlayer.isOnCooldown(this)) { + } else if (this.bPlayer.isOnCooldown(this)) { return; } - lastTime = System.currentTimeMillis(); + this.lastTime = System.currentTimeMillis(); - if (prepare()) { - start(); + if (this.prepare()) { + this.start(); } } public boolean isEligible() { - return bPlayer.canBend(this) && bPlayer.canLavabend(); + return this.bPlayer.canBend(this) && this.bPlayer.canLavabend(); } public boolean prepare() { - Block targetBlock = BlockSource.getEarthSourceBlock(player, prepareRange, ClickType.SHIFT_DOWN); + final Block targetBlock = BlockSource.getEarthSourceBlock(this.player, this.prepareRange, ClickType.SHIFT_DOWN); if (targetBlock == null || !(targetBlock.getRelative(BlockFace.UP).getType() == Material.AIR) && !isLava(targetBlock.getRelative(BlockFace.UP))) { return false; } - LavaSurge otherSurge = getAbility(player, this.getClass()); + final LavaSurge otherSurge = getAbility(this.player, this.getClass()); if (otherSurge != null) { otherSurge.revertFracture(); } - if ((canSourceBeEarth && isEarthbendable(targetBlock)) || isLavabendable(targetBlock)) { - startLocation = targetBlock.getLocation().add(0, 1, 0); - sourceBlock = targetBlock; + if ((this.canSourceBeEarth && this.isEarthbendable(targetBlock)) || this.isLavabendable(targetBlock)) { + this.startLocation = targetBlock.getLocation().add(0, 1, 0); + this.sourceBlock = targetBlock; return true; } @@ -114,152 +114,152 @@ public boolean prepare() { } public void launch() { - Location targetLocation = GeneralMethods.getTargetedLocation(player, travelRange * 2); + Location targetLocation = GeneralMethods.getTargetedLocation(this.player, this.travelRange * 2); try { - targetLocation = GeneralMethods.getTargetedEntity(player, travelRange * 2, null).getLocation(); + targetLocation = GeneralMethods.getTargetedEntity(this.player, this.travelRange * 2, null).getLocation(); } - catch (NullPointerException e) { + catch (final NullPointerException e) { } if (targetLocation == null) { - remove(); + this.remove(); return; } - time = System.currentTimeMillis(); - direction = GeneralMethods.getDirection(startLocation, targetLocation).multiply(0.07); + this.time = System.currentTimeMillis(); + this.direction = GeneralMethods.getDirection(this.startLocation, targetLocation).multiply(0.07); - if (direction.getY() < 0) { - direction.setY(0); + if (this.direction.getY() < 0) { + this.direction.setY(0); } - if (canSourceBeEarth) { - openFracture(); + if (this.canSourceBeEarth) { + this.openFracture(); } else { - skipFracture(); + this.skipFracture(); } } public void openFracture() { - List affectedBlocks = GeneralMethods.getBlocksAroundPoint(sourceBlock.getLocation(), fractureRadius); + final List affectedBlocks = GeneralMethods.getBlocksAroundPoint(this.sourceBlock.getLocation(), this.fractureRadius); - for (Block b : affectedBlocks) { - if (isEarthbendable(b)) { - fracture.add(b); + for (final Block b : affectedBlocks) { + if (this.isEarthbendable(b)) { + this.fracture.add(b); } } - listIterator = fracture.listIterator(); - isFractureOpen = true; - bPlayer.addCooldown(this); + this.listIterator = this.fracture.listIterator(); + this.isFractureOpen = true; + this.bPlayer.addCooldown(this); } public void skipFracture() { - listIterator = fracture.listIterator(); - isFractureOpen = true; + this.listIterator = this.fracture.listIterator(); + this.isFractureOpen = true; } public void revertFracture() { - for (TempBlock tb : fractureTempBlocks) { + for (final TempBlock tb : this.fractureTempBlocks) { tb.revertBlock(); } - fracture.clear(); + this.fracture.clear(); } @Override public void remove() { super.remove(); - revertFracture(); + this.revertFracture(); } - public boolean canMoveThrough(Block block) { - if (isTransparent(startLocation.getBlock()) || isEarthbendable(startLocation.getBlock()) || isLavabendable(startLocation.getBlock())) { + public boolean canMoveThrough(final Block block) { + if (this.isTransparent(this.startLocation.getBlock()) || this.isEarthbendable(this.startLocation.getBlock()) || this.isLavabendable(this.startLocation.getBlock())) { return true; } return false; } public void removeLava() { - for (TempBlock tb : lavaBlocks.values()) { + for (final TempBlock tb : this.lavaBlocks.values()) { tb.revertBlock(); } - movingLava.clear(); + this.movingLava.clear(); } @Override public void progress() { - long curTime = System.currentTimeMillis(); - if (!player.isOnline() || player.isDead()) { - remove(); + final long curTime = System.currentTimeMillis(); + if (!this.player.isOnline() || this.player.isDead()) { + this.remove(); return; - } else if (!hasSurgeStarted && !bPlayer.getBoundAbilityName().equals(getName())) { - remove(); + } else if (!this.hasSurgeStarted && !this.bPlayer.getBoundAbilityName().equals(this.getName())) { + this.remove(); return; } - if (!hasSurgeStarted && sourceBlock != null && curTime > lastTime + particleInterval) { - lastTime = curTime; - ParticleEffect.LAVA.display(sourceBlock.getLocation(), 0, 0, 0, 0, 1); - } else if (hasSurgeStarted && curTime > lastTime + particleInterval) { - lastTime = curTime; - for (FallingBlock fblock : fallingBlocks) { + if (!this.hasSurgeStarted && this.sourceBlock != null && curTime > this.lastTime + this.particleInterval) { + this.lastTime = curTime; + ParticleEffect.LAVA.display(this.sourceBlock.getLocation(), 0, 0, 0, 0, 1); + } else if (this.hasSurgeStarted && curTime > this.lastTime + this.particleInterval) { + this.lastTime = curTime; + for (final FallingBlock fblock : this.fallingBlocks) { ParticleEffect.LAVA.display(fblock.getLocation(), 0, 0, 0, 0, 1); } } - if (isFractureOpen && !hasSurgeStarted) { - if (!listIterator.hasNext()) { - hasSurgeStarted = true; + if (this.isFractureOpen && !this.hasSurgeStarted) { + if (!this.listIterator.hasNext()) { + this.hasSurgeStarted = true; } else { - Block b = listIterator.next(); + final Block b = this.listIterator.next(); playEarthbendingSound(b.getLocation()); for (int i = 0; i < 2; i++) { - TempBlock tb = new TempBlock(b, Material.STATIONARY_LAVA, (byte) 0); - fractureTempBlocks.add(tb); + final TempBlock tb = new TempBlock(b, Material.STATIONARY_LAVA, (byte) 0); + this.fractureTempBlocks.add(tb); } } } - if (hasSurgeStarted) { - if (fallingBlocksCount >= maxBlocks) { + if (this.hasSurgeStarted) { + if (this.fallingBlocksCount >= this.maxBlocks) { return; } - if (curTime > time + (fallingBlockInterval * fallingBlocksCount)) { - FallingBlock fbs = GeneralMethods.spawnFallingBlock(sourceBlock.getLocation().add(0, 1, 0), 11, (byte) 0); - fallingBlocks.add(fbs); + if (curTime > this.time + (this.fallingBlockInterval * this.fallingBlocksCount)) { + final FallingBlock fbs = GeneralMethods.spawnFallingBlock(this.sourceBlock.getLocation().add(0, 1, 0), 11, (byte) 0); + this.fallingBlocks.add(fbs); ALL_FALLING_BLOCKS.add(fbs); - double x = random.nextDouble() / 5; - double z = random.nextDouble() / 5; + double x = this.random.nextDouble() / 5; + double z = this.random.nextDouble() / 5; - x = (random.nextBoolean()) ? -x : x; - z = (random.nextBoolean()) ? -z : z; + x = (this.random.nextBoolean()) ? -x : x; + z = (this.random.nextBoolean()) ? -z : z; - fbs.setVelocity(direction.clone().add(new Vector(x, 0.2, z)).multiply(1.2)); + fbs.setVelocity(this.direction.clone().add(new Vector(x, 0.2, z)).multiply(1.2)); fbs.setDropItem(false); - for (Block b : fracture) { - if (random.nextBoolean() && b != sourceBlock) { - FallingBlock fb = GeneralMethods.spawnFallingBlock(b.getLocation().add(new Vector(0, 1, 0)), 11, (byte) 0); + for (final Block b : this.fracture) { + if (this.random.nextBoolean() && b != this.sourceBlock) { + final FallingBlock fb = GeneralMethods.spawnFallingBlock(b.getLocation().add(new Vector(0, 1, 0)), 11, (byte) 0); ALL_FALLING_BLOCKS.add(fb); - fallingBlocks.add(fb); - fb.setVelocity(direction.clone().add(new Vector(random.nextDouble() / 10, 0.1, random.nextDouble() / 10)).multiply(1.2)); + this.fallingBlocks.add(fb); + fb.setVelocity(this.direction.clone().add(new Vector(this.random.nextDouble() / 10, 0.1, this.random.nextDouble() / 10)).multiply(1.2)); fb.setDropItem(false); } } - fallingBlocksCount++; + this.fallingBlocksCount++; } - for (FallingBlock fb : fallingBlocks) { - for (Entity e : GeneralMethods.getEntitiesAroundPoint(fb.getLocation(), 2)) { + for (final FallingBlock fb : this.fallingBlocks) { + for (final Entity e : GeneralMethods.getEntitiesAroundPoint(fb.getLocation(), 2)) { if (e instanceof LivingEntity) { - if (e.getEntityId() != player.getEntityId()) { - DamageHandler.damageEntity(e, impactDamage, this); + if (e.getEntityId() != this.player.getEntityId()) { + DamageHandler.damageEntity(e, this.impactDamage, this); e.setFireTicks(100); - GeneralMethods.setVelocity(e, direction.clone()); + GeneralMethods.setVelocity(e, this.direction.clone()); } } } @@ -274,12 +274,12 @@ public String getName() { @Override public Location getLocation() { - return startLocation; + return this.startLocation; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -294,178 +294,178 @@ public boolean isHarmlessAbility() { @Override public boolean isHiddenAbility() { - return true; // disabled + return true; // disabled } - + public static HashSet getAllFallingBlocks() { return ALL_FALLING_BLOCKS; } public boolean isHasSurgeStarted() { - return hasSurgeStarted; + return this.hasSurgeStarted; } - public void setHasSurgeStarted(boolean hasSurgeStarted) { + public void setHasSurgeStarted(final boolean hasSurgeStarted) { this.hasSurgeStarted = hasSurgeStarted; } public boolean isFractureOpen() { - return isFractureOpen; + return this.isFractureOpen; } - public void setFractureOpen(boolean isFractureOpen) { + public void setFractureOpen(final boolean isFractureOpen) { this.isFractureOpen = isFractureOpen; } public boolean isCanSourceBeEarth() { - return canSourceBeEarth; + return this.canSourceBeEarth; } - public void setCanSourceBeEarth(boolean canSourceBeEarth) { + public void setCanSourceBeEarth(final boolean canSourceBeEarth) { this.canSourceBeEarth = canSourceBeEarth; } public int getFallingBlocksCount() { - return fallingBlocksCount; + return this.fallingBlocksCount; } - public void setFallingBlocksCount(int fallingBlocksCount) { + public void setFallingBlocksCount(final int fallingBlocksCount) { this.fallingBlocksCount = fallingBlocksCount; } public int getMaxBlocks() { - return maxBlocks; + return this.maxBlocks; } - public void setMaxBlocks(int maxBlocks) { + public void setMaxBlocks(final int maxBlocks) { this.maxBlocks = maxBlocks; } public int getParticleInterval() { - return particleInterval; + return this.particleInterval; } - public void setParticleInterval(int particleInterval) { + public void setParticleInterval(final int particleInterval) { this.particleInterval = particleInterval; } public int getFallingBlockInterval() { - return fallingBlockInterval; + return this.fallingBlockInterval; } - public void setFallingBlockInterval(int fallingBlockInterval) { + public void setFallingBlockInterval(final int fallingBlockInterval) { this.fallingBlockInterval = fallingBlockInterval; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getLastTime() { - return lastTime; + return this.lastTime; } - public void setLastTime(long lastTime) { + public void setLastTime(final long lastTime) { this.lastTime = lastTime; } public double getImpactDamage() { - return impactDamage; + return this.impactDamage; } - public void setImpactDamage(double impactDamage) { + public void setImpactDamage(final double impactDamage) { this.impactDamage = impactDamage; } public double getFractureRadius() { - return fractureRadius; + return this.fractureRadius; } - public void setFractureRadius(double fractureRadius) { + public void setFractureRadius(final double fractureRadius) { this.fractureRadius = fractureRadius; } public double getPrepareRange() { - return prepareRange; + return this.prepareRange; } - public void setPrepareRange(double prepareRange) { + public void setPrepareRange(final double prepareRange) { this.prepareRange = prepareRange; } public double getTravelRange() { - return travelRange; + return this.travelRange; } - public void setTravelRange(double travelRange) { + public void setTravelRange(final double travelRange) { this.travelRange = travelRange; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Random getRandom() { - return random; + return this.random; } - public void setRandom(Random random) { + public void setRandom(final Random random) { this.random = random; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Location getStartLocation() { - return startLocation; + return this.startLocation; } - public void setStartLocation(Location startLocation) { + public void setStartLocation(final Location startLocation) { this.startLocation = startLocation; } public ListIterator getListIterator() { - return listIterator; + return this.listIterator; } - public void setListIterator(ListIterator listIterator) { + public void setListIterator(final ListIterator listIterator) { this.listIterator = listIterator; } public ArrayList getFallingBlocks() { - return fallingBlocks; + return this.fallingBlocks; } public ArrayList getFracture() { - return fracture; + return this.fracture; } public ArrayList getFractureTempBlocks() { - return fractureTempBlocks; + return this.fractureTempBlocks; } public ArrayList getMovingLava() { - return movingLava; + return this.movingLava; } public Map getLavaBlocks() { - return lavaBlocks; + return this.lavaBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWall.java b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWall.java index c65eb9c5c..2ad5e163e 100644 --- a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWall.java +++ b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWall.java @@ -1,13 +1,9 @@ package com.projectkorra.projectkorra.earthbending.lava; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.LavaAbility; -import com.projectkorra.projectkorra.avatar.AvatarState; -import com.projectkorra.projectkorra.firebending.FireBlast; -import com.projectkorra.projectkorra.util.BlockSource; -import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; -import com.projectkorra.projectkorra.util.ClickType; -import com.projectkorra.projectkorra.util.TempBlock; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; @@ -16,16 +12,20 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.LavaAbility; +import com.projectkorra.projectkorra.avatar.AvatarState; +import com.projectkorra.projectkorra.firebending.FireBlast; +import com.projectkorra.projectkorra.util.BlockSource; +import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; +import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.TempBlock; public class LavaSurgeWall extends LavaAbility { private static final Map AFFECTED_BLOCKS = new ConcurrentHashMap(); private static final Map WALL_BLOCKS = new ConcurrentHashMap(); - private static final int SURGE_WAVE_RANGE = 20; // TODO: remove this + private static final int SURGE_WAVE_RANGE = 20; private boolean progressing; private boolean settingUp; @@ -42,7 +42,7 @@ public class LavaSurgeWall extends LavaAbility { private Vector firstDirection; private Vector targetDirection; - public LavaSurgeWall(Player player) { + public LavaSurgeWall(final Player player) { super(player); this.interval = 30; @@ -50,35 +50,35 @@ public LavaSurgeWall(Player player) { this.range = getConfig().getDouble("Abilities.Water.Surge.Wall.Range"); this.cooldown = GeneralMethods.getGlobalCooldown(); - LavaSurgeWave wave = getAbility(player, LavaSurgeWave.class); + final LavaSurgeWave wave = getAbility(player, LavaSurgeWave.class); if (wave != null && wave.isProgressing()) { LavaSurgeWave.launch(player); return; } - if (bPlayer.isAvatarState()) { - radius = AvatarState.getValue(radius); - range = AvatarState.getValue(range); + if (this.bPlayer.isAvatarState()) { + this.radius = AvatarState.getValue(this.radius); + this.range = AvatarState.getValue(this.range); } - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } } public boolean prepare() { - cancelPrevious(); - Block block = BlockSource.getSourceBlock(player, range, BlockSourceType.LAVA, ClickType.LEFT_CLICK); + this.cancelPrevious(); + final Block block = BlockSource.getSourceBlock(this.player, this.range, BlockSourceType.LAVA, ClickType.LEFT_CLICK); if (block != null) { - sourceBlock = block; - focusBlock(); + this.sourceBlock = block; + this.focusBlock(); return true; } return false; } private void cancelPrevious() { - LavaSurgeWall lavaWall = getAbility(player, LavaSurgeWall.class); + final LavaSurgeWall lavaWall = getAbility(this.player, LavaSurgeWall.class); if (lavaWall != null) { if (lavaWall.progressing) { lavaWall.removeLava(lavaWall.sourceBlock); @@ -89,42 +89,42 @@ private void cancelPrevious() { } public void cancel() { - remove(); + this.remove(); } private void focusBlock() { - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } public void moveLava() { - if (sourceBlock != null) { - targetDestination = getTargetEarthBlock((int) range).getLocation(); + if (this.sourceBlock != null) { + this.targetDestination = this.getTargetEarthBlock((int) this.range).getLocation(); - if (targetDestination.distanceSquared(location) <= 1) { - progressing = false; - targetDestination = null; + if (this.targetDestination.distanceSquared(this.location) <= 1) { + this.progressing = false; + this.targetDestination = null; } else { - progressing = true; - settingUp = true; - firstDestination = getToEyeLevel(); - firstDirection = getDirection(sourceBlock.getLocation(), firstDestination); - targetDirection = getDirection(firstDestination, targetDestination); - - if (!GeneralMethods.isAdjacentToThreeOrMoreSources(sourceBlock)) { - sourceBlock.setType(Material.AIR); + this.progressing = true; + this.settingUp = true; + this.firstDestination = this.getToEyeLevel(); + this.firstDirection = this.getDirection(this.sourceBlock.getLocation(), this.firstDestination); + this.targetDirection = this.getDirection(this.firstDestination, this.targetDestination); + + if (!GeneralMethods.isAdjacentToThreeOrMoreSources(this.sourceBlock)) { + this.sourceBlock.setType(Material.AIR); } - addLava(sourceBlock); + this.addLava(this.sourceBlock); } } } private Location getToEyeLevel() { - Location loc = sourceBlock.getLocation().clone(); - loc.setY(targetDestination.getY()); + final Location loc = this.sourceBlock.getLocation().clone(); + loc.setY(this.targetDestination.getY()); return loc; } - private Vector getDirection(Location location, Location destination) { + private Vector getDirection(final Location location, final Location destination) { double x1, y1, z1; double x0, y0, z0; x1 = destination.getX(); @@ -138,55 +138,55 @@ private Vector getDirection(Location location, Location destination) { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - if (!forming) { - breakBlock(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + if (!this.forming) { + this.breakBlock(); } - remove(); + this.remove(); return; } - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - if (progressing && !player.isSneaking()) { - remove(); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + if (this.progressing && !this.player.isSneaking()) { + this.remove(); return; } - if (!progressing) { - sourceBlock.getWorld().playEffect(location, Effect.SMOKE, 4, (int) range); + if (!this.progressing) { + this.sourceBlock.getWorld().playEffect(this.location, Effect.SMOKE, 4, (int) this.range); return; } - if (forming) { - ArrayList blocks = new ArrayList(); - Location loc = GeneralMethods.getTargetedLocation(player, (int) range, Material.WATER, Material.STATIONARY_WATER, Material.ICE); - location = loc.clone(); - Vector dir = player.getEyeLocation().getDirection(); + if (this.forming) { + final ArrayList blocks = new ArrayList(); + final Location loc = GeneralMethods.getTargetedLocation(this.player, (int) this.range, Material.WATER, Material.STATIONARY_WATER, Material.ICE); + this.location = loc.clone(); + final Vector dir = this.player.getEyeLocation().getDirection(); Vector vec; Block block; - for (double i = 0; i <= radius; i += 0.5) { + for (double i = 0; i <= this.radius; i += 0.5) { for (double angle = 0; angle < 360; angle += 10) { vec = GeneralMethods.getOrthogonalVector(dir.clone(), angle, i); block = loc.clone().add(vec).getBlock(); - if (GeneralMethods.isRegionProtectedFromBuild(player, "LavaSurge", block.getLocation())) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, "LavaSurge", block.getLocation())) { continue; } if (WALL_BLOCKS.containsKey(block)) { blocks.add(block); - } else if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE || isLavabendable(block))) { - WALL_BLOCKS.put(block, player); - addWallBlock(block); + } else if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE || this.isLavabendable(block))) { + WALL_BLOCKS.put(block, this.player); + this.addWallBlock(block); blocks.add(block); FireBlast.removeFireBlastsAroundPoint(block.getLocation(), 2); } } } - for (Block blocki : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(blocki) == player && !blocks.contains(blocki)) { + for (final Block blocki : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(blocki) == this.player && !blocks.contains(blocki)) { finalRemoveLava(blocki); } } @@ -194,58 +194,58 @@ public void progress() { return; } - if (sourceBlock.getLocation().distanceSquared(firstDestination) < 0.5 * 0.5 && settingUp) { - settingUp = false; + if (this.sourceBlock.getLocation().distanceSquared(this.firstDestination) < 0.5 * 0.5 && this.settingUp) { + this.settingUp = false; } Vector direction; - if (settingUp) { - direction = firstDirection; + if (this.settingUp) { + direction = this.firstDirection; } else { - direction = targetDirection; + direction = this.targetDirection; } - location = location.clone().add(direction); - Block block = location.getBlock(); - if (block.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block = location.getBlock(); + this.location = this.location.clone().add(direction); + Block block = this.location.getBlock(); + if (block.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); } if (block.getType() != Material.AIR) { - breakBlock(); + this.breakBlock(); return; - } else if (!progressing) { - breakBlock(); + } else if (!this.progressing) { + this.breakBlock(); return; } - addLava(block); - removeLava(sourceBlock); - sourceBlock = block; - if (location.distanceSquared(targetDestination) < 1) { - removeLava(sourceBlock); - forming = true; + this.addLava(block); + this.removeLava(this.sourceBlock); + this.sourceBlock = block; + if (this.location.distanceSquared(this.targetDestination) < 1) { + this.removeLava(this.sourceBlock); + this.forming = true; } return; } } - private void addWallBlock(Block block) { + private void addWallBlock(final Block block) { new TempBlock(block, Material.STATIONARY_LAVA, (byte) 8); } private void breakBlock() { - finalRemoveLava(sourceBlock); - for (Block block : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(block) == player) { + finalRemoveLava(this.sourceBlock); + for (final Block block : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(block) == this.player) { finalRemoveLava(block); } } - remove(); + this.remove(); } - private void removeLava(Block block) { + private void removeLava(final Block block) { if (block != null) { if (AFFECTED_BLOCKS.containsKey(block)) { if (!GeneralMethods.isAdjacentToThreeOrMoreSources(block)) { @@ -256,7 +256,7 @@ private void removeLava(Block block) { } } - private static void finalRemoveLava(Block block) { + private static void finalRemoveLava(final Block block) { if (AFFECTED_BLOCKS.containsKey(block)) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); @@ -267,23 +267,24 @@ private static void finalRemoveLava(Block block) { } } - private void addLava(Block block) { - if (GeneralMethods.isRegionProtectedFromBuild(player, "LavaSurge", block.getLocation())) + private void addLava(final Block block) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, "LavaSurge", block.getLocation())) { return; + } if (!TempBlock.isTempBlock(block)) { new TempBlock(block, Material.STATIONARY_LAVA, (byte) 8); AFFECTED_BLOCKS.put(block, block); } } - public static void moveLava(Player player) { - LavaSurgeWall wall = getAbility(player, LavaSurgeWall.class); + public static void moveLava(final Player player) { + final LavaSurgeWall wall = getAbility(player, LavaSurgeWall.class); if (wall != null) { wall.moveLava(); } } - public static void form(Player player) { + public static void form(final Player player) { if (!hasAbility(player, LavaSurgeWall.class)) { new LavaSurgeWave(player); return; @@ -295,20 +296,20 @@ public static void form(Player player) { } public static void cleanup() { - for (Block block : AFFECTED_BLOCKS.keySet()) { + for (final Block block : AFFECTED_BLOCKS.keySet()) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); WALL_BLOCKS.remove(block); } - for (Block block : WALL_BLOCKS.keySet()) { + for (final Block block : WALL_BLOCKS.keySet()) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); WALL_BLOCKS.remove(block); } } - public static boolean wasBrokenFor(Player player, Block block) { - LavaSurgeWall wall = getAbility(player, LavaSurgeWall.class); + public static boolean wasBrokenFor(final Player player, final Block block) { + final LavaSurgeWall wall = getAbility(player, LavaSurgeWall.class); if (wall != null) { if (wall.sourceBlock == null) { return false; @@ -334,12 +335,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -351,113 +352,113 @@ public boolean isSneakAbility() { public boolean isHarmlessAbility() { return false; } - + @Override public boolean isHiddenAbility() { return true; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isForming() { - return forming; + return this.forming; } - public void setForming(boolean forming) { + public void setForming(final boolean forming) { this.forming = forming; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Location getTargetDestination() { - return targetDestination; + return this.targetDestination; } - public void setTargetDestination(Location targetDestination) { + public void setTargetDestination(final Location targetDestination) { this.targetDestination = targetDestination; } public Vector getFirstDirection() { - return firstDirection; + return this.firstDirection; } - public void setFirstDirection(Vector firstDirection) { + public void setFirstDirection(final Vector firstDirection) { this.firstDirection = firstDirection; } public Vector getTargetDirection() { - return targetDirection; + return this.targetDirection; } - public void setTargetDirection(Vector targetDirection) { + public void setTargetDirection(final Vector targetDirection) { this.targetDirection = targetDirection; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWave.java b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWave.java index 2f4bf241a..1d2f342d2 100644 --- a/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWave.java +++ b/src/com/projectkorra/projectkorra/earthbending/lava/LavaSurgeWave.java @@ -1,14 +1,7 @@ package com.projectkorra.projectkorra.earthbending.lava; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.LavaAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.avatar.AvatarState; -import com.projectkorra.projectkorra.firebending.FireBlast; -import com.projectkorra.projectkorra.util.BlockSource; -import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; -import com.projectkorra.projectkorra.util.ClickType; -import com.projectkorra.projectkorra.util.TempBlock; +import java.util.ArrayList; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; @@ -19,8 +12,15 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.ElementalAbility; +import com.projectkorra.projectkorra.ability.LavaAbility; +import com.projectkorra.projectkorra.avatar.AvatarState; +import com.projectkorra.projectkorra.firebending.FireBlast; +import com.projectkorra.projectkorra.util.BlockSource; +import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; +import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.TempBlock; public class LavaSurgeWave extends LavaAbility { @@ -38,10 +38,10 @@ public class LavaSurgeWave extends LavaAbility { private Block sourceBlock; private Location targetDestination; private Vector targetDirection; - private ConcurrentHashMap waveBlocks; - private ConcurrentHashMap frozenBlocks; + private final ConcurrentHashMap waveBlocks; + private final ConcurrentHashMap frozenBlocks; - public LavaSurgeWave(Player player) { + public LavaSurgeWave(final Player player) { super(player); this.progressing = false; @@ -56,37 +56,37 @@ public LavaSurgeWave(Player player) { this.waveBlocks = new ConcurrentHashMap(); this.frozenBlocks = new ConcurrentHashMap(); - if (bPlayer.isAvatarState()) { - range = AvatarState.getValue(range); - maxRadius = AvatarState.getValue(maxRadius); - horizontalPush = AvatarState.getValue(horizontalPush); - verticalPush = AvatarState.getValue(verticalPush); + if (this.bPlayer.isAvatarState()) { + this.range = AvatarState.getValue(this.range); + this.maxRadius = AvatarState.getValue(this.maxRadius); + this.horizontalPush = AvatarState.getValue(this.horizontalPush); + this.verticalPush = AvatarState.getValue(this.verticalPush); } - if (prepare()) { - LavaSurgeWave wave = getAbility(player, LavaSurgeWave.class); + if (this.prepare()) { + final LavaSurgeWave wave = getAbility(player, LavaSurgeWave.class); if (wave != null) { wave.remove(); } - start(); - time = System.currentTimeMillis(); + this.start(); + this.time = System.currentTimeMillis(); } } public boolean prepare() { - cancelPrevious(); - Block block = BlockSource.getSourceBlock(player, range, BlockSourceType.LAVA, ClickType.SHIFT_DOWN); + this.cancelPrevious(); + final Block block = BlockSource.getSourceBlock(this.player, this.range, BlockSourceType.LAVA, ClickType.SHIFT_DOWN); if (block != null) { - sourceBlock = block; - focusBlock(); + this.sourceBlock = block; + this.focusBlock(); return true; } return false; } private void cancelPrevious() { - LavaSurgeWave oldWave = getAbility(player, LavaSurgeWave.class); + final LavaSurgeWave oldWave = getAbility(this.player, LavaSurgeWave.class); if (oldWave != null) { if (oldWave.progressing) { oldWave.breakBlock(); @@ -97,44 +97,44 @@ private void cancelPrevious() { } private void focusBlock() { - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } public void moveLava() { - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } - bPlayer.addCooldown(this); - if (sourceBlock != null) { - if (!sourceBlock.getWorld().equals(player.getWorld())) { + this.bPlayer.addCooldown(this); + if (this.sourceBlock != null) { + if (!this.sourceBlock.getWorld().equals(this.player.getWorld())) { return; } - Entity target = GeneralMethods.getTargetedEntity(player, range); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range); if (target == null) { - targetDestination = getTargetEarthBlock((int) range).getLocation(); + this.targetDestination = this.getTargetEarthBlock((int) this.range).getLocation(); } else { - targetDestination = ((LivingEntity) target).getEyeLocation(); + this.targetDestination = ((LivingEntity) target).getEyeLocation(); } - if (targetDestination.distanceSquared(location) <= 1) { - progressing = false; - targetDestination = null; + if (this.targetDestination.distanceSquared(this.location) <= 1) { + this.progressing = false; + this.targetDestination = null; } else { - progressing = true; - targetDirection = getDirection(sourceBlock.getLocation(), targetDestination).normalize(); - targetDestination = location.clone().add(targetDirection.clone().multiply(range)); + this.progressing = true; + this.targetDirection = this.getDirection(this.sourceBlock.getLocation(), this.targetDestination).normalize(); + this.targetDestination = this.location.clone().add(this.targetDirection.clone().multiply(this.range)); - if (!GeneralMethods.isAdjacentToThreeOrMoreSources(sourceBlock)) { - sourceBlock.setType(Material.AIR); + if (!GeneralMethods.isAdjacentToThreeOrMoreSources(this.sourceBlock)) { + this.sourceBlock.setType(Material.AIR); } - addLava(sourceBlock); + this.addLava(this.sourceBlock); } } } - private Vector getDirection(Location location, Location destination) { + private Vector getDirection(final Location location, final Location destination) { double x1, y1, z1; double x0, y0, z0; x1 = destination.getX(); @@ -148,30 +148,30 @@ private Vector getDirection(Location location, Location destination) { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - breakBlock(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.breakBlock(); return; } - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - if (!progressing) { - sourceBlock.getWorld().playEffect(location, Effect.SMOKE, 4, (int) range); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + if (!this.progressing) { + this.sourceBlock.getWorld().playEffect(this.location, Effect.SMOKE, 4, (int) this.range); return; } - Vector direction = targetDirection; - location = location.clone().add(direction); - Block blockl = location.getBlock(); - ArrayList blocks = new ArrayList(); + final Vector direction = this.targetDirection; + this.location = this.location.clone().add(direction); + final Block blockl = this.location.getBlock(); + final ArrayList blocks = new ArrayList(); - if (!GeneralMethods.isRegionProtectedFromBuild(this, location) && blockl.getType() != Material.LEAVES && (blockl.getType() == Material.AIR || blockl.getType() == Material.FIRE || WaterAbility.isPlant(blockl) || isLava(blockl))) { - for (double i = 0; i <= radius; i += 0.5) { + if (!GeneralMethods.isRegionProtectedFromBuild(this, this.location) && blockl.getType() != Material.LEAVES && (blockl.getType() == Material.AIR || blockl.getType() == Material.FIRE || ElementalAbility.isPlant(blockl) || isLava(blockl))) { + for (double i = 0; i <= this.radius; i += 0.5) { for (double angle = 0; angle < 360; angle += 10) { - Vector vec = GeneralMethods.getOrthogonalVector(targetDirection, angle, i); - Block block = location.clone().add(vec).getBlock(); + final Vector vec = GeneralMethods.getOrthogonalVector(this.targetDirection, angle, i); + final Block block = this.location.clone().add(vec).getBlock(); - if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE) || isLavabendable(block)) { + if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE) || this.isLavabendable(block)) { blocks.add(block); FireBlast.removeFireBlastsAroundPoint(block.getLocation(), 2); } @@ -179,35 +179,35 @@ public void progress() { } } - for (Block block : waveBlocks.keySet()) { + for (final Block block : this.waveBlocks.keySet()) { if (!blocks.contains(block)) { - finalRemoveLava(block); + this.finalRemoveLava(block); } } - for (Block block : blocks) { - if (!waveBlocks.containsKey(block)) { - addLava(block); + for (final Block block : blocks) { + if (!this.waveBlocks.containsKey(block)) { + this.addLava(block); } } - if (waveBlocks.isEmpty()) { - breakBlock(); - progressing = false; + if (this.waveBlocks.isEmpty()) { + this.breakBlock(); + this.progressing = false; return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2 * radius)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2 * this.radius)) { boolean knockback = false; - for (Block block : waveBlocks.keySet()) { + for (final Block block : this.waveBlocks.keySet()) { if (entity.getLocation().distanceSquared(block.getLocation()) <= 2 * 2) { - if (entity.getEntityId() != player.getEntityId() || canHitSelf) { + if (entity.getEntityId() != this.player.getEntityId() || this.canHitSelf) { knockback = true; } } } if (knockback) { - Vector dir = direction.clone(); - dir.setY(dir.getY() * verticalPush); - entity.setVelocity(entity.getVelocity().clone().add(dir.clone().multiply(horizontalPush))); + final Vector dir = direction.clone(); + dir.setY(dir.getY() * this.verticalPush); + entity.setVelocity(entity.getVelocity().clone().add(dir.clone().multiply(this.horizontalPush))); entity.setFallDistance(0); if (entity.getFireTicks() > 0) { @@ -217,17 +217,17 @@ public void progress() { } } - if (!progressing) { - breakBlock(); + if (!this.progressing) { + this.breakBlock(); return; } - if (location.distanceSquared(targetDestination) < 1) { - progressing = false; - breakBlock(); + if (this.location.distanceSquared(this.targetDestination) < 1) { + this.progressing = false; + this.breakBlock(); return; } - if (radius < maxRadius) { - radius += .5; + if (this.radius < this.maxRadius) { + this.radius += .5; } return; } @@ -236,30 +236,30 @@ public void progress() { } private void breakBlock() { - for (Block block : waveBlocks.keySet()) { - finalRemoveLava(block); + for (final Block block : this.waveBlocks.keySet()) { + this.finalRemoveLava(block); } - remove(); + this.remove(); } - private void finalRemoveLava(Block block) { - if (waveBlocks.containsKey(block)) { + private void finalRemoveLava(final Block block) { + if (this.waveBlocks.containsKey(block)) { TempBlock.revertBlock(block, Material.AIR); - waveBlocks.remove(block); + this.waveBlocks.remove(block); } } - private void addLava(Block block) { + private void addLava(final Block block) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return; } else if (!TempBlock.isTempBlock(block)) { new TempBlock(block, Material.STATIONARY_LAVA, (byte) 8); - waveBlocks.put(block, block); + this.waveBlocks.put(block, block); } } - public static boolean isBlockInWave(Block block) { - for (LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { + public static boolean isBlockInWave(final Block block) { + for (final LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { if (block.getWorld().equals(lavaWave.location.getWorld()) && block.getLocation().distance(lavaWave.location) <= 2 * lavaWave.radius) { return true; } @@ -267,8 +267,8 @@ public static boolean isBlockInWave(Block block) { return false; } - public static boolean isBlockWave(Block block) { - for (LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { + public static boolean isBlockWave(final Block block) { + for (final LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { if (lavaWave.waveBlocks.containsKey(block)) { return true; } @@ -276,20 +276,20 @@ public static boolean isBlockWave(Block block) { return false; } - public static void launch(Player player) { - LavaSurgeWave lavaWave = getAbility(player, LavaSurgeWave.class); + public static void launch(final Player player) { + final LavaSurgeWave lavaWave = getAbility(player, LavaSurgeWave.class); if (lavaWave != null) { lavaWave.moveLava(); } } public static void cleanup() { - for (LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { - for (Block block : lavaWave.waveBlocks.keySet()) { + for (final LavaSurgeWave lavaWave : getAbilities(LavaSurgeWave.class)) { + for (final Block block : lavaWave.waveBlocks.keySet()) { block.setType(Material.AIR); lavaWave.waveBlocks.remove(block); } - for (Block block : lavaWave.frozenBlocks.keySet()) { + for (final Block block : lavaWave.frozenBlocks.keySet()) { block.setType(Material.AIR); lavaWave.frozenBlocks.remove(block); } @@ -303,12 +303,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -320,121 +320,121 @@ public boolean isSneakAbility() { public boolean isHarmlessAbility() { return false; } - + @Override public boolean isHiddenAbility() { return true; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public boolean isCanHitSelf() { - return canHitSelf; + return this.canHitSelf; } - public void setCanHitSelf(boolean canHitSelf) { + public void setCanHitSelf(final boolean canHitSelf) { this.canHitSelf = canHitSelf; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getMaxRadius() { - return maxRadius; + return this.maxRadius; } - public void setMaxRadius(double maxRadius) { + public void setMaxRadius(final double maxRadius) { this.maxRadius = maxRadius; } public double getHorizontalPush() { - return horizontalPush; + return this.horizontalPush; } - public void setHorizontalPush(double horizontalPush) { + public void setHorizontalPush(final double horizontalPush) { this.horizontalPush = horizontalPush; } public double getVerticalPush() { - return verticalPush; + return this.verticalPush; } - public void setVerticalPush(double verticalPush) { + public void setVerticalPush(final double verticalPush) { this.verticalPush = verticalPush; } public double getInterval() { - return interval; + return this.interval; } - public void setInterval(double interval) { + public void setInterval(final double interval) { this.interval = interval; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getTargetDestination() { - return targetDestination; + return this.targetDestination; } - public void setTargetDestination(Location targetDestination) { + public void setTargetDestination(final Location targetDestination) { this.targetDestination = targetDestination; } public Vector getTargetDirection() { - return targetDirection; + return this.targetDirection; } - public void setTargetDirection(Vector targetDirection) { + public void setTargetDirection(final Vector targetDirection) { this.targetDirection = targetDirection; } public ConcurrentHashMap getWaveBlocks() { - return waveBlocks; + return this.waveBlocks; } public ConcurrentHashMap getFrozenBlocks() { - return frozenBlocks; + return this.frozenBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/earthbending/metal/Extraction.java b/src/com/projectkorra/projectkorra/earthbending/metal/Extraction.java index cb4381efd..0805d8949 100644 --- a/src/com/projectkorra/projectkorra/earthbending/metal/Extraction.java +++ b/src/com/projectkorra/projectkorra/earthbending/metal/Extraction.java @@ -10,7 +10,6 @@ import org.bukkit.inventory.ItemStack; import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.ability.MetalAbility; public class Extraction extends MetalAbility { @@ -21,7 +20,7 @@ public class Extraction extends MetalAbility { private long cooldown; private Block originBlock; - public Extraction(Player player) { + public Extraction(final Player player) { super(player); this.doubleChance = getConfig().getInt("Abilities.Earth.Extraction.DoubleLootChance"); @@ -29,64 +28,61 @@ public Extraction(Player player) { this.cooldown = getConfig().getLong("Abilities.Earth.Extraction.Cooldown"); this.selectRange = getConfig().getInt("Abilities.Earth.Extraction.SelectRange"); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } - originBlock = player.getTargetBlock((HashSet) null, selectRange); - if (originBlock == null) { + this.originBlock = player.getTargetBlock((HashSet) null, this.selectRange); + if (this.originBlock == null) { return; } - - Material material = originBlock.getType(); - - if (!GeneralMethods.isRegionProtectedFromBuild(this, originBlock.getLocation())) { - if (EarthAbility.isMetalbendable(player, material)) { - Material type = null; - - switch (material) { - case IRON_ORE: - originBlock.setType(Material.STONE); - player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.IRON_INGOT, getAmount())); - type = Material.STONE; - break; - case GOLD_ORE: - originBlock.setType(Material.STONE); - player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.GOLD_INGOT, getAmount())); - type = Material.STONE; - break; - case QUARTZ_ORE: - originBlock.setType(Material.NETHERRACK); - player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.QUARTZ, getAmount())); - type = Material.NETHERRACK; - break; - default: - break; - } - if (type != null) { - /* - * Update the block from Methods.movedearth to Stone - * otherwise players can use RaiseEarth > Extraction > - * Collapse to dupe the material from the block. - */ - if (getMovedEarth().containsKey(originBlock)) { - getMovedEarth().remove(originBlock); - } - } + if (!GeneralMethods.isRegionProtectedFromBuild(this, this.originBlock.getLocation())) { + final Material material = this.originBlock.getType(); + Material type = null; + + switch (material) { + case IRON_ORE: + this.originBlock.setType(Material.STONE); + player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.IRON_INGOT, this.getAmount())); + type = Material.STONE; + break; + case GOLD_ORE: + this.originBlock.setType(Material.STONE); + player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.GOLD_INGOT, this.getAmount())); + type = Material.STONE; + break; + case QUARTZ_ORE: + this.originBlock.setType(Material.NETHERRACK); + player.getWorld().dropItem(player.getLocation(), new ItemStack(Material.QUARTZ, this.getAmount())); + type = Material.NETHERRACK; + break; + default: + return; + } - playMetalbendingSound(originBlock.getLocation()); - start(); - bPlayer.addCooldown(this); - remove(); + if (type != null) { + /* + * Update the block from Methods.movedearth to Stone otherwise + * players can use RaiseEarth > Extraction > Collapse to dupe + * the material from the block. + */ + if (getMovedEarth().containsKey(this.originBlock)) { + getMovedEarth().remove(this.originBlock); + } } + + playMetalbendingSound(this.originBlock.getLocation()); + this.start(); + this.bPlayer.addCooldown(this); + this.remove(); } } private int getAmount() { - Random rand = new Random(); - return rand.nextInt(99) + 1 <= tripleChance ? 3 : rand.nextInt(99) + 1 <= doubleChance ? 2 : 1; + final Random rand = new Random(); + return rand.nextInt(99) + 1 <= this.tripleChance ? 3 : rand.nextInt(99) + 1 <= this.doubleChance ? 2 : 1; } @Override @@ -100,17 +96,17 @@ public void progress() { @Override public Location getLocation() { - if (originBlock != null) { - return originBlock.getLocation(); - } else if (player != null) { - return player.getLocation(); + if (this.originBlock != null) { + return this.originBlock.getLocation(); + } else if (this.player != null) { + return this.player.getLocation(); } return null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -124,38 +120,38 @@ public boolean isHarmlessAbility() { } public int getDoubleChance() { - return doubleChance; + return this.doubleChance; } - public void setDoubleChance(int doubleChance) { + public void setDoubleChance(final int doubleChance) { this.doubleChance = doubleChance; } public int getTripleChance() { - return tripleChance; + return this.tripleChance; } - public void setTripleChance(int tripleChance) { + public void setTripleChance(final int tripleChance) { this.tripleChance = tripleChance; } public int getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(int selectRange) { + public void setSelectRange(final int selectRange) { this.selectRange = selectRange; } public Block getOriginBlock() { - return originBlock; + return this.originBlock; } - public void setOriginBlock(Block originBlock) { + public void setOriginBlock(final Block originBlock) { this.originBlock = originBlock; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java b/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java index 6caa45efd..b4857b186 100644 --- a/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java +++ b/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java @@ -50,10 +50,9 @@ public class MetalClips extends MetalAbility { private double crushDamage; private double damage; private LivingEntity targetEntity; - //private ItemStack[] oldArmor; private List trackedIngots; - public MetalClips(Player player, int abilityType) { + public MetalClips(final Player player, final int abilityType) { super(player); if (hasAbility(player, MetalClips.class)) { return; @@ -75,218 +74,213 @@ public MetalClips(Player player, int abilityType) { this.canThrow = (getConfig().getBoolean("Abilities.Earth.MetalClips.ThrowEnabled") && player.hasPermission("bending.ability.metalclips.throw")); this.trackedIngots = new ArrayList<>(); - if (bPlayer.isAvatarState()) { - cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.MetalClips.Cooldown"); - range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.MetalClips.Range"); - crushDamage = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.MetalClips.CrushDamage"); + if (this.bPlayer.isAvatarState()) { + this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.MetalClips.Cooldown"); + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.MetalClips.Range"); + this.crushDamage = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.MetalClips.CrushDamage"); } if (abilityType == 0) { - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } if (!player.getInventory().containsAtLeast(new ItemStack(Material.IRON_INGOT), 1)) { return; } - shootMetal(); + this.shootMetal(); } else if (abilityType == 1) { - if (bPlayer.isOnCooldown("MetalClips Magnet")) { + if (this.bPlayer.isOnCooldown("MetalClips Magnet")) { return; } - isMagnetized = true; + this.isMagnetized = true; } - start(); + this.start(); } /* * public static ItemStack getOriginalHelmet(LivingEntity ent) { MetalClips * clips = TARGET_TO_ABILITY.get(ent); if (clips != null) { return * clips.oldArmor[3]; } return null; } - * + * * public static ItemStack getOriginalChestplate(LivingEntity ent) { * MetalClips clips = TARGET_TO_ABILITY.get(ent); if (clips != null) { * return clips.oldArmor[2]; } return null; } - * + * * public static ItemStack getOriginalLeggings(LivingEntity ent) { * MetalClips clips = TARGET_TO_ABILITY.get(ent); if (clips != null) { * return clips.oldArmor[1]; } return null; } - * + * * public static ItemStack getOriginalBoots(LivingEntity ent) { MetalClips * clips = TARGET_TO_ABILITY.get(ent); if (clips != null) { return * clips.oldArmor[0]; } return null; } - * + * * public static ItemStack[] getOriginalArmor(LivingEntity ent) { MetalClips * clips = TARGET_TO_ABILITY.get(ent); if (clips != null) { return * clips.oldArmor; } return null; } */ public void shootMetal() { - if (bPlayer.isOnCooldown("MetalClips Shoot")) { + if (this.bPlayer.isOnCooldown("MetalClips Shoot")) { return; } - bPlayer.addCooldown("MetalClips Shoot", shootCooldown); - ItemStack is = new ItemStack(Material.IRON_INGOT, 1); + this.bPlayer.addCooldown("MetalClips Shoot", this.shootCooldown); + final ItemStack is = new ItemStack(Material.IRON_INGOT, 1); - if (!player.getInventory().containsAtLeast(is, 1)) { + if (!this.player.getInventory().containsAtLeast(is, 1)) { return; } - Item item = player.getWorld().dropItemNaturally(player.getLocation().add(0, 1, 0), is); + final Item item = this.player.getWorld().dropItemNaturally(this.player.getLocation().add(0, 1, 0), is); Vector vector; - Entity targetedEntity = GeneralMethods.getTargetedEntity(player, range, new ArrayList()); + final Entity targetedEntity = GeneralMethods.getTargetedEntity(this.player, this.range, new ArrayList()); if (targetedEntity != null) { - vector = GeneralMethods.getDirection(player.getLocation(), targetedEntity.getLocation()); + vector = GeneralMethods.getDirection(this.player.getLocation(), targetedEntity.getLocation()); } else { - vector = GeneralMethods.getDirection(player.getLocation(), GeneralMethods.getTargetedLocation(player, range)); + vector = GeneralMethods.getDirection(this.player.getLocation(), GeneralMethods.getTargetedLocation(this.player, this.range)); } item.setVelocity(vector.normalize().add(new Vector(0, 0.1, 0).multiply(1.2))); - trackedIngots.add(item); - player.getInventory().removeItem(is); + this.trackedIngots.add(item); + this.player.getInventory().removeItem(is); } public void formArmor() { - if (metalClipsCount >= 4) { + if (this.metalClipsCount >= 4) { return; - } else if (metalClipsCount == 3 && !canUse4Clips) { + } else if (this.metalClipsCount == 3 && !this.canUse4Clips) { return; - } else if (targetEntity != null && GeneralMethods.isRegionProtectedFromBuild(this, targetEntity.getLocation())) { + } else if (this.targetEntity != null && GeneralMethods.isRegionProtectedFromBuild(this, this.targetEntity.getLocation())) { return; } - metalClipsCount = (metalClipsCount < 4) ? metalClipsCount + 1 : 4; + this.metalClipsCount = (this.metalClipsCount < 4) ? this.metalClipsCount + 1 : 4; - if (targetEntity instanceof Player) { - Player target = (Player) targetEntity; + for (final TempArmor armor : TempArmor.getTempArmorList(this.targetEntity)) { + armor.revert(); + } - ItemStack[] metalArmor = new ItemStack[4]; + if (this.targetEntity instanceof Player) { + final Player target = (Player) this.targetEntity; - metalArmor[2] = (metalClipsCount >= 1) ? new ItemStack(Material.IRON_CHESTPLATE) : new ItemStack(Material.AIR); - metalArmor[0] = (metalClipsCount >= 2) ? new ItemStack(Material.IRON_BOOTS) : new ItemStack(Material.AIR); - metalArmor[1] = (metalClipsCount >= 3) ? new ItemStack(Material.IRON_LEGGINGS) : new ItemStack(Material.AIR); - metalArmor[3] = (metalClipsCount >= 4) ? new ItemStack(Material.IRON_HELMET) : new ItemStack(Material.AIR); - ENTITY_CLIPS_COUNT.put(target, metalClipsCount); + final ItemStack[] metalArmor = new ItemStack[4]; - TempArmor armor = TempArmor.getTempArmor(target); - if (armor != null) - armor.revert(); + metalArmor[2] = (this.metalClipsCount >= 1) ? new ItemStack(Material.IRON_CHESTPLATE) : new ItemStack(Material.AIR); + metalArmor[0] = (this.metalClipsCount >= 2) ? new ItemStack(Material.IRON_BOOTS) : new ItemStack(Material.AIR); + metalArmor[1] = (this.metalClipsCount >= 3) ? new ItemStack(Material.IRON_LEGGINGS) : new ItemStack(Material.AIR); + metalArmor[3] = (this.metalClipsCount >= 4) ? new ItemStack(Material.IRON_HELMET) : new ItemStack(Material.AIR); + ENTITY_CLIPS_COUNT.put(target, this.metalClipsCount); new TempArmor(target, this, metalArmor); } else { + final ItemStack[] metalarmor = new ItemStack[4]; - ItemStack[] metalarmor = new ItemStack[4]; - - metalarmor[2] = (metalClipsCount >= 1) ? new ItemStack(Material.IRON_CHESTPLATE) : new ItemStack(Material.AIR); - metalarmor[0] = (metalClipsCount >= 2) ? new ItemStack(Material.IRON_BOOTS) : new ItemStack(Material.AIR); - metalarmor[1] = (metalClipsCount >= 3) ? new ItemStack(Material.IRON_LEGGINGS) : new ItemStack(Material.AIR); - metalarmor[3] = (metalClipsCount >= 4) ? new ItemStack(Material.IRON_HELMET) : new ItemStack(Material.AIR); - ENTITY_CLIPS_COUNT.put(targetEntity, metalClipsCount); - - TempArmor armor = TempArmor.getTempArmor(targetEntity); - if (armor != null) - armor.revert(); + metalarmor[2] = (this.metalClipsCount >= 1) ? new ItemStack(Material.IRON_CHESTPLATE) : new ItemStack(Material.AIR); + metalarmor[0] = (this.metalClipsCount >= 2) ? new ItemStack(Material.IRON_BOOTS) : new ItemStack(Material.AIR); + metalarmor[1] = (this.metalClipsCount >= 3) ? new ItemStack(Material.IRON_LEGGINGS) : new ItemStack(Material.AIR); + metalarmor[3] = (this.metalClipsCount >= 4) ? new ItemStack(Material.IRON_HELMET) : new ItemStack(Material.AIR); + ENTITY_CLIPS_COUNT.put(this.targetEntity, this.metalClipsCount); - new TempArmor(targetEntity, this, metalarmor); + new TempArmor(this.targetEntity, this, metalarmor); } - armorStartTime = System.currentTimeMillis(); - isBeingWorn = true; + this.armorStartTime = System.currentTimeMillis(); + this.isBeingWorn = true; } public void resetArmor() { - if (!isMagnetized) { - bPlayer.addCooldown(this); + if (!this.isMagnetized) { + this.bPlayer.addCooldown(this); } - if (targetEntity == null || !TempArmor.hasTempArmor(targetEntity) || targetEntity.isDead()) { + if (this.targetEntity == null || !TempArmor.hasTempArmor(this.targetEntity) || this.targetEntity.isDead()) { return; } - TempArmor.getTempArmor(targetEntity).revert(); + TempArmor.getVisibleTempArmor(this.targetEntity).revert(); - dropIngots(targetEntity.getLocation()); - isBeingWorn = false; + this.dropIngots(this.targetEntity.getLocation()); + this.isBeingWorn = false; } public void launch() { - if (!canThrow) { + if (!this.canThrow) { return; } - if (targetEntity == null) { + if (this.targetEntity == null) { return; } - Location location = player.getLocation(); + final Location location = this.player.getLocation(); double dx, dy, dz; - Location target = targetEntity.getLocation().clone(); + final Location target = this.targetEntity.getLocation().clone(); dx = target.getX() - location.getX(); dy = target.getY() - location.getY(); dz = target.getZ() - location.getZ(); - Vector vector = new Vector(dx, dy, dz); + final Vector vector = new Vector(dx, dy, dz); vector.normalize(); - targetEntity.setVelocity(vector.multiply(metalClipsCount / 2).normalize()); - remove(); + this.targetEntity.setVelocity(vector.multiply(this.metalClipsCount / 2).normalize()); + this.remove(); } public void crush() { - if (bPlayer.isOnCooldown("MetalClips Crush")) { + if (this.bPlayer.isOnCooldown("MetalClips Crush")) { return; } - bPlayer.addCooldown("MetalClips Crush", crushCooldown); - DamageHandler.damageEntity(targetEntity, player, crushDamage, this); + this.bPlayer.addCooldown("MetalClips Crush", this.crushCooldown); + DamageHandler.damageEntity(this.targetEntity, this.player, this.crushDamage, this); } @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (targetEntity != null) { - if ((targetEntity instanceof Player && !((Player) targetEntity).isOnline()) || targetEntity.isDead()) { - remove(); + if (this.targetEntity != null) { + if ((this.targetEntity instanceof Player && !((Player) this.targetEntity).isOnline()) || this.targetEntity.isDead()) { + this.remove(); return; } } - if (player.isSneaking()) { - hasSnuck = true; + if (this.player.isSneaking()) { + this.hasSnuck = true; } - if (!player.isSneaking()) { - if (isMagnetized) { - bPlayer.addCooldown("MetalClips Magnet", magnetCooldown); - remove(); + if (!this.player.isSneaking()) { + if (this.isMagnetized) { + this.bPlayer.addCooldown("MetalClips Magnet", this.magnetCooldown); + this.remove(); return; } - isControlling = false; - isMagnetized = false; - if (metalClipsCount < 4 && hasSnuck && abilityType == 0) { - launch(); + this.isControlling = false; + this.isMagnetized = false; + if (this.metalClipsCount < 4 && this.hasSnuck && this.abilityType == 0) { + this.launch(); } } - if (isMagnetized) { - if (GeneralMethods.getEntitiesAroundPoint(player.getLocation(), magnetRange).size() == 0) { - remove(); + if (this.isMagnetized) { + if (GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.magnetRange).size() == 0) { + this.remove(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), magnetRange)) { - Vector vector = GeneralMethods.getDirection(entity.getLocation(), player.getLocation()); - ItemStack itemInHand = player.getInventory().getItemInMainHand(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.magnetRange)) { + final Vector vector = GeneralMethods.getDirection(entity.getLocation(), this.player.getLocation()); + final ItemStack itemInHand = this.player.getInventory().getItemInMainHand(); - if (entity instanceof Player && canLoot && itemInHand.getType() == Material.IRON_INGOT && (itemInHand.hasItemMeta() && itemInHand.getItemMeta().getDisplayName().equalsIgnoreCase("Magnet"))) { - Player targetPlayer = (Player) entity; + if (entity instanceof Player && this.canLoot && itemInHand.getType() == Material.IRON_INGOT && (itemInHand.hasItemMeta() && itemInHand.getItemMeta().getDisplayName().equalsIgnoreCase("Magnet"))) { + final Player targetPlayer = (Player) entity; - if (targetPlayer.getEntityId() == player.getEntityId()) { + if (targetPlayer.getEntityId() == this.player.getEntityId()) { continue; } - ItemStack[] inventory = targetPlayer.getInventory().getContents(); + final ItemStack[] inventory = targetPlayer.getInventory().getContents(); - for (ItemStack is : inventory) { + for (final ItemStack is : inventory) { if (is == null) { continue; } @@ -299,9 +293,9 @@ public void progress() { } targetPlayer.getInventory().setContents(inventory); - ItemStack[] armor = targetPlayer.getInventory().getArmorContents(); + final ItemStack[] armor = targetPlayer.getInventory().getArmorContents(); - for (ItemStack is : armor) { + for (final ItemStack is : armor) { if (Arrays.asList(METAL_ITEMS).contains(is.getType())) { targetPlayer.getWorld().dropItem(targetPlayer.getLocation(), is); is.setType(Material.AIR); @@ -315,12 +309,12 @@ public void progress() { } } - if ((entity instanceof Zombie || entity instanceof Skeleton) && canLoot && itemInHand.getType() == Material.IRON_INGOT && itemInHand.getItemMeta().getDisplayName().equalsIgnoreCase("Magnet")) { - LivingEntity livingEntity = (LivingEntity) entity; + if ((entity instanceof Zombie || entity instanceof Skeleton) && this.canLoot && itemInHand.getType() == Material.IRON_INGOT && itemInHand.getItemMeta().getDisplayName().equalsIgnoreCase("Magnet")) { + final LivingEntity livingEntity = (LivingEntity) entity; - ItemStack[] armor = livingEntity.getEquipment().getArmorContents(); + final ItemStack[] armor = livingEntity.getEquipment().getArmorContents(); - for (ItemStack istack : armor) { + for (final ItemStack istack : armor) { if (Arrays.asList(METAL_ITEMS).contains(istack.getType())) { livingEntity.getWorld().dropItem(livingEntity.getLocation(), istack); istack.setType(Material.AIR); @@ -336,107 +330,107 @@ public void progress() { } if (entity instanceof Item) { - Item iron = (Item) entity; + final Item iron = (Item) entity; if (Arrays.asList(METAL_ITEMS).contains(iron.getItemStack().getType())) { - iron.setVelocity(vector.normalize().multiply(magnetPower).add(new Vector(0, 0.2, 0))); + iron.setVelocity(vector.normalize().multiply(this.magnetPower).add(new Vector(0, 0.2, 0))); } } } } - if (isBeingWorn && System.currentTimeMillis() > armorStartTime + armorTime) { - remove(); + if (this.isBeingWorn && System.currentTimeMillis() > this.armorStartTime + this.armorTime) { + this.remove(); return; } - if (isControlling && player.isSneaking()) { - if (metalClipsCount == 1) { - Location oldLocation = targetEntity.getLocation(); + if (this.isControlling && this.player.isSneaking()) { + if (this.metalClipsCount == 1) { + final Location oldLocation = this.targetEntity.getLocation(); Location loc = oldLocation; - if (player.getWorld().equals(oldLocation.getWorld())) { - loc = GeneralMethods.getTargetedLocation(player, (int) player.getLocation().distance(oldLocation)); + if (this.player.getWorld().equals(oldLocation.getWorld())) { + loc = GeneralMethods.getTargetedLocation(this.player, (int) this.player.getLocation().distance(oldLocation)); } double distance = 0; if (loc.getWorld().equals(oldLocation.getWorld())) { distance = loc.distance(oldLocation); } - Vector vector = GeneralMethods.getDirection(targetEntity.getLocation(), player.getLocation()); + final Vector vector = GeneralMethods.getDirection(this.targetEntity.getLocation(), this.player.getLocation()); if (distance > 0.5) { - targetEntity.setVelocity(vector.normalize().multiply(0.2)); + this.targetEntity.setVelocity(vector.normalize().multiply(0.2)); } } - if (metalClipsCount == 2) { - Location oldLocation = targetEntity.getLocation(); + if (this.metalClipsCount == 2) { + final Location oldLocation = this.targetEntity.getLocation(); Location loc = oldLocation; - if (player.getWorld().equals(oldLocation.getWorld())) { - loc = GeneralMethods.getTargetedLocation(player, (int) player.getLocation().distance(oldLocation)); + if (this.player.getWorld().equals(oldLocation.getWorld())) { + loc = GeneralMethods.getTargetedLocation(this.player, (int) this.player.getLocation().distance(oldLocation)); } double distance = 0; if (loc.getWorld().equals(oldLocation.getWorld())) { distance = loc.distance(oldLocation); } - Vector vector = GeneralMethods.getDirection(targetEntity.getLocation(), GeneralMethods.getTargetedLocation(player, 10)); + final Vector vector = GeneralMethods.getDirection(this.targetEntity.getLocation(), GeneralMethods.getTargetedLocation(this.player, 10)); if (distance > 1.2) { - targetEntity.setVelocity(vector.normalize().multiply(0.2)); + this.targetEntity.setVelocity(vector.normalize().multiply(0.2)); } } - if (metalClipsCount >= 3) { - Location oldLocation = targetEntity.getLocation(); + if (this.metalClipsCount >= 3) { + final Location oldLocation = this.targetEntity.getLocation(); Location loc = oldLocation; - if (player.getWorld().equals(oldLocation.getWorld())) { - loc = GeneralMethods.getTargetedLocation(player, (int) player.getLocation().distance(oldLocation)); + if (this.player.getWorld().equals(oldLocation.getWorld())) { + loc = GeneralMethods.getTargetedLocation(this.player, (int) this.player.getLocation().distance(oldLocation)); } double distance = 0; if (loc.getWorld().equals(oldLocation.getWorld())) { distance = loc.distance(oldLocation); } - Vector vector = GeneralMethods.getDirection(oldLocation, GeneralMethods.getTargetedLocation(player, 10)); + final Vector vector = GeneralMethods.getDirection(oldLocation, GeneralMethods.getTargetedLocation(this.player, 10)); if (distance > 1.2) { - targetEntity.setVelocity(vector.normalize().multiply(.5)); + this.targetEntity.setVelocity(vector.normalize().multiply(.5)); } else { - targetEntity.setVelocity(new Vector(0, 0, 0)); + this.targetEntity.setVelocity(new Vector(0, 0, 0)); } - targetEntity.setFallDistance(0); + this.targetEntity.setFallDistance(0); } } - for (int i = trackedIngots.size() - 1; i >= 0; i--) { - Item ii = trackedIngots.get(i); + for (int i = this.trackedIngots.size() - 1; i >= 0; i--) { + final Item ii = this.trackedIngots.get(i); if (ii.isOnGround()) { - trackedIngots.remove(i); + this.trackedIngots.remove(i); continue; } if (ii.getItemStack().getType() == Material.IRON_INGOT) { if (GeneralMethods.getEntitiesAroundPoint(ii.getLocation(), 2).size() == 0) { - remove(); + this.remove(); return; } - for (Entity e : GeneralMethods.getEntitiesAroundPoint(ii.getLocation(), 2)) { - if (e instanceof LivingEntity && e.getEntityId() != player.getEntityId()) { + for (final Entity e : GeneralMethods.getEntitiesAroundPoint(ii.getLocation(), 2)) { + if (e instanceof LivingEntity && e.getEntityId() != this.player.getEntityId()) { if ((e instanceof Player || e instanceof Zombie || e instanceof Skeleton)) { - if (targetEntity == null) { - targetEntity = (LivingEntity) e; - TARGET_TO_ABILITY.put(targetEntity, this); - formArmor(); - } else if (targetEntity == e) { - formArmor(); + if (this.targetEntity == null) { + this.targetEntity = (LivingEntity) e; + TARGET_TO_ABILITY.put(this.targetEntity, this); + this.formArmor(); + } else if (this.targetEntity == e) { + this.formArmor(); } else { - dropIngots(e.getLocation()); - TARGET_TO_ABILITY.get(targetEntity).remove(); + this.dropIngots(e.getLocation()); + TARGET_TO_ABILITY.get(this.targetEntity).remove(); } } else { - DamageHandler.damageEntity(e, player, damage, this); - dropIngots(e.getLocation(), ii.getItemStack().getAmount()); - remove(); + DamageHandler.damageEntity(e, this.player, this.damage, this); + this.dropIngots(e.getLocation(), ii.getItemStack().getAmount()); + this.remove(); } ii.remove(); @@ -446,23 +440,23 @@ public void progress() { } } - removeDeadIngots(); + this.removeDeadIngots(); } - - public void dropIngots(Location loc) { - dropIngots(loc, metalClipsCount == 0 ? 1 : metalClipsCount); + + public void dropIngots(final Location loc) { + this.dropIngots(loc, this.metalClipsCount == 0 ? 1 : this.metalClipsCount); } - public void dropIngots(Location loc, int amount) { - Item i = player.getWorld().dropItem(loc, new ItemStack(Material.IRON_INGOT, amount)); + public void dropIngots(final Location loc, final int amount) { + final Item i = this.player.getWorld().dropItem(loc, new ItemStack(Material.IRON_INGOT, amount)); i.setPickupDelay(61); } public void removeDeadIngots() { - for (int i = 0; i < trackedIngots.size(); i++) { - Item ii = trackedIngots.get(i); + for (int i = 0; i < this.trackedIngots.size(); i++) { + final Item ii = this.trackedIngots.get(i); if (ii.isDead()) { - trackedIngots.remove(ii); + this.trackedIngots.remove(ii); } } } @@ -471,22 +465,22 @@ public void removeDeadIngots() { public void remove() { super.remove(); - resetArmor(); - trackedIngots.clear(); - metalClipsCount = 0; + this.resetArmor(); + this.trackedIngots.clear(); + this.metalClipsCount = 0; - if (targetEntity != null) { - ENTITY_CLIPS_COUNT.remove(targetEntity); - TARGET_TO_ABILITY.remove(targetEntity); + if (this.targetEntity != null) { + ENTITY_CLIPS_COUNT.remove(this.targetEntity); + TARGET_TO_ABILITY.remove(this.targetEntity); } } - public static boolean isControlled(LivingEntity player) { + public static boolean isControlled(final LivingEntity player) { return TARGET_TO_ABILITY.containsKey(player); } - public static boolean isControllingEntity(Player player) { - MetalClips clips = getAbility(player, MetalClips.class); + public static boolean isControllingEntity(final Player player) { + final MetalClips clips = getAbility(player, MetalClips.class); return clips != null && player.isSneaking() && clips.targetEntity != null; } @@ -498,10 +492,11 @@ public static Map getTargetToAbility() { return TARGET_TO_ABILITY; } - public static boolean removeControlledEnitity(LivingEntity entity) { - if (entity == null) + public static boolean removeControlledEnitity(final LivingEntity entity) { + if (entity == null) { return false; - for (MetalClips metalclips : CoreAbility.getAbilities(MetalClips.class)) { + } + for (final MetalClips metalclips : CoreAbility.getAbilities(MetalClips.class)) { if (metalclips.targetEntity == entity) { metalclips.remove(); return true; @@ -517,25 +512,25 @@ public String getName() { @Override public Location getLocation() { - if (targetEntity != null) { - return targetEntity.getLocation(); - } else if (player != null) { - return player.getLocation(); + if (this.targetEntity != null) { + return this.targetEntity.getLocation(); + } else if (this.player != null) { + return this.player.getLocation(); } return null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } public long getShootCooldown() { - return shootCooldown; + return this.shootCooldown; } public long getCrushCooldown() { - return crushCooldown; + return this.crushCooldown; } @Override @@ -549,130 +544,130 @@ public boolean isHarmlessAbility() { } public boolean isBeingWorn() { - return isBeingWorn; + return this.isBeingWorn; } - public void setBeingWorn(boolean isBeingWorn) { + public void setBeingWorn(final boolean isBeingWorn) { this.isBeingWorn = isBeingWorn; } public boolean isControlling() { - return isControlling; + return this.isControlling; } - public void setControlling(boolean isControlling) { + public void setControlling(final boolean isControlling) { this.isControlling = isControlling; } public boolean isCanThrow() { - return canThrow; + return this.canThrow; } - public void setCanThrow(boolean canThrow) { + public void setCanThrow(final boolean canThrow) { this.canThrow = canThrow; } public boolean isMagnetized() { - return isMagnetized; + return this.isMagnetized; } - public void setMagnetized(boolean isMagnetized) { + public void setMagnetized(final boolean isMagnetized) { this.isMagnetized = isMagnetized; } public boolean isCanUse4Clips() { - return canUse4Clips; + return this.canUse4Clips; } - public void setCanUse4Clips(boolean canUse4Clips) { + public void setCanUse4Clips(final boolean canUse4Clips) { this.canUse4Clips = canUse4Clips; } public boolean isCanLoot() { - return canLoot; + return this.canLoot; } - public void setCanLoot(boolean canLoot) { + public void setCanLoot(final boolean canLoot) { this.canLoot = canLoot; } public int getMetalClipsCount() { - return metalClipsCount; + return this.metalClipsCount; } - public void setMetalClipsCount(int metalClipsCount) { + public void setMetalClipsCount(final int metalClipsCount) { this.metalClipsCount = metalClipsCount; } public int getAbilityType() { - return abilityType; + return this.abilityType; } - public void setAbilityType(int abilityType) { + public void setAbilityType(final int abilityType) { this.abilityType = abilityType; } public int getArmorTime() { - return armorTime; + return this.armorTime; } - public void setArmorTime(int armorTime) { + public void setArmorTime(final int armorTime) { this.armorTime = armorTime; } public double getCrushDamage() { - return crushDamage; + return this.crushDamage; } - public void setCrushDamage(double crushDamage) { + public void setCrushDamage(final double crushDamage) { this.crushDamage = crushDamage; } public int getMagnetRange() { - return magnetRange; + return this.magnetRange; } - public void setMagnetRange(int magnetRange) { + public void setMagnetRange(final int magnetRange) { this.magnetRange = magnetRange; } public long getArmorStartTime() { - return armorStartTime; + return this.armorStartTime; } - public void setArmorStartTime(long armorStartTime) { + public void setArmorStartTime(final long armorStartTime) { this.armorStartTime = armorStartTime; } public double getMagnetPower() { - return magnetPower; + return this.magnetPower; } - public void setMagnetPower(double magnetPower) { + public void setMagnetPower(final double magnetPower) { this.magnetPower = magnetPower; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public LivingEntity getTargetEntity() { - return targetEntity; + return this.targetEntity; } - public void setTargetEntity(LivingEntity targetEntity) { + public void setTargetEntity(final LivingEntity targetEntity) { this.targetEntity = targetEntity; } public List getTrackedIngots() { - return trackedIngots; + return this.trackedIngots; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/earthbending/passive/DensityShift.java b/src/com/projectkorra/projectkorra/earthbending/passive/DensityShift.java index b8ebb85a0..ba00ce208 100644 --- a/src/com/projectkorra/projectkorra/earthbending/passive/DensityShift.java +++ b/src/com/projectkorra/projectkorra/earthbending/passive/DensityShift.java @@ -1,20 +1,137 @@ package com.projectkorra.projectkorra.earthbending.passive; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; +import org.bukkit.material.MaterialData; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; +import com.projectkorra.projectkorra.command.Commands; +import com.projectkorra.projectkorra.configuration.ConfigManager; +import com.projectkorra.projectkorra.util.TempBlock; public class DensityShift extends EarthAbility implements PassiveAbility { + private static final Map SAND_BLOCKS = new ConcurrentHashMap<>(); + private static final Map SAND_ID_ENTITIES = new ConcurrentHashMap<>(); - public DensityShift(Player player) { + public DensityShift(final Player player) { super(player); } + public static boolean softenLanding(final Player player) { + if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { + return false; + } + + final Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (bPlayer == null) { + return false; + } else if (bPlayer.canMetalbend() && ElementalAbility.isMetalBlock(block)) { + return true; + } + + if (ElementalAbility.isEarth(block) || ElementalAbility.isTransparent(player, block)) { + if (!ElementalAbility.isTransparent(player, block)) { + final MaterialData type = block.getState().getData(); + if (GeneralMethods.isSolid(block.getRelative(BlockFace.DOWN))) { + if (type.getItemType() == Material.RED_SANDSTONE) { + final byte data = (byte) 0x1; + block.setType(Material.SAND); + block.setData(data); + } else { + block.setType(Material.SAND); + } + + if (!SAND_BLOCKS.containsKey(block)) { + SAND_ID_ENTITIES.put(block, type); + SAND_BLOCKS.put(block, System.currentTimeMillis()); + } + } + } + + for (final Block affectedBlock : GeneralMethods.getBlocksAroundPoint(block.getLocation(), 2)) { + if (ElementalAbility.isEarth(affectedBlock)) { + if (GeneralMethods.isSolid(affectedBlock.getRelative(BlockFace.DOWN))) { + final MaterialData type = affectedBlock.getState().getData(); + if (type.getItemType() == Material.RED_SANDSTONE) { + final byte data = (byte) 0x1; + affectedBlock.setType(Material.SAND); + affectedBlock.setData(data); + } else { + affectedBlock.setType(Material.SAND); + } + + if (!SAND_BLOCKS.containsKey(affectedBlock)) { + SAND_ID_ENTITIES.put(affectedBlock, type); + SAND_BLOCKS.put(affectedBlock, System.currentTimeMillis()); + } + } + } + } + + return true; + } + + return (TempBlock.isTempBlock(block) && EarthAbility.isEarthbendable(TempBlock.get(block).getBlock().getType(), true, true, false)) || EarthAbility.isEarthbendable(block.getType(), true, true, false) || ElementalAbility.isTransparent(player, block); + } + + public static boolean isPassiveSand(final Block block) { + return SAND_BLOCKS.containsKey(block); + } + + public static void revertSand(final Block block) { + final MaterialData materialdata = SAND_ID_ENTITIES.get(block); + SAND_ID_ENTITIES.remove(block); + SAND_BLOCKS.remove(block); + + if (block.getType() == Material.SAND) { + block.setType(materialdata.getItemType()); + block.setData(materialdata.getData()); + } + } + + public static void revertSands() { + for (final Block block : SAND_BLOCKS.keySet()) { + if (System.currentTimeMillis() >= SAND_BLOCKS.get(block) + getDuration()) { + revertSand(block); + } + } + } + + public static void revertAllSand() { + for (final Block block : SAND_BLOCKS.keySet()) { + revertSand(block); + } + } + + public static void removeAll() { + revertAllSand(); + } + + public static Map getSandBlocks() { + return SAND_BLOCKS; + } + + public static Map getSandIdEntities() { + return SAND_ID_ENTITIES; + } + + public static long getDuration() { + return ConfigManager.getConfig().getLong("Abilities.Earth.Passive.Duration"); + } + @Override public void progress() { - } @Override @@ -39,7 +156,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player.getLocation(); } @Override @@ -47,4 +164,8 @@ public boolean isInstantiable() { return false; } + @Override + public boolean isProgressable() { + return false; + } } diff --git a/src/com/projectkorra/projectkorra/earthbending/passive/EarthPassive.java b/src/com/projectkorra/projectkorra/earthbending/passive/EarthPassive.java index 6df82ba16..815d4a538 100644 --- a/src/com/projectkorra/projectkorra/earthbending/passive/EarthPassive.java +++ b/src/com/projectkorra/projectkorra/earthbending/passive/EarthPassive.java @@ -1,148 +1,13 @@ package com.projectkorra.projectkorra.earthbending.passive; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.EarthAbility; -import com.projectkorra.projectkorra.ability.ElementalAbility; -import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import org.bukkit.block.Block; + import com.projectkorra.projectkorra.earthbending.lava.LavaSurgeWall; import com.projectkorra.projectkorra.earthbending.lava.LavaSurgeWave; import com.projectkorra.projectkorra.util.TempBlock; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.material.MaterialData; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - public class EarthPassive { - - private static final Map SAND_BLOCKS = new ConcurrentHashMap<>(); - private static final Map SAND_ID_ENTITIES = new ConcurrentHashMap<>(); - - @SuppressWarnings("deprecation") - public static boolean softenLanding(Player player) { - if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { - return false; - } - - Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (bPlayer == null) { - return false; - } else if (bPlayer.canMetalbend() && ElementalAbility.isMetalBlock(block)) { - return true; - } - - if (EarthAbility.isEarth(block) || ElementalAbility.isTransparent(player, block)) { - if (!ElementalAbility.isTransparent(player, block)) { - MaterialData type = block.getState().getData(); - if (GeneralMethods.isSolid(block.getRelative(BlockFace.DOWN))) { - if (type.getItemType() == Material.RED_SANDSTONE) { - byte data = (byte) 0x1; - block.setType(Material.SAND); - block.setData(data); - } else { - block.setType(Material.SAND); - } - if (!SAND_BLOCKS.containsKey(block)) { - SAND_ID_ENTITIES.put(block, type); - SAND_BLOCKS.put(block, System.currentTimeMillis()); - } - } - } - - for (Block affectedBlock : GeneralMethods.getBlocksAroundPoint(block.getLocation(), 2)) { - if (EarthAbility.isEarth(affectedBlock)) { - if (GeneralMethods.isSolid(affectedBlock.getRelative(BlockFace.DOWN))) { - MaterialData type = affectedBlock.getState().getData(); - if (type.getItemType() == Material.RED_SANDSTONE) { - byte data = (byte) 0x1; - affectedBlock.setType(Material.SAND); - affectedBlock.setData(data); - } else { - affectedBlock.setType(Material.SAND); - } - if (!SAND_BLOCKS.containsKey(affectedBlock)) { - SAND_ID_ENTITIES.put(affectedBlock, type); - SAND_BLOCKS.put(affectedBlock, System.currentTimeMillis()); - } - } - } - } - return true; - } - - return (TempBlock.isTempBlock(block) && EarthAbility.isEarthbendable(TempBlock.get(block).getBlock().getType(), true, true, false)) || EarthAbility.isEarthbendable(block.getType(), true, true, false) || EarthAbility.isTransparent(player, block); - } - - public static boolean isPassiveSand(Block block) { - return SAND_BLOCKS.containsKey(block); - } - - @SuppressWarnings("deprecation") - public static void revertSand(Block block) { - MaterialData materialdata = SAND_ID_ENTITIES.get(block); - SAND_ID_ENTITIES.remove(block); - SAND_BLOCKS.remove(block); - - if (block.getType() == Material.SAND) { - block.setType(materialdata.getItemType()); - block.setData(materialdata.getData()); - } - } - - /*@SuppressWarnings("deprecation") - public static void handleMetalPassives() { - for (Player player : Bukkit.getOnlinePlayers()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (bPlayer != null && bPlayer.canBendPassive(Element.EARTH) && bPlayer.canMetalbend()) { - if (player.isSneaking() && !bPlayer.isOnCooldown("MetalPassive")) { - Block block = player.getTargetBlock((HashSet) null, 5); - if (block == null) { - continue; - } - if (block.getType() == Material.IRON_DOOR_BLOCK && !GeneralMethods.isRegionProtectedFromBuild(player, block.getLocation())) { - if (block.getData() >= 8) { - block = block.getRelative(BlockFace.DOWN); - } - if (block.getData() < 4) { - block.setData((byte) (block.getData() + 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_IRON_DOOR_CLOSE, 10, 1); - } else { - block.setData((byte) (block.getData() - 4)); - block.getWorld().playSound(block.getLocation(), Sound.BLOCK_IRON_DOOR_OPEN, 10, 1); - } - bPlayer.addCooldown("MetalPassive", 200); - } - } - } - } - }*/ - - public static void revertSands() { - for (Block block : SAND_BLOCKS.keySet()) { - if (System.currentTimeMillis() >= SAND_BLOCKS.get(block) + getDuration()) { - revertSand(block); - } - } - } - - public static void revertAllSand() { - for (Block block : SAND_BLOCKS.keySet()) { - revertSand(block); - } - } - - public static void removeAll() { - revertAllSand(); - } - - public static boolean canPhysicsChange(Block block) { + public static boolean canPhysicsChange(final Block block) { if (LavaSurgeWall.getAffectedBlocks().containsKey(block)) { return false; } else if (LavaSurgeWall.getWallBlocks().containsKey(block)) { @@ -152,10 +17,11 @@ public static boolean canPhysicsChange(Block block) { } else if (TempBlock.isTempBlock(block)) { return false; } + return true; } - public static boolean canFlowFromTo(Block from, Block to) { + public static boolean canFlowFromTo(final Block from, final Block to) { if (LavaSurgeWall.getAffectedBlocks().containsKey(to) || LavaSurgeWall.getAffectedBlocks().containsKey(from)) { return false; } else if (LavaSurgeWall.getWallBlocks().containsKey(to) || LavaSurgeWall.getWallBlocks().containsKey(from)) { @@ -163,19 +29,7 @@ public static boolean canFlowFromTo(Block from, Block to) { } else if (LavaSurgeWave.isBlockWave(to) || LavaSurgeWave.isBlockWave(from)) { return false; } - return true; - } - - public static Map getSandBlocks() { - return SAND_BLOCKS; - } - - public static Map getSandIdEntities() { - return SAND_ID_ENTITIES; - } - public static long getDuration() { - return ConfigManager.getConfig().getLong("Abilities.Earth.Passive.Duration"); + return true; } - -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/earthbending/passive/FerroControl.java b/src/com/projectkorra/projectkorra/earthbending/passive/FerroControl.java index abe2b3d30..509cfa239 100644 --- a/src/com/projectkorra/projectkorra/earthbending/passive/FerroControl.java +++ b/src/com/projectkorra/projectkorra/earthbending/passive/FerroControl.java @@ -1,20 +1,59 @@ package com.projectkorra.projectkorra.earthbending.passive; +import java.util.HashSet; + import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.MetalAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; public class FerroControl extends MetalAbility implements PassiveAbility { - public FerroControl(Player player) { + private Block block; + + public FerroControl(final Player player) { super(player); + } @Override public void progress() { + if (!this.player.isSneaking() || !this.bPlayer.canUsePassive(this) || !this.bPlayer.canBendPassive(this)) { + return; + } + + boolean used = false, tDoor = false, open = false; + this.block = this.player.getTargetBlock((HashSet) null, 5); + + if (this.block != null) { + if (this.block.getType() == Material.IRON_DOOR_BLOCK && !GeneralMethods.isRegionProtectedFromBuild(this.player, this.block.getLocation())) { + if (this.block.getData() >= 8) { + this.block = this.block.getRelative(BlockFace.DOWN); + } + + this.block.setData((byte) ((this.block.getData() & 0x4) == 0x4 ? (this.block.getData() & ~0x4) : (this.block.getData() | 0x4))); + open = (this.block.getData() & 0x4) == 0x4; + used = true; + } else if (this.block.getType() == Material.IRON_TRAPDOOR && !GeneralMethods.isRegionProtectedFromBuild(this.player, this.block.getLocation())) { + this.block.setData((byte) ((this.block.getData() & 0x4) == 0x4 ? (this.block.getData() & ~0x4) : (this.block.getData() | 0x4))); + open = (this.block.getData() & 0x4) == 0x4; + used = true; + tDoor = true; + } + } + + if (used) { + final String sound = "BLOCK_IRON_" + (tDoor ? "TRAP" : "") + "DOOR_" + (open ? "OPEN" : "CLOSE"); + this.block.getWorld().playSound(this.block.getLocation(), Sound.valueOf(sound), 0.5f, 0); + this.bPlayer.addCooldown(this, 200); + } } @Override @@ -39,12 +78,16 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.block != null ? this.block.getLocation() : null; } @Override public boolean isInstantiable() { - return false; + return true; } + @Override + public boolean isProgressable() { + return true; + } } diff --git a/src/com/projectkorra/projectkorra/earthbending/util/EarthbendingManager.java b/src/com/projectkorra/projectkorra/earthbending/util/EarthbendingManager.java index 3590e5bc4..6e1204903 100644 --- a/src/com/projectkorra/projectkorra/earthbending/util/EarthbendingManager.java +++ b/src/com/projectkorra/projectkorra/earthbending/util/EarthbendingManager.java @@ -1,25 +1,24 @@ package com.projectkorra.projectkorra.earthbending.util; +import org.bukkit.Bukkit; + import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.earthbending.EarthTunnel; import com.projectkorra.projectkorra.earthbending.Shockwave; import com.projectkorra.projectkorra.earthbending.Tremorsense; -import com.projectkorra.projectkorra.earthbending.passive.EarthPassive; +import com.projectkorra.projectkorra.earthbending.passive.DensityShift; import com.projectkorra.projectkorra.util.RevertChecker; -import org.bukkit.Bukkit; - public class EarthbendingManager implements Runnable { - public ProjectKorra plugin; - public EarthbendingManager(ProjectKorra plugin) { + public EarthbendingManager(final ProjectKorra plugin) { this.plugin = plugin; } + @Override public void run() { - EarthPassive.revertSands(); - //EarthPassive.handleMetalPassives(); + DensityShift.revertSands(); RevertChecker.revertEarthBlocks(); Shockwave.progressAll(); Tremorsense.manage(Bukkit.getServer()); diff --git a/src/com/projectkorra/projectkorra/event/AbilityCollisionEvent.java b/src/com/projectkorra/projectkorra/event/AbilityCollisionEvent.java index bc9b217a5..8f533746c 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityCollisionEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityCollisionEvent.java @@ -13,24 +13,26 @@ public class AbilityCollisionEvent extends Event implements Cancellable { private boolean cancelled; private Collision collision; - public AbilityCollisionEvent(Collision collision) { + public AbilityCollisionEvent(final Collision collision) { this.collision = collision; this.cancelled = false; } + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - public void setCancelled(boolean cancelled) { + @Override + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public Collision getCollision() { - return collision; + return this.collision; } - public void setCollision(Collision collision) { + public void setCollision(final Collision collision) { this.collision = collision; } diff --git a/src/com/projectkorra/projectkorra/event/AbilityDamageEntityEvent.java b/src/com/projectkorra/projectkorra/event/AbilityDamageEntityEvent.java index 070ab32ec..a4875c146 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityDamageEntityEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityDamageEntityEvent.java @@ -10,7 +10,7 @@ /** * Called when an ability damages an {@link Entity} - * + * * @author kingbirdy * */ @@ -19,19 +19,19 @@ public class AbilityDamageEntityEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled = false; - private Entity entity; - private Ability ability; + private final Entity entity; + private final Ability ability; private double damage; - private boolean ignoreArmor; + private final boolean ignoreArmor; /** * Create a new AbilityDamageEntityEvent - * + * * @param entity The entity that was damaged * @param ability The damaging ability * @param damage The amount of damage done */ - public AbilityDamageEntityEvent(Entity entity, Ability ability, double damage, boolean ignoreArmor) { + public AbilityDamageEntityEvent(final Entity entity, final Ability ability, final double damage, final boolean ignoreArmor) { this.entity = entity; this.ability = ability; this.damage = damage; @@ -40,53 +40,54 @@ public AbilityDamageEntityEvent(Entity entity, Ability ability, double damage, b /** * Returns the damage dealt to the entity - * + * * @return the amount of damage done */ public double getDamage() { - return damage; + return this.damage; } /** * Sets the damage dealt to the entity - * + * * @param damage the amount of damage done */ - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } /** * Gets the entity that was damaged - * + * * @return the damaged entity */ public Entity getEntity() { - return entity; + return this.entity; } /** * Gets the ability used - * + * * @return ability used */ public Ability getAbility() { - return ability; + return this.ability; } public boolean doesIgnoreArmor() { - return ignoreArmor; + return this.ignoreArmor; } /** * Gets the player that used the ability - * + * * @return player that used ability */ public Player getSource() { - return ability.getPlayer(); + return this.ability.getPlayer(); } + @Override public HandlerList getHandlers() { return handlers; } @@ -97,11 +98,11 @@ public static HandlerList getHandlerList() { @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } } diff --git a/src/com/projectkorra/projectkorra/event/AbilityEndEvent.java b/src/com/projectkorra/projectkorra/event/AbilityEndEvent.java index 0cff9198f..c518ce7a1 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityEndEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityEndEvent.java @@ -10,12 +10,12 @@ public class AbilityEndEvent extends Event { Ability ability; - public AbilityEndEvent(Ability ability) { + public AbilityEndEvent(final Ability ability) { this.ability = ability; } public Ability getAbility() { - return ability; + return this.ability; } @Override diff --git a/src/com/projectkorra/projectkorra/event/AbilityLoadEvent.java b/src/com/projectkorra/projectkorra/event/AbilityLoadEvent.java index c489d66c5..1a100b12b 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityLoadEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityLoadEvent.java @@ -1,11 +1,11 @@ package com.projectkorra.projectkorra.event; +import java.util.jar.JarFile; + import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.bukkit.plugin.Plugin; -import java.util.jar.JarFile; - /** * Called when an ability is successfully loaded. */ @@ -19,12 +19,12 @@ public class AbilityLoadEvent extends Event { /** * Creates a new AbilityLoadEvent. - * + * * @param plugin The instance of ProjectKorra * @param loadable The class that was loaded * @param jarFile The JarFile the class was loaded from */ - public AbilityLoadEvent(Plugin plugin, T loadable, JarFile jarFile) { + public AbilityLoadEvent(final Plugin plugin, final T loadable, final JarFile jarFile) { this.plugin = plugin; this.loadable = loadable; this.jarFile = jarFile; @@ -41,28 +41,28 @@ public static HandlerList getHandlerList() { /** * Gets the JarFile the ability was loaded from. - * + * * @return The JarFile from the event */ public JarFile getJarFile() { - return jarFile; + return this.jarFile; } /** * Gets the ability's class that was loaded. - * + * * @return The loaded class */ public T getLoadable() { - return loadable; + return this.loadable; } /** * Gets the ProjectKorra instance the ability was loaded into. - * + * * @return The ProjectKorra instance */ public Plugin getPlugin() { - return plugin; + return this.plugin; } } diff --git a/src/com/projectkorra/projectkorra/event/AbilityProgressEvent.java b/src/com/projectkorra/projectkorra/event/AbilityProgressEvent.java index 970bb5c36..97bc2508a 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityProgressEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityProgressEvent.java @@ -7,7 +7,7 @@ /** * Called when an ability starts - * + * * @author Philip * */ @@ -17,14 +17,15 @@ public class AbilityProgressEvent extends Event { Ability ability; - public AbilityProgressEvent(Ability ability) { + public AbilityProgressEvent(final Ability ability) { this.ability = ability; } public Ability getAbility() { - return ability; + return this.ability; } + @Override public HandlerList getHandlers() { return handlers; } diff --git a/src/com/projectkorra/projectkorra/event/AbilityStartEvent.java b/src/com/projectkorra/projectkorra/event/AbilityStartEvent.java index 06aafb929..64f69f904 100644 --- a/src/com/projectkorra/projectkorra/event/AbilityStartEvent.java +++ b/src/com/projectkorra/projectkorra/event/AbilityStartEvent.java @@ -8,7 +8,7 @@ /** * Called when an ability starts - * + * * @author Philip * */ @@ -19,14 +19,15 @@ public class AbilityStartEvent extends Event implements Cancellable { boolean cancelled = false; Ability ability; - public AbilityStartEvent(Ability ability) { + public AbilityStartEvent(final Ability ability) { this.ability = ability; } public Ability getAbility() { - return ability; + return this.ability; } + @Override public HandlerList getHandlers() { return handlers; } @@ -37,11 +38,11 @@ public static HandlerList getHandlerList() { @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } @Override - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } diff --git a/src/com/projectkorra/projectkorra/event/AttributeModifyEvent.java b/src/com/projectkorra/projectkorra/event/AttributeModifyEvent.java index 7460fd12a..774079e5e 100644 --- a/src/com/projectkorra/projectkorra/event/AttributeModifyEvent.java +++ b/src/com/projectkorra/projectkorra/event/AttributeModifyEvent.java @@ -7,49 +7,49 @@ import com.projectkorra.projectkorra.attribute.AttributeModifier; public class AttributeModifyEvent extends Event { - - private CoreAbility ability; - private String attribute; - private double oldValue; + + private final CoreAbility ability; + private final String attribute; + private final double oldValue; private double newValue; - private AttributeModifier modifier; - - public AttributeModifyEvent(CoreAbility ability, String attribute, double oldValue, double newValue, AttributeModifier modifier) { + private final AttributeModifier modifier; + + public AttributeModifyEvent(final CoreAbility ability, final String attribute, final double oldValue, final double newValue, final AttributeModifier modifier) { this.ability = ability; this.attribute = attribute; this.oldValue = oldValue; this.newValue = newValue; this.modifier = modifier; } - + public CoreAbility getAbility() { - return ability; + return this.ability; } - + public AttributeModifier getModifier() { - return modifier; + return this.modifier; } - + public boolean hasModifier() { - return modifier != null; + return this.modifier != null; } - + public String getAttribute() { - return attribute; + return this.attribute; } - + public double getOldValue() { - return oldValue; + return this.oldValue; } - + public double getNewValue() { - return newValue; + return this.newValue; } - - public void setNewValue(double newValue) { + + public void setNewValue(final double newValue) { this.newValue = newValue; } - + @Override public HandlerList getHandlers() { return null; diff --git a/src/com/projectkorra/projectkorra/event/BendingPlayerCreationEvent.java b/src/com/projectkorra/projectkorra/event/BendingPlayerCreationEvent.java index e2311d538..2110e3d2e 100644 --- a/src/com/projectkorra/projectkorra/event/BendingPlayerCreationEvent.java +++ b/src/com/projectkorra/projectkorra/event/BendingPlayerCreationEvent.java @@ -12,12 +12,13 @@ public class BendingPlayerCreationEvent extends Event { private static final HandlerList handlers = new HandlerList(); - private BendingPlayer bPlayer; + private final BendingPlayer bPlayer; - public BendingPlayerCreationEvent(BendingPlayer bPlayer) { + public BendingPlayerCreationEvent(final BendingPlayer bPlayer) { this.bPlayer = bPlayer; } + @Override public HandlerList getHandlers() { return handlers; } @@ -30,6 +31,6 @@ public static HandlerList getHandlerList() { * @return BendingPlayer created */ public BendingPlayer getBendingPlayer() { - return bPlayer; + return this.bPlayer; } } diff --git a/src/com/projectkorra/projectkorra/event/BendingReloadEvent.java b/src/com/projectkorra/projectkorra/event/BendingReloadEvent.java index f74d5a638..c3b639fd3 100644 --- a/src/com/projectkorra/projectkorra/event/BendingReloadEvent.java +++ b/src/com/projectkorra/projectkorra/event/BendingReloadEvent.java @@ -13,12 +13,13 @@ public class BendingReloadEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled = false; - private CommandSender sender; + private final CommandSender sender; - public BendingReloadEvent(CommandSender sender) { + public BendingReloadEvent(final CommandSender sender) { this.sender = sender; } + @Override public HandlerList getHandlers() { return handlers; } @@ -31,7 +32,7 @@ public static HandlerList getHandlerList() { * @return Who called the reload */ public CommandSender getSender() { - return sender; + return this.sender; } /** @@ -39,17 +40,17 @@ public CommandSender getSender() { */ @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } /** * Sets if the event is cancelled - * + * * @param cancel boolean value indicating whether the event is cancelled or * not */ @Override - public void setCancelled(boolean cancel) { - cancelled = cancel; + public void setCancelled(final boolean cancel) { + this.cancelled = cancel; } } diff --git a/src/com/projectkorra/projectkorra/event/BindChangeEvent.java b/src/com/projectkorra/projectkorra/event/BindChangeEvent.java index 01baf0fb4..79bc2b677 100644 --- a/src/com/projectkorra/projectkorra/event/BindChangeEvent.java +++ b/src/com/projectkorra/projectkorra/event/BindChangeEvent.java @@ -6,21 +6,21 @@ /** * Called when a player binds or unbinds an ability - * + * * @author savior67 */ public class BindChangeEvent extends Event { private static final HandlerList handlers = new HandlerList(); - private Player player; - private String ability; - private int slot; //slot is -1 if it is a multiability - private boolean isBinding; //true if the ability is being binded, otherwise false - private boolean isMultiAbility; //true if the ability is a multiability + private final Player player; + private final String ability; + private final int slot; // slot is -1 if it is a multiability. + private final boolean isBinding; // true if the ability is being binded, otherwise false. + private final boolean isMultiAbility; // true if the ability is a multiability. private boolean cancelled; - //bind event for abilities - public BindChangeEvent(Player player, String ability, int slot, boolean isBinding) { + // bind event for abilities. + public BindChangeEvent(final Player player, final String ability, final int slot, final boolean isBinding) { this.player = player; this.ability = ability; this.slot = slot; @@ -29,8 +29,8 @@ public BindChangeEvent(Player player, String ability, int slot, boolean isBindin this.isMultiAbility = false; } - //used for multi abilities - public BindChangeEvent(Player player, String ability, boolean isBinding) { + // used for multi abilities. + public BindChangeEvent(final Player player, final String ability, final boolean isBinding) { this.player = player; this.ability = ability; this.slot = -1; @@ -40,7 +40,7 @@ public BindChangeEvent(Player player, String ability, boolean isBinding) { } public String getAbility() { - return ability; + return this.ability; } @Override @@ -53,26 +53,26 @@ public static HandlerList getHandlerList() { } public Player getPlayer() { - return player; + return this.player; } public int getSlot() { - return slot; + return this.slot; } public boolean isBinding() { - return isBinding; + return this.isBinding; } public boolean isCancelled() { - return cancelled; + return this.cancelled; } public boolean isMultiAbility() { - return isMultiAbility; + return this.isMultiAbility; } - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } } diff --git a/src/com/projectkorra/projectkorra/event/EntityBendingDeathEvent.java b/src/com/projectkorra/projectkorra/event/EntityBendingDeathEvent.java index 3788a50fc..327c2ac09 100644 --- a/src/com/projectkorra/projectkorra/event/EntityBendingDeathEvent.java +++ b/src/com/projectkorra/projectkorra/event/EntityBendingDeathEvent.java @@ -1,13 +1,13 @@ package com.projectkorra.projectkorra.event; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.Ability; - import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.Ability; + /** * Called when an entity is killed by * {@link GeneralMethods#damageEntity(Player player, Entity entity, double damage, String ability) @@ -17,56 +17,57 @@ public class EntityBendingDeathEvent extends Event { public static final HandlerList handlers = new HandlerList(); - private Entity entity; - private Ability ability; - private double damage; + private final Entity entity; + private final Ability ability; + private final double damage; /** * Creates a new EntityBendingDeathEvent - * + * * @param entity the entity who died * @param damage the amount of damage done in the attack that killed the * victim * @param ability the ability used to kill the entity */ - public EntityBendingDeathEvent(Entity entity, double damage, Ability ability) { + public EntityBendingDeathEvent(final Entity entity, final double damage, final Ability ability) { this.entity = entity; this.ability = ability; this.damage = damage; } /** - * + * * @return the entity that was killed */ public Entity getEntity() { - return entity; + return this.entity; } /** - * + * * @return the player who killed the entity */ public Player getAttacker() { - return ability.getPlayer(); + return this.ability.getPlayer(); } /** - * + * * @return the ability used to kill the victim */ public Ability getAbility() { - return ability; + return this.ability; } /** - * + * * @return the amount of damage done in the attack that killed the victim */ public double getDamage() { - return damage; + return this.damage; } + @Override public HandlerList getHandlers() { return handlers; } diff --git a/src/com/projectkorra/projectkorra/event/HorizontalVelocityChangeEvent.java b/src/com/projectkorra/projectkorra/event/HorizontalVelocityChangeEvent.java index 7ea8c708f..1941fb65a 100644 --- a/src/com/projectkorra/projectkorra/event/HorizontalVelocityChangeEvent.java +++ b/src/com/projectkorra/projectkorra/event/HorizontalVelocityChangeEvent.java @@ -19,17 +19,17 @@ public class HorizontalVelocityChangeEvent extends Event implements Cancellable private boolean isCancelled; - private Entity entity; - private Player instigator; - private Vector from; - private Vector to; - private Vector difference; + private final Entity entity; + private final Player instigator; + private final Vector from; + private final Vector to; + private final Vector difference; private Location start; private Location end; private Ability abil; @Deprecated - public HorizontalVelocityChangeEvent(Entity entity, Player instigator, Vector from, Vector to, Vector difference) { + public HorizontalVelocityChangeEvent(final Entity entity, final Player instigator, final Vector from, final Vector to, final Vector difference) { this.entity = entity; this.instigator = instigator; this.from = from; @@ -37,7 +37,7 @@ public HorizontalVelocityChangeEvent(Entity entity, Player instigator, Vector fr this.difference = difference; } - public HorizontalVelocityChangeEvent(Entity entity, Player instigator, Vector from, Vector to, Vector difference, Location start, Location end, Ability ability) { + public HorizontalVelocityChangeEvent(final Entity entity, final Player instigator, final Vector from, final Vector to, final Vector difference, final Location start, final Location end, final Ability ability) { this.entity = entity; this.instigator = instigator; this.from = from; @@ -45,46 +45,46 @@ public HorizontalVelocityChangeEvent(Entity entity, Player instigator, Vector fr this.difference = difference; this.start = start; this.end = end; - abil = ability; + this.abil = ability; } public Entity getEntity() { - return entity; + return this.entity; } public Player getInstigator() { - return instigator; + return this.instigator; } public Vector getFrom() { - return from; + return this.from; } public Vector getTo() { - return to; + return this.to; } public Location getStartPoint() { - return start; + return this.start; } public Location getEndPoint() { - return end; + return this.end; } public double getDistanceTraveled() { - if (!start.getWorld().equals(end.getWorld())) { + if (!this.start.getWorld().equals(this.end.getWorld())) { return 0; } - return start.distance(end); + return this.start.distance(this.end); } public Vector getDifference() { - return difference; + return this.difference; } public Ability getAbility() { - return abil; + return this.abil; } @Override @@ -98,11 +98,11 @@ public static HandlerList getHandlerList() { @Override public boolean isCancelled() { - return isCancelled; + return this.isCancelled; } @Override - public void setCancelled(boolean value) { + public void setCancelled(final boolean value) { this.isCancelled = value; } } diff --git a/src/com/projectkorra/projectkorra/event/PlayerChangeElementEvent.java b/src/com/projectkorra/projectkorra/event/PlayerChangeElementEvent.java index 6144eac6d..b898fb8e9 100644 --- a/src/com/projectkorra/projectkorra/event/PlayerChangeElementEvent.java +++ b/src/com/projectkorra/projectkorra/event/PlayerChangeElementEvent.java @@ -1,38 +1,39 @@ package com.projectkorra.projectkorra.event; -import com.projectkorra.projectkorra.Element; - import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import com.projectkorra.projectkorra.Element; + /** * Called when a player's bending element is modified */ public class PlayerChangeElementEvent extends Event { private static final HandlerList handlers = new HandlerList(); - private CommandSender sender; - private Player target; - private Element element; - private Result result; + private final CommandSender sender; + private final Player target; + private final Element element; + private final Result result; /** - * + * * @param sender the {@link CommandSender} who changed the player's bending * @param target the {@link Player player} who's bending was changed * @param element the {@link Element element} that was affected * @param result whether the element was chosen, added, removed, or * permaremoved */ - public PlayerChangeElementEvent(CommandSender sender, Player target, Element element, Result result) { + public PlayerChangeElementEvent(final CommandSender sender, final Player target, final Element element, final Result result) { this.sender = sender; this.target = target; this.element = element; this.result = result; } + @Override public HandlerList getHandlers() { return handlers; } @@ -42,35 +43,35 @@ public static HandlerList getHandlerList() { } /** - * + * * @return the {@link CommandSender} who changed the player's bending */ public CommandSender getSender() { - return sender; + return this.sender; } /** - * + * * @return the {@link Player player} who's bending was changed */ public Player getTarget() { - return target; + return this.target; } /** - * + * * @return the {@link Element element} that was affected */ public Element getElement() { - return element; + return this.element; } /** - * + * * @return whether the element was chosen, added, removed, or permaremoved */ public Result getResult() { - return result; + return this.result; } public static enum Result { diff --git a/src/com/projectkorra/projectkorra/event/PlayerChangeSubElementEvent.java b/src/com/projectkorra/projectkorra/event/PlayerChangeSubElementEvent.java index d0bffca53..9dc656a8c 100644 --- a/src/com/projectkorra/projectkorra/event/PlayerChangeSubElementEvent.java +++ b/src/com/projectkorra/projectkorra/event/PlayerChangeSubElementEvent.java @@ -1,36 +1,37 @@ package com.projectkorra.projectkorra.event; -import com.projectkorra.projectkorra.Element; -import com.projectkorra.projectkorra.Element.SubElement; - import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.Element.SubElement; + public class PlayerChangeSubElementEvent extends Event { private static final HandlerList handlers = new HandlerList(); - private CommandSender sender; - private Player target; - private SubElement sub; - private Result result; + private final CommandSender sender; + private final Player target; + private final SubElement sub; + private final Result result; /** - * + * * @param sender the {@link CommandSender} who changed the player's bending * @param target the {@link Player} who's bending was changed * @param sub the {@link SubElement} that was changed to * @param result whether the element was chosen, added, removed, or * permaremoved */ - public PlayerChangeSubElementEvent(CommandSender sender, Player target, SubElement sub, Result result) { + public PlayerChangeSubElementEvent(final CommandSender sender, final Player target, final SubElement sub, final Result result) { this.sender = sender; this.target = target; this.sub = sub; this.result = result; } + @Override public HandlerList getHandlers() { return handlers; } @@ -40,35 +41,35 @@ public static HandlerList getHandlerList() { } /** - * + * * @return the {@link CommandSender} who changed the player's bending */ public CommandSender getSender() { - return sender; + return this.sender; } /** - * + * * @return the {@link Player player} who's bending was changed */ public Player getTarget() { - return target; + return this.target; } /** - * + * * @return the {@link Element element} that was affected */ public SubElement getSubElement() { - return sub; + return this.sub; } /** - * + * * @return whether the element was chosen, added, removed, or permaremoved */ public Result getResult() { - return result; + return this.result; } public static enum Result { diff --git a/src/com/projectkorra/projectkorra/event/PlayerCooldownChangeEvent.java b/src/com/projectkorra/projectkorra/event/PlayerCooldownChangeEvent.java index 026e60ce0..2a64c6d7e 100644 --- a/src/com/projectkorra/projectkorra/event/PlayerCooldownChangeEvent.java +++ b/src/com/projectkorra/projectkorra/event/PlayerCooldownChangeEvent.java @@ -13,13 +13,13 @@ public static enum Result { private static final HandlerList HANDLERS = new HandlerList(); - private Player player; - private String ability; - private Result eventresult; + private final Player player; + private final String ability; + private final Result eventresult; private boolean cancelled; private long cooldown; - public PlayerCooldownChangeEvent(Player player, String abilityname, long cooldown, Result result) { + public PlayerCooldownChangeEvent(final Player player, final String abilityname, final long cooldown, final Result result) { this.player = player; this.ability = abilityname; this.eventresult = result; @@ -28,33 +28,36 @@ public PlayerCooldownChangeEvent(Player player, String abilityname, long cooldow } public Player getPlayer() { - return player; + return this.player; } public String getAbility() { - return ability; + return this.ability; } public Result getResult() { - return eventresult; + return this.eventresult; } public long getCooldown() { - return cooldown; + return this.cooldown; } + @Override public boolean isCancelled() { - return cancelled; + return this.cancelled; } - public void setCancelled(boolean cancel) { + @Override + public void setCancelled(final boolean cancel) { this.cancelled = cancel; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } + @Override public HandlerList getHandlers() { return HANDLERS; } diff --git a/src/com/projectkorra/projectkorra/event/PlayerJumpEvent.java b/src/com/projectkorra/projectkorra/event/PlayerJumpEvent.java index e0bed633b..d8316113c 100644 --- a/src/com/projectkorra/projectkorra/event/PlayerJumpEvent.java +++ b/src/com/projectkorra/projectkorra/event/PlayerJumpEvent.java @@ -8,25 +8,24 @@ public class PlayerJumpEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); - private Player player; - private double height; + private final Player player; + private final double height; - public PlayerJumpEvent(Player player, double height) { + public PlayerJumpEvent(final Player player, final double height) { this.player = player; this.height = height; } public Player getPlayer() { - return player; + return this.player; } public double getHeight() { - return height; + return this.height; } @Override public HandlerList getHandlers() { - // TODO Auto-generated method stub return HANDLERS; } diff --git a/src/com/projectkorra/projectkorra/firebending/Blaze.java b/src/com/projectkorra/projectkorra/firebending/Blaze.java index ccb8ff492..3bd1933ad 100644 --- a/src/com/projectkorra/projectkorra/firebending/Blaze.java +++ b/src/com/projectkorra/projectkorra/firebending/Blaze.java @@ -1,12 +1,12 @@ package com.projectkorra.projectkorra.firebending; -import com.projectkorra.projectkorra.ability.FireAbility; -import com.projectkorra.projectkorra.avatar.AvatarState; - import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.avatar.AvatarState; + public class Blaze extends FireAbility { private int arc; @@ -14,7 +14,7 @@ public class Blaze extends FireAbility { private double range; private double speed; - public Blaze(Player player) { + public Blaze(final Player player) { super(player); this.speed = 2; @@ -22,18 +22,18 @@ public Blaze(Player player) { this.arc = getConfig().getInt("Abilities.Fire.Blaze.Arc"); this.range = getConfig().getDouble("Abilities.Fire.Blaze.Range"); - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("BlazeArc")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("BlazeArc")) { return; } - this.range = getDayFactor(range); - this.range = AvatarState.getValue(range, player); - this.arc = (int) getDayFactor(arc); - Location location = player.getLocation(); + this.range = this.getDayFactor(this.range); + this.range = AvatarState.getValue(this.range, player); + this.arc = (int) this.getDayFactor(this.arc); + final Location location = player.getLocation(); - for (int i = -arc; i <= arc; i += speed) { - double angle = Math.toRadians(i); - Vector direction = player.getEyeLocation().getDirection().clone(); + for (int i = -this.arc; i <= this.arc; i += this.speed) { + final double angle = Math.toRadians(i); + final Vector direction = player.getEyeLocation().getDirection().clone(); double x, z, vx, vz; x = direction.getX(); @@ -45,12 +45,12 @@ public Blaze(Player player) { direction.setX(vx); direction.setZ(vz); - new BlazeArc(player, location, direction, range); + new BlazeArc(player, location, direction, this.range); } - start(); - bPlayer.addCooldown("BlazeArc", cooldown); - remove(); + this.start(); + this.bPlayer.addCooldown("BlazeArc", this.cooldown); + this.remove(); } @Override @@ -64,12 +64,12 @@ public void progress() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override diff --git a/src/com/projectkorra/projectkorra/firebending/BlazeArc.java b/src/com/projectkorra/projectkorra/firebending/BlazeArc.java index 994c38a1c..996b5977b 100644 --- a/src/com/projectkorra/projectkorra/firebending/BlazeArc.java +++ b/src/com/projectkorra/projectkorra/firebending/BlazeArc.java @@ -1,8 +1,8 @@ package com.projectkorra.projectkorra.firebending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.FireAbility; -import com.projectkorra.projectkorra.waterbending.plant.PlantRegrowth; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -12,9 +12,9 @@ import org.bukkit.material.MaterialData; import org.bukkit.util.Vector; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.waterbending.plant.PlantRegrowth; public class BlazeArc extends FireAbility { @@ -32,13 +32,13 @@ public class BlazeArc extends FireAbility { private Location location; private Vector direction; - public BlazeArc(Player player, Location location, Vector direction, double range) { + public BlazeArc(final Player player, final Location location, final Vector direction, final double range) { super(player); - this.range = getDayFactor(range); + this.range = this.getDayFactor(range); this.speed = getConfig().getLong("Abilities.Fire.Blaze.Speed"); - this.interval = (long) (1000. / speed); + this.interval = (long) (1000. / this.speed); this.origin = location.clone(); - this.location = origin.clone(); + this.location = this.origin.clone(); this.direction = direction.clone(); this.direction.setY(0); @@ -46,14 +46,14 @@ public BlazeArc(Player player, Location location, Vector direction, double range this.location = this.location.clone().add(this.direction); this.time = System.currentTimeMillis(); - start(); + this.start(); } - private void ignite(Block block) { + private void ignite(final Block block) { if (block.getType() != Material.FIRE && block.getType() != Material.AIR) { if (canFireGrief()) { if (isPlant(block) || isSnow(block)) { - new PlantRegrowth(player, block); + new PlantRegrowth(this.player, block); } } else if (block.getType() != Material.FIRE) { REPLACED_BLOCKS.put(block.getLocation(), block.getState().getData()); @@ -67,35 +67,35 @@ private void ignite(Block block) { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; - } else if (System.currentTimeMillis() - time >= interval) { - location = location.clone().add(direction); - time = System.currentTimeMillis(); + } else if (System.currentTimeMillis() - this.time >= this.interval) { + this.location = this.location.clone().add(this.direction); + this.time = System.currentTimeMillis(); - Block block = location.getBlock(); + final Block block = this.location.getBlock(); if (block.getType() == Material.FIRE) { return; } - if (location.distanceSquared(origin) > range * range) { - remove(); + if (this.location.distanceSquared(this.origin) > this.range * this.range) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { return; } - if (isIgnitable(player, block)) { - ignite(block); - } else if (isIgnitable(player, block.getRelative(BlockFace.DOWN))) { - ignite(block.getRelative(BlockFace.DOWN)); - location = block.getRelative(BlockFace.DOWN).getLocation(); - } else if (isIgnitable(player, block.getRelative(BlockFace.UP))) { - ignite(block.getRelative(BlockFace.UP)); - location = block.getRelative(BlockFace.UP).getLocation(); + if (isIgnitable(this.player, block)) { + this.ignite(block); + } else if (isIgnitable(this.player, block.getRelative(BlockFace.DOWN))) { + this.ignite(block.getRelative(BlockFace.DOWN)); + this.location = block.getRelative(BlockFace.DOWN).getLocation(); + } else if (isIgnitable(this.player, block.getRelative(BlockFace.UP))) { + this.ignite(block.getRelative(BlockFace.UP)); + this.location = block.getRelative(BlockFace.UP).getLocation(); } else { - remove(); + this.remove(); return; } } @@ -103,11 +103,11 @@ public void progress() { public static void dissipateAll() { if (DISSIPATE_REMOVE_TIME != 0) { - for (Block block : IGNITED_TIMES.keySet()) { + for (final Block block : IGNITED_TIMES.keySet()) { if (block.getType() != Material.FIRE) { removeBlock(block); } else { - long time = IGNITED_TIMES.get(block); + final long time = IGNITED_TIMES.get(block); if (System.currentTimeMillis() > time + DISSIPATE_REMOVE_TIME) { block.setType(Material.AIR); removeBlock(block); @@ -118,14 +118,14 @@ public static void dissipateAll() { } public static void handleDissipation() { - for (Block block : IGNITED_BLOCKS.keySet()) { + for (final Block block : IGNITED_BLOCKS.keySet()) { if (block.getType() != Material.FIRE) { IGNITED_BLOCKS.remove(block); } } } - public static boolean isIgnitable(Player player, Block block) { + public static boolean isIgnitable(final Player player, final Block block) { if (block.getType() == Material.FIRE) { return true; } else if (Arrays.asList(OVERWRITABLE_MATERIALS).contains(block.getType())) { @@ -134,18 +134,18 @@ public static boolean isIgnitable(Player player, Block block) { return false; } - Block belowBlock = block.getRelative(BlockFace.DOWN); + final Block belowBlock = block.getRelative(BlockFace.DOWN); return isIgnitable(belowBlock); } public static void removeAllCleanup() { - for (Block block : IGNITED_BLOCKS.keySet()) { + for (final Block block : IGNITED_BLOCKS.keySet()) { removeBlock(block); } } - public static void removeAroundPoint(Location location, double radius) { - for (BlazeArc stream : getAbilities(BlazeArc.class)) { + public static void removeAroundPoint(final Location location, final double radius) { + for (final BlazeArc stream : getAbilities(BlazeArc.class)) { if (stream.location.getWorld().equals(location.getWorld())) { if (stream.location.distanceSquared(location) <= radius * radius) { stream.remove(); @@ -154,8 +154,7 @@ public static void removeAroundPoint(Location location, double radius) { } } - @SuppressWarnings("deprecation") - public static void removeBlock(Block block) { + public static void removeBlock(final Block block) { if (IGNITED_BLOCKS.containsKey(block)) { IGNITED_BLOCKS.remove(block); } @@ -176,10 +175,10 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; + if (this.location != null) { + return this.location; } - return origin; + return this.origin; } @Override @@ -198,50 +197,50 @@ public boolean isHarmlessAbility() { } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } @@ -265,7 +264,7 @@ public static Map getReplacedBlocks() { return REPLACED_BLOCKS; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/firebending/BlazeRing.java b/src/com/projectkorra/projectkorra/firebending/BlazeRing.java index d34d465c4..b4f5c859a 100644 --- a/src/com/projectkorra/projectkorra/firebending/BlazeRing.java +++ b/src/com/projectkorra/projectkorra/firebending/BlazeRing.java @@ -13,7 +13,7 @@ public class BlazeRing extends FireAbility { private double angleIncrement; private Location location; - public BlazeRing(Player player) { + public BlazeRing(final Player player) { super(player); this.range = getConfig().getInt("Abilities.Fire.Blaze.Ring.Range"); @@ -21,16 +21,16 @@ public BlazeRing(Player player) { this.cooldown = getConfig().getLong("Abilities.Fire.Blaze.Ring.Cooldown"); this.location = player.getLocation(); - if (bPlayer.isAvatarState()) { - range = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.Blaze.Ring.Range"); + if (this.bPlayer.isAvatarState()) { + this.range = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.Blaze.Ring.Range"); } - if (!bPlayer.canBend(this) || bPlayer.isOnCooldown("BlazeRing")) { + if (!this.bPlayer.canBend(this) || this.bPlayer.isOnCooldown("BlazeRing")) { return; } - for (double degrees = 0; degrees < 360; degrees += angleIncrement) { - double angle = Math.toRadians(degrees); - Vector direction = player.getEyeLocation().getDirection().clone(); + for (double degrees = 0; degrees < 360; degrees += this.angleIncrement) { + final double angle = Math.toRadians(degrees); + final Vector direction = player.getEyeLocation().getDirection().clone(); double x, z, vx, vz; x = direction.getX(); @@ -42,12 +42,12 @@ public BlazeRing(Player player) { direction.setX(vx); direction.setZ(vz); - new BlazeArc(player, location, direction, range); + new BlazeArc(player, this.location, direction, this.range); } - start(); - bPlayer.addCooldown("BlazeRing", cooldown); - remove(); + this.start(); + this.bPlayer.addCooldown("BlazeRing", this.cooldown); + this.remove(); } @Override @@ -61,12 +61,12 @@ public void progress() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -80,26 +80,26 @@ public boolean isHarmlessAbility() { } public int getRange() { - return range; + return this.range; } - public void setRange(int range) { + public void setRange(final int range) { this.range = range; } public double getAngleIncrement() { - return angleIncrement; + return this.angleIncrement; } - public void setAngleIncrement(double angleIncrement) { + public void setAngleIncrement(final double angleIncrement) { this.angleIncrement = angleIncrement; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireBlast.java b/src/com/projectkorra/projectkorra/firebending/FireBlast.java index 474bbb128..e73c1f712 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireBlast.java +++ b/src/com/projectkorra/projectkorra/firebending/FireBlast.java @@ -49,47 +49,47 @@ public class FireBlast extends FireAbility { private Vector direction; private List safeBlocks; - public FireBlast(Location location, Vector direction, Player player, int damage, List safeBlocks) { + public FireBlast(final Location location, final Vector direction, final Player player, final int damage, final List safeBlocks) { super(player); if (location.getBlock().isLiquid()) { return; } - setFields(); + this.setFields(); this.safeBlocks = safeBlocks; this.damage = damage; this.location = location.clone(); this.origin = location.clone(); this.direction = direction.clone().normalize(); - this.range = getDayFactor(range); - this.damage = getDayFactor(damage); + this.range = this.getDayFactor(this.range); + this.damage = this.getDayFactor(damage); - start(); + this.start(); } - public FireBlast(Player player) { + public FireBlast(final Player player) { super(player); - if (bPlayer.isOnCooldown("FireBlast")) { + if (this.bPlayer.isOnCooldown("FireBlast")) { return; } else if (player.getEyeLocation().getBlock().isLiquid() || FireBlastCharged.isCharging(player)) { return; } - setFields(); + this.setFields(); this.isFireBurst = false; - this.damage = getDayFactor(getConfig().getDouble("Abilities.Fire.FireBlast.Damage")); + this.damage = this.getDayFactor(getConfig().getDouble("Abilities.Fire.FireBlast.Damage")); this.safeBlocks = new ArrayList<>(); - this.range = getDayFactor(this.range); + this.range = this.getDayFactor(this.range); this.location = player.getEyeLocation(); this.origin = player.getEyeLocation(); this.direction = player.getEyeLocation().getDirection().normalize(); - this.location = location.add(direction.clone()); + this.location = this.location.add(this.direction.clone()); - start(); - bPlayer.addCooldown("FireBlast", cooldown); + this.start(); + this.bPlayer.addCooldown("FireBlast", this.cooldown); } private void setFields() { @@ -108,47 +108,51 @@ private void setFields() { } private void advanceLocation() { - if (showParticles) { - ParticleEffect.FLAME.display(location, 0.275F, 0.275F, 0.275F, 0, 6); - ParticleEffect.SMOKE.display(location, 0.3F, 0.3F, 0.3F, 0, 3); + if (this.showParticles) { + ParticleEffect.FLAME.display(this.location, 0.275F, 0.275F, 0.275F, 0, 6); + ParticleEffect.SMOKE.display(this.location, 0.3F, 0.3F, 0.3F, 0, 3); } - location = location.add(direction.clone().multiply(speedFactor)); - if (random.nextInt(4) == 0) { - playFirebendingSound(location); + if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { + this.remove(); + return; + } + this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); + if (this.random.nextInt(4) == 0) { + playFirebendingSound(this.location); } } - private void affect(Entity entity) { - if (entity.getUniqueId() != player.getUniqueId()) { - if (bPlayer.isAvatarState()) { - GeneralMethods.setVelocity(entity, direction.clone().multiply(AvatarState.getValue(pushFactor))); + private void affect(final Entity entity) { + if (entity.getUniqueId() != this.player.getUniqueId()) { + if (this.bPlayer.isAvatarState()) { + GeneralMethods.setVelocity(entity, this.direction.clone().multiply(AvatarState.getValue(this.pushFactor))); } else { - GeneralMethods.setVelocity(entity, direction.clone().multiply(pushFactor)); + GeneralMethods.setVelocity(entity, this.direction.clone().multiply(this.pushFactor)); } if (entity instanceof LivingEntity) { - entity.setFireTicks((int) (fireTicks * 20)); - DamageHandler.damageEntity(entity, damage, this); + entity.setFireTicks((int) (this.fireTicks * 20)); + DamageHandler.damageEntity(entity, this.damage, this); AirAbility.breakBreathbendingHold(entity); - new FireDamageTimer(entity, player); - remove(); + new FireDamageTimer(entity, this.player); + this.remove(); } } } - private void ignite(Location location) { - for (Block block : GeneralMethods.getBlocksAroundPoint(location, collisionRadius)) { - if (BlazeArc.isIgnitable(player, block) && !safeBlocks.contains(block) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { + private void ignite(final Location location) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(location, this.collisionRadius)) { + if (BlazeArc.isIgnitable(this.player, block) && !this.safeBlocks.contains(block) && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { if (canFireGrief()) { if (isPlant(block) || isSnow(block)) { - new PlantRegrowth(player, block); + new PlantRegrowth(this.player, block); } block.setType(Material.FIRE); } else { createTempFire(block.getLocation()); } - if (dissipate) { - BlazeArc.getIgnitedBlocks().put(block, player); + if (this.dissipate) { + BlazeArc.getIgnitedBlocks().put(block, this.player); BlazeArc.getIgnitedTimes().put(block, System.currentTimeMillis()); } } @@ -157,48 +161,48 @@ private void ignite(Location location) { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this) || GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this) || GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } - speedFactor = speed * (ProjectKorra.time_step / 1000.0); - ticks++; + this.speedFactor = this.speed * (ProjectKorra.time_step / 1000.0); + this.ticks++; - if (ticks > MAX_TICKS) { - remove(); + if (this.ticks > MAX_TICKS) { + this.remove(); return; } - Block block = location.getBlock(); + final Block block = this.location.getBlock(); if (GeneralMethods.isSolid(block) || block.isLiquid()) { - if (block.getType() == Material.FURNACE && powerFurnace) { - Furnace furnace = (Furnace) block.getState(); + if (block.getType() == Material.FURNACE && this.powerFurnace) { + final Furnace furnace = (Furnace) block.getState(); furnace.setBurnTime((short) 800); furnace.setCookTime((short) 800); furnace.update(); - } else if (BlazeArc.isIgnitable(player, block.getRelative(BlockFace.UP))) { - if ((isFireBurst && fireBurstIgnite) || !isFireBurst) { - ignite(location); + } else if (BlazeArc.isIgnitable(this.player, block.getRelative(BlockFace.UP))) { + if ((this.isFireBurst && this.fireBurstIgnite) || !this.isFireBurst) { + this.ignite(this.location); } } - remove(); + this.remove(); return; } - if (location.distanceSquared(origin) > range * range) { - remove(); + if (this.location.distanceSquared(this.origin) > this.range * this.range) { + this.remove(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { - affect(entity); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { + this.affect(entity); if (entity instanceof LivingEntity) { break; } } - advanceLocation(); + this.advanceLocation(); } /** @@ -206,10 +210,10 @@ public void progress() { * {@link Collision} for the new system. */ @Deprecated - public static boolean annihilateBlasts(Location location, double radius, Player source) { + public static boolean annihilateBlasts(final Location location, final double radius, final Player source) { boolean broke = false; - for (FireBlast blast : getAbilities(FireBlast.class)) { - Location fireBlastLocation = blast.location; + for (final FireBlast blast : getAbilities(FireBlast.class)) { + final Location fireBlastLocation = blast.location; if (location.getWorld().equals(fireBlastLocation.getWorld()) && !blast.player.equals(source)) { if (location.distanceSquared(fireBlastLocation) <= radius * radius) { blast.remove(); @@ -223,10 +227,10 @@ public static boolean annihilateBlasts(Location location, double radius, Player return broke; } - public static ArrayList getAroundPoint(Location location, double radius) { - ArrayList list = new ArrayList(); - for (FireBlast fireBlast : getAbilities(FireBlast.class)) { - Location fireblastlocation = fireBlast.location; + public static ArrayList getAroundPoint(final Location location, final double radius) { + final ArrayList list = new ArrayList(); + for (final FireBlast fireBlast : getAbilities(FireBlast.class)) { + final Location fireblastlocation = fireBlast.location; if (location.getWorld().equals(fireblastlocation.getWorld())) { if (location.distanceSquared(fireblastlocation) <= radius * radius) { list.add(fireBlast); @@ -236,9 +240,9 @@ public static ArrayList getAroundPoint(Location location, double radi return list; } - public static void removeFireBlastsAroundPoint(Location location, double radius) { - for (FireBlast fireBlast : getAbilities(FireBlast.class)) { - Location fireBlastLocation = fireBlast.location; + public static void removeFireBlastsAroundPoint(final Location location, final double radius) { + for (final FireBlast fireBlast : getAbilities(FireBlast.class)) { + final Location fireBlastLocation = fireBlast.location; if (location.getWorld().equals(fireBlastLocation.getWorld())) { if (location.distanceSquared(fireBlastLocation) <= radius * radius) { fireBlast.remove(); @@ -250,17 +254,17 @@ public static void removeFireBlastsAroundPoint(Location location, double radius) @Override public String getName() { - return isFireBurst ? "FireBurst" : "FireBlast"; + return this.isFireBurst ? "FireBurst" : "FireBlast"; } @Override public Location getLocation() { - return location != null ? location : origin; + return this.location != null ? this.location : this.origin; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -275,114 +279,114 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } public boolean isPowerFurnace() { - return powerFurnace; + return this.powerFurnace; } - public void setPowerFurnace(boolean powerFurnace) { + public void setPowerFurnace(final boolean powerFurnace) { this.powerFurnace = powerFurnace; } public boolean isShowParticles() { - return showParticles; + return this.showParticles; } - public void setShowParticles(boolean showParticles) { + public void setShowParticles(final boolean showParticles) { this.showParticles = showParticles; } public boolean isDissipate() { - return dissipate; + return this.dissipate; } - public void setDissipate(boolean dissipate) { + public void setDissipate(final boolean dissipate) { this.dissipate = dissipate; } public int getTicks() { - return ticks; + return this.ticks; } - public void setTicks(int ticks) { + public void setTicks(final int ticks) { this.ticks = ticks; } public double getSpeedFactor() { - return speedFactor; + return this.speedFactor; } - public void setSpeedFactor(double speedFactor) { + public void setSpeedFactor(final double speedFactor) { this.speedFactor = speedFactor; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } public double getFireTicks() { - return fireTicks; + return this.fireTicks; } - public void setFireTicks(double fireTicks) { + public void setFireTicks(final double fireTicks) { this.fireTicks = fireTicks; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public Random getRandom() { - return random; + return this.random; } - public void setRandom(Random random) { + public void setRandom(final Random random) { this.random = random; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } @@ -391,22 +395,22 @@ public static int getMaxTicks() { } public List getSafeBlocks() { - return safeBlocks; + return this.safeBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public boolean isFireBurst() { - return isFireBurst; + return this.isFireBurst; } - public void setFireBurst(boolean isFireBurst) { + public void setFireBurst(final boolean isFireBurst) { this.isFireBurst = isFireBurst; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java b/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java index ef7924d3b..eafa6d54b 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java +++ b/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java @@ -1,12 +1,9 @@ package com.projectkorra.projectkorra.firebending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.ability.FireAbility; -import com.projectkorra.projectkorra.avatar.AvatarState; -import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.ParticleEffect; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Effect; import org.bukkit.Location; @@ -19,10 +16,13 @@ import org.bukkit.entity.TNTPrimed; import org.bukkit.util.Vector; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.avatar.AvatarState; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.ParticleEffect; public class FireBlastCharged extends FireAbility { @@ -47,10 +47,10 @@ public class FireBlastCharged extends FireAbility { private Location location; private Vector direction; - public FireBlastCharged(Player player) { + public FireBlastCharged(final Player player) { super(player); - if (!bPlayer.canBend(this) || hasAbility(player, FireBlastCharged.class)) { + if (!this.bPlayer.canBend(this) || hasAbility(player, FireBlastCharged.class)) { return; } @@ -67,31 +67,31 @@ public FireBlastCharged(Player player) { this.damageRadius = getConfig().getDouble("Abilities.Fire.FireBlast.Charged.DamageRadius"); this.explosionRadius = getConfig().getDouble("Abilities.Fire.FireBlast.Charged.ExplosionRadius"); this.fireTicks = getConfig().getDouble("Abilities.Fire.FireBlast.Charged.FireTicks"); - this.innerRadius = damageRadius / 2; + this.innerRadius = this.damageRadius / 2; if (isDay(player.getWorld())) { - this.chargeTime = (long) (chargeTime / getDayFactor()); - this.maxDamage = getDayFactor(maxDamage); - this.range = getDayFactor(range); + this.chargeTime = (long) (this.chargeTime / getDayFactor()); + this.maxDamage = this.getDayFactor(this.maxDamage); + this.range = this.getDayFactor(this.range); } - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.FireBlast.Charged.ChargeTime"); this.maxDamage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireBlast.Charged.Damage"); } if (!player.getEyeLocation().getBlock().isLiquid()) { - start(); + this.start(); } } - public static boolean annihilateBlasts(Location location, double radius, Player source) { + public static boolean annihilateBlasts(final Location location, final double radius, final Player source) { boolean broke = false; - for (FireBlastCharged chargedBlast : getAbilities(FireBlastCharged.class)) { + for (final FireBlastCharged chargedBlast : getAbilities(FireBlastCharged.class)) { if (!chargedBlast.launched) { continue; } - Location fireBlastLocation = chargedBlast.location; + final Location fireBlastLocation = chargedBlast.location; if (location.getWorld().equals(fireBlastLocation.getWorld()) && !source.equals(chargedBlast.player)) { if (location.distanceSquared(fireBlastLocation) <= radius * radius) { chargedBlast.explode(); @@ -102,12 +102,12 @@ public static boolean annihilateBlasts(Location location, double radius, Player return broke; } - public static FireBlastCharged getFireball(Entity entity) { + public static FireBlastCharged getFireball(final Entity entity) { return entity != null ? EXPLOSIONS.get(entity) : null; } - public static boolean isCharging(Player player) { - for (FireBlastCharged chargedBlast : getAbilities(player, FireBlastCharged.class)) { + public static boolean isCharging(final Player player) { + for (final FireBlastCharged chargedBlast : getAbilities(player, FireBlastCharged.class)) { if (!chargedBlast.launched) { return true; } @@ -115,12 +115,12 @@ public static boolean isCharging(Player player) { return false; } - public static void removeFireballsAroundPoint(Location location, double radius) { - for (FireBlastCharged fireball : getAbilities(FireBlastCharged.class)) { + public static void removeFireballsAroundPoint(final Location location, final double radius) { + for (final FireBlastCharged fireball : getAbilities(FireBlastCharged.class)) { if (!fireball.launched) { continue; } - Location fireblastlocation = fireball.location; + final Location fireblastlocation = fireball.location; if (location.getWorld().equals(fireblastlocation.getWorld())) { if (location.distanceSquared(fireblastlocation) <= radius * radius) { fireball.remove(); @@ -129,31 +129,31 @@ public static void removeFireballsAroundPoint(Location location, double radius) } } - public void dealDamage(Entity entity) { - if (explosion == null) { + public void dealDamage(final Entity entity) { + if (this.explosion == null) { return; } double distance = 0; - if (entity.getWorld().equals(explosion.getWorld())) { - distance = entity.getLocation().distance(explosion.getLocation()); + if (entity.getWorld().equals(this.explosion.getWorld())) { + distance = entity.getLocation().distance(this.explosion.getLocation()); } - if (distance > damageRadius) { + if (distance > this.damageRadius) { return; - } else if (distance < innerRadius) { - DamageHandler.damageEntity(entity, maxDamage, this); + } else if (distance < this.innerRadius) { + DamageHandler.damageEntity(entity, this.maxDamage, this); return; } - double slope = -(maxDamage * .5) / (damageRadius - innerRadius); - double damage = slope * (distance - innerRadius) + maxDamage; + final double slope = -(this.maxDamage * .5) / (this.damageRadius - this.innerRadius); + final double damage = slope * (distance - this.innerRadius) + this.maxDamage; DamageHandler.damageEntity(entity, damage, this); AirAbility.breakBreathbendingHold(entity); } public void explode() { boolean explode = true; - for (Block block : GeneralMethods.getBlocksAroundPoint(location, 3)) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.location, 3)) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { explode = false; break; @@ -161,75 +161,75 @@ public void explode() { } if (explode) { - if (canDamageBlocks && explosionRadius > 0 && canFireGrief()) { - explosion = player.getWorld().spawn(location, TNTPrimed.class); - explosion.setFuseTicks(0); - double yield = explosionRadius; + if (this.canDamageBlocks && this.explosionRadius > 0 && canFireGrief()) { + this.explosion = this.player.getWorld().spawn(this.location, TNTPrimed.class); + this.explosion.setFuseTicks(0); + double yield = this.explosionRadius; - if (!bPlayer.isAvatarState()) { - yield = getDayFactor(yield, player.getWorld()); + if (!this.bPlayer.isAvatarState()) { + yield = getDayFactor(yield, this.player.getWorld()); } else { yield = AvatarState.getValue(yield); } - explosion.setYield((float) yield); - EXPLOSIONS.put(explosion, this); + this.explosion.setYield((float) yield); + EXPLOSIONS.put(this.explosion, this); } else { - List entities = GeneralMethods.getEntitiesAroundPoint(location, damageRadius); - for (Entity entity : entities) { + final List entities = GeneralMethods.getEntitiesAroundPoint(this.location, this.damageRadius); + for (final Entity entity : entities) { if (entity instanceof LivingEntity) { - double slope = -(maxDamage * .5) / (damageRadius - innerRadius); + final double slope = -(this.maxDamage * .5) / (this.damageRadius - this.innerRadius); double damage = 0; - if (entity.getWorld().equals(location.getWorld())) { - damage = slope * (entity.getLocation().distance(location) - innerRadius) + maxDamage; + if (entity.getWorld().equals(this.location.getWorld())) { + damage = slope * (entity.getLocation().distance(this.location) - this.innerRadius) + this.maxDamage; } DamageHandler.damageEntity(entity, damage, this); } } - location.getWorld().playSound(location, Sound.ENTITY_GENERIC_EXPLODE, 5, 1); - ParticleEffect.EXPLOSION_HUGE.display(new Vector(0, 0, 0), 0, location, 255.0D); + this.location.getWorld().playSound(this.location, Sound.ENTITY_GENERIC_EXPLODE, 5, 1); + ParticleEffect.EXPLOSION_HUGE.display(new Vector(0, 0, 0), 0, this.location, 255.0D); } } - ignite(location); - remove(); + this.ignite(this.location); + this.remove(); } private void executeFireball() { - for (Block block : GeneralMethods.getBlocksAroundPoint(location, collisionRadius)) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.location, this.collisionRadius)) { ParticleEffect.FLAME.display(block.getLocation(), 0.5F, 0.5F, 0.5F, 0, 5); ParticleEffect.SMOKE.display(block.getLocation(), 0.5F, 0.5F, 0.5F, 0, 2); if ((new Random()).nextInt(4) == 0) { - playFirebendingSound(location); + playFirebendingSound(this.location); } } boolean exploded = false; - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2 * collisionRadius)) { - if (entity.getEntityId() == player.getEntityId() || GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2 * this.collisionRadius)) { + if (entity.getEntityId() == this.player.getEntityId() || GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } - entity.setFireTicks((int) (fireTicks * 20)); + entity.setFireTicks((int) (this.fireTicks * 20)); if (entity instanceof LivingEntity) { if (!exploded) { - explode(); + this.explode(); exploded = true; } - dealDamage(entity); + this.dealDamage(entity); } } } - private void ignite(Location location) { - for (Block block : GeneralMethods.getBlocksAroundPoint(location, collisionRadius)) { - if (BlazeArc.isIgnitable(player, block)) { + private void ignite(final Location location) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(location, this.collisionRadius)) { + if (BlazeArc.isIgnitable(this.player, block)) { if (block.getType() != Material.FIRE) { BlazeArc.getReplacedBlocks().put(block.getLocation(), block.getState().getData()); } block.setType(Material.FIRE); - if (dissipate) { - BlazeArc.getIgnitedBlocks().put(block, player); + if (this.dissipate) { + BlazeArc.getIgnitedBlocks().put(block, this.player); BlazeArc.getIgnitedTimes().put(block, System.currentTimeMillis()); } } @@ -238,58 +238,62 @@ private void ignite(Location location) { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this) && !launched) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this) && !this.launched) { + this.remove(); return; - } else if (!bPlayer.canBend(CoreAbility.getAbility("FireBlast")) && !launched) { - remove(); + } else if (!this.bPlayer.canBend(CoreAbility.getAbility("FireBlast")) && !this.launched) { + this.remove(); return; - } else if (!player.isSneaking() && !charged) { - remove(); + } else if (!this.player.isSneaking() && !this.charged) { + this.remove(); return; } - if (System.currentTimeMillis() > getStartTime() + chargeTime) { - charged = true; + if (System.currentTimeMillis() > this.getStartTime() + this.chargeTime) { + this.charged = true; } - if (!player.isSneaking() && !launched) { - launched = true; - location = player.getEyeLocation(); - origin = location.clone(); - direction = location.getDirection().normalize().multiply(collisionRadius); + if (!this.player.isSneaking() && !this.launched) { + this.launched = true; + this.location = this.player.getEyeLocation(); + this.origin = this.location.clone(); + this.direction = this.location.getDirection().normalize().multiply(this.collisionRadius); } - if (System.currentTimeMillis() > time + interval) { - if (launched) { - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + if (System.currentTimeMillis() > this.time + this.interval) { + if (this.launched) { + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } } - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); - if (!launched && !charged) { + if (!this.launched && !this.charged) { return; - } else if (!launched) { - player.getWorld().playEffect(player.getEyeLocation(), Effect.MOBSPAWNER_FLAMES, 0, 3); + } else if (!this.launched) { + this.player.getWorld().playEffect(this.player.getEyeLocation(), Effect.MOBSPAWNER_FLAMES, 0, 3); return; } - location = location.clone().add(direction); - if (location.distanceSquared(origin) > range * range) { - remove(); + if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { + this.explode(); + return; + } + this.location = this.location.clone().add(this.direction); + if (this.location.distanceSquared(this.origin) > this.range * this.range) { + this.remove(); return; } - if (GeneralMethods.isSolid(location.getBlock())) { - explode(); + if (GeneralMethods.isSolid(this.location.getBlock())) { + this.explode(); return; - } else if (location.getBlock().isLiquid()) { - remove(); + } else if (this.location.getBlock().isLiquid()) { + this.remove(); return; } - executeFireball(); + this.executeFireball(); } } @@ -300,7 +304,7 @@ public String getName() { @Override public Location getLocation() { - return location != null ? location : origin; + return this.location != null ? this.location : this.origin; } @Override @@ -317,7 +321,7 @@ public boolean isSneakAbility() { public boolean isHarmlessAbility() { return false; } - + @Override public boolean isCollidable() { return this.launched; @@ -325,138 +329,138 @@ public boolean isCollidable() { @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } public boolean isCharged() { - return charged; + return this.charged; } - public void setCharged(boolean charged) { + public void setCharged(final boolean charged) { this.charged = charged; } public boolean isLaunched() { - return launched; + return this.launched; } - public void setLaunched(boolean launched) { + public void setLaunched(final boolean launched) { this.launched = launched; } public boolean isCanDamageBlocks() { - return canDamageBlocks; + return this.canDamageBlocks; } - public void setCanDamageBlocks(boolean canDamageBlocks) { + public void setCanDamageBlocks(final boolean canDamageBlocks) { this.canDamageBlocks = canDamageBlocks; } public boolean isDissipate() { - return dissipate; + return this.dissipate; } - public void setDissipate(boolean dissipate) { + public void setDissipate(final boolean dissipate) { this.dissipate = dissipate; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getMaxDamage() { - return maxDamage; + return this.maxDamage; } - public void setMaxDamage(double maxDamage) { + public void setMaxDamage(final double maxDamage) { this.maxDamage = maxDamage; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } public double getDamageRadius() { - return damageRadius; + return this.damageRadius; } - public void setDamageRadius(double damageRadius) { + public void setDamageRadius(final double damageRadius) { this.damageRadius = damageRadius; } public double getExplosionRadius() { - return explosionRadius; + return this.explosionRadius; } - public void setExplosionRadius(double explosionRadius) { + public void setExplosionRadius(final double explosionRadius) { this.explosionRadius = explosionRadius; } public double getInnerRadius() { - return innerRadius; + return this.innerRadius; } - public void setInnerRadius(double innerRadius) { + public void setInnerRadius(final double innerRadius) { this.innerRadius = innerRadius; } public double getFireTicks() { - return fireTicks; + return this.fireTicks; } - public void setFireTicks(double fireTicks) { + public void setFireTicks(final double fireTicks) { this.fireTicks = fireTicks; } public TNTPrimed getExplosion() { - return explosion; + return this.explosion; } - public void setExplosion(TNTPrimed explosion) { + public void setExplosion(final TNTPrimed explosion) { this.explosion = explosion; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } @@ -464,7 +468,7 @@ public static Map getExplosions() { return EXPLOSIONS; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireBurst.java b/src/com/projectkorra/projectkorra/firebending/FireBurst.java index e0095e9e6..fbe4a3573 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireBurst.java +++ b/src/com/projectkorra/projectkorra/firebending/FireBurst.java @@ -1,8 +1,7 @@ package com.projectkorra.projectkorra.firebending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.ability.FireAbility; +import java.util.ArrayList; +import java.util.List; import org.bukkit.Effect; import org.bukkit.Location; @@ -11,8 +10,9 @@ import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.List; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.FireAbility; public class FireBurst extends FireAbility { @@ -26,7 +26,7 @@ public class FireBurst extends FireAbility { private double particlesPercentage; private ArrayList blasts; - public FireBurst(Player player) { + public FireBurst(final Player player) { super(player); this.charged = false; @@ -39,59 +39,59 @@ public FireBurst(Player player) { this.particlesPercentage = getConfig().getDouble("Abilities.Fire.FireBurst.ParticlesPercentage"); this.blasts = new ArrayList<>(); - if (!bPlayer.canBend(this) || hasAbility(player, FireBurst.class)) { + if (!this.bPlayer.canBend(this) || hasAbility(player, FireBurst.class)) { return; } if (isDay(player.getWorld())) { - chargeTime /= getDayFactor(); + this.chargeTime /= getDayFactor(); } - if (bPlayer.isAvatarState() || isSozinsComet(player.getWorld())) { - chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.FireBurst.Damage"); - damage = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.FireBurst.Damage"); - cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.FireBurst.Cooldown"); + if (this.bPlayer.isAvatarState() || isSozinsComet(player.getWorld())) { + this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.FireBurst.Damage"); + this.damage = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.FireBurst.Damage"); + this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.FireBurst.Cooldown"); } - start(); + this.start(); } - public static void coneBurst(Player player) { - FireBurst burst = getAbility(player, FireBurst.class); + public static void coneBurst(final Player player) { + final FireBurst burst = getAbility(player, FireBurst.class); if (burst != null) { burst.coneBurst(); } } private void coneBurst() { - if (charged) { - Location location = player.getEyeLocation(); - List safeBlocks = GeneralMethods.getBlocksAroundPoint(player.getLocation(), 2); - Vector vector = location.getDirection(); + if (this.charged) { + final Location location = this.player.getEyeLocation(); + final List safeBlocks = GeneralMethods.getBlocksAroundPoint(this.player.getLocation(), 2); + final Vector vector = location.getDirection(); - double angle = Math.toRadians(30); + final double angle = Math.toRadians(30); double x, y, z; - double r = 1; + final double r = 1; - for (double theta = 0; theta <= 180; theta += angleTheta) { - double dphi = anglePhi / Math.sin(Math.toRadians(theta)); + for (double theta = 0; theta <= 180; theta += this.angleTheta) { + final double dphi = this.anglePhi / Math.sin(Math.toRadians(theta)); for (double phi = 0; phi < 360; phi += dphi) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); x = r * Math.cos(rphi) * Math.sin(rtheta); y = r * Math.sin(rphi) * Math.sin(rtheta); z = r * Math.cos(rtheta); - Vector direction = new Vector(x, z, y); + final Vector direction = new Vector(x, z, y); if (direction.angle(vector) <= angle) { - FireBlast fblast = new FireBlast(location, direction.normalize(), player, damage, safeBlocks); + final FireBlast fblast = new FireBlast(location, direction.normalize(), this.player, this.damage, safeBlocks); fblast.setRange(this.range); } } } - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } - remove(); + this.remove(); } /** @@ -100,9 +100,9 @@ private void coneBurst() { * spread out then we can show more at a time. */ public void handleSmoothParticles() { - for (int i = 0; i < blasts.size(); i++) { - final FireBlast fblast = blasts.get(i); - int toggleTime = (int) (i % (100.0 / particlesPercentage)); + for (int i = 0; i < this.blasts.size(); i++) { + final FireBlast fblast = this.blasts.get(i); + final int toggleTime = (int) (i % (100.0 / this.particlesPercentage)); new BukkitRunnable() { @Override public void run() { @@ -114,56 +114,56 @@ public void run() { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() > getStartTime() + chargeTime && !charged) { - charged = true; + if (System.currentTimeMillis() > this.getStartTime() + this.chargeTime && !this.charged) { + this.charged = true; } - if (!player.isSneaking()) { - if (charged) { - sphereBurst(); + if (!this.player.isSneaking()) { + if (this.charged) { + this.sphereBurst(); } else { - remove(); + this.remove(); } - } else if (charged) { - Location location = player.getEyeLocation(); + } else if (this.charged) { + final Location location = this.player.getEyeLocation(); location.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, 4, 3); } } private void sphereBurst() { - if (charged) { - Location location = player.getEyeLocation(); - List safeblocks = GeneralMethods.getBlocksAroundPoint(player.getLocation(), 2); + if (this.charged) { + final Location location = this.player.getEyeLocation(); + final List safeblocks = GeneralMethods.getBlocksAroundPoint(this.player.getLocation(), 2); double x, y, z; - double r = 1; + final double r = 1; - for (double theta = 0; theta <= 180; theta += angleTheta) { - double dphi = anglePhi / Math.sin(Math.toRadians(theta)); + for (double theta = 0; theta <= 180; theta += this.angleTheta) { + final double dphi = this.anglePhi / Math.sin(Math.toRadians(theta)); for (double phi = 0; phi < 360; phi += dphi) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); x = r * Math.cos(rphi) * Math.sin(rtheta); y = r * Math.sin(rphi) * Math.sin(rtheta); z = r * Math.cos(rtheta); - Vector direction = new Vector(x, z, y); - FireBlast fblast = new FireBlast(location, direction.normalize(), player, damage, safeblocks); + final Vector direction = new Vector(x, z, y); + final FireBlast fblast = new FireBlast(location, direction.normalize(), this.player, this.damage, safeblocks); fblast.setRange(this.range); fblast.setShowParticles(false); - blasts.add(fblast); + this.blasts.add(fblast); } } - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } - remove(); - handleSmoothParticles(); + this.remove(); + this.handleSmoothParticles(); } @Override @@ -173,12 +173,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -192,66 +192,66 @@ public boolean isHarmlessAbility() { } public boolean isCharged() { - return charged; + return this.charged; } - public void setCharged(boolean charged) { + public void setCharged(final boolean charged) { this.charged = charged; } public int getDamage() { - return damage; + return this.damage; } - public void setDamage(int damage) { + public void setDamage(final int damage) { this.damage = damage; } public long getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(long chargeTime) { + public void setChargeTime(final long chargeTime) { this.chargeTime = chargeTime; } public long getRange() { - return range; + return this.range; } - public void setRange(long range) { + public void setRange(final long range) { this.range = range; } public double getAngleTheta() { - return angleTheta; + return this.angleTheta; } - public void setAngleTheta(double angleTheta) { + public void setAngleTheta(final double angleTheta) { this.angleTheta = angleTheta; } public double getAnglePhi() { - return anglePhi; + return this.anglePhi; } - public void setAnglePhi(double anglePhi) { + public void setAnglePhi(final double anglePhi) { this.anglePhi = anglePhi; } public double getParticlesPercentage() { - return particlesPercentage; + return this.particlesPercentage; } - public void setParticlesPercentage(double particlesPercentage) { + public void setParticlesPercentage(final double particlesPercentage) { this.particlesPercentage = particlesPercentage; } public ArrayList getBlasts() { - return blasts; + return this.blasts; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireJet.java b/src/com/projectkorra/projectkorra/firebending/FireJet.java index 1c052a427..5c7591119 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireJet.java +++ b/src/com/projectkorra/projectkorra/firebending/FireJet.java @@ -1,9 +1,6 @@ package com.projectkorra.projectkorra.firebending; -import com.projectkorra.projectkorra.ability.FireAbility; -import com.projectkorra.projectkorra.airbending.AirSpout; -import com.projectkorra.projectkorra.util.Flight; -import com.projectkorra.projectkorra.util.ParticleEffect; +import java.util.Random; import org.bukkit.Location; import org.bukkit.Material; @@ -11,7 +8,10 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.Random; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.airbending.AirSpout; +import com.projectkorra.projectkorra.util.ParticleEffect; public class FireJet extends FireAbility { @@ -22,19 +22,19 @@ public class FireJet extends FireAbility { private double speed; private Random random; - public FireJet(Player player) { + public FireJet(final Player player) { super(player); - FireJet oldJet = getAbility(player, FireJet.class); + final FireJet oldJet = getAbility(player, FireJet.class); if (oldJet != null) { oldJet.remove(); return; - } else if (bPlayer.isOnCooldown(this)) { + } else if (this.bPlayer.isOnCooldown(this)) { return; } if (hasAbility(player, AirSpout.class)) { - AirSpout abil = getAbility(player, AirSpout.class); + final AirSpout abil = getAbility(player, AirSpout.class); abil.remove(); } @@ -44,11 +44,11 @@ public FireJet(Player player) { this.cooldown = getConfig().getLong("Abilities.Fire.FireJet.Cooldown"); this.random = new Random(); - this.speed = getDayFactor(speed); - Block block = player.getLocation().getBlock(); + this.speed = this.getDayFactor(this.speed); + final Block block = player.getLocation().getBlock(); - if (BlazeArc.isIgnitable(player, block) || block.getType() == Material.AIR || block.getType() == Material.STEP || block.getType() == Material.WOOD_STEP || bPlayer.isAvatarState()) { - player.setVelocity(player.getEyeLocation().getDirection().clone().normalize().multiply(speed)); + if (BlazeArc.isIgnitable(player, block) || block.getType() == Material.AIR || block.getType() == Material.STEP || block.getType() == Material.WOOD_STEP || this.bPlayer.isAvatarState()) { + player.setVelocity(player.getEyeLocation().getDirection().clone().normalize().multiply(this.speed)); if (canFireGrief()) { if (block.getType() == Material.AIR) { createTempFire(block.getLocation()); @@ -58,44 +58,50 @@ public FireJet(Player player) { block.setType(Material.FIRE); } - new Flight(player); + ProjectKorra.flightHandler.createInstance(player, this.getName()); player.setAllowFlight(true); - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); - start(); - bPlayer.addCooldown(this); + this.start(); + this.bPlayer.addCooldown(this); } } @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if ((isWater(player.getLocation().getBlock()) || System.currentTimeMillis() > time + duration) && (!bPlayer.isAvatarState() || !avatarStateToggled)) { - remove(); + } else if ((isWater(this.player.getLocation().getBlock()) || System.currentTimeMillis() > this.time + this.duration) && (!this.bPlayer.isAvatarState() || !this.avatarStateToggled)) { + this.remove(); return; } else { - if (random.nextInt(2) == 0) { - playFirebendingSound(player.getLocation()); + if (this.random.nextInt(2) == 0) { + playFirebendingSound(this.player.getLocation()); } - ParticleEffect.FLAME.display(player.getLocation(), 0.6F, 0.6F, 0.6F, 0, 20); - ParticleEffect.SMOKE.display(player.getLocation(), 0.6F, 0.6F, 0.6F, 0, 20); + ParticleEffect.FLAME.display(this.player.getLocation(), 0.6F, 0.6F, 0.6F, 0, 20); + ParticleEffect.SMOKE.display(this.player.getLocation(), 0.6F, 0.6F, 0.6F, 0, 20); double timefactor; - if (bPlayer.isAvatarState() && avatarStateToggled) { + if (this.bPlayer.isAvatarState() && this.avatarStateToggled) { timefactor = 1; } else { - timefactor = 1 - (System.currentTimeMillis() - time) / (2.0 * duration); + timefactor = 1 - (System.currentTimeMillis() - this.time) / (2.0 * this.duration); } - Vector velocity = player.getEyeLocation().getDirection().clone().normalize().multiply(speed * timefactor); - player.setVelocity(velocity); - player.setFallDistance(0); + final Vector velocity = this.player.getEyeLocation().getDirection().clone().normalize().multiply(this.speed * timefactor); + this.player.setVelocity(velocity); + this.player.setFallDistance(0); } } + @Override + public void remove() { + super.remove(); + ProjectKorra.flightHandler.removeInstance(this.player, this.getName()); + } + @Override public String getName() { return "FireJet"; @@ -103,12 +109,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -122,38 +128,38 @@ public boolean isHarmlessAbility() { } public boolean isAvatarStateToggled() { - return avatarStateToggled; + return this.avatarStateToggled; } - public void setAvatarStateToggled(boolean avatarStateToggled) { + public void setAvatarStateToggled(final boolean avatarStateToggled) { this.avatarStateToggled = avatarStateToggled; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getDuration() { - return duration; + return this.duration; } - public void setDuration(long duration) { + public void setDuration(final long duration) { this.duration = duration; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireManipulation.java b/src/com/projectkorra/projectkorra/firebending/FireManipulation.java index 373236bc7..c97c6ccf4 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireManipulation.java +++ b/src/com/projectkorra/projectkorra/firebending/FireManipulation.java @@ -23,7 +23,7 @@ public static enum FireManipulationType { SHIFT, CLICK; } - // Configurable variables + // Configurable variables. private long streamCooldown; private double streamRange; private double streamDamage; @@ -39,7 +39,7 @@ public static enum FireManipulationType { private int shieldParticles; private long maxDuration; - // Instance related variables + // Instance related variables. private FireManipulationType fireManipulationType; private boolean firing; @@ -49,15 +49,15 @@ public static enum FireManipulationType { private Location origin; private Location focalPoint; - public FireManipulation(Player player, FireManipulationType fireManipulationType) { + public FireManipulation(final Player player, final FireManipulationType fireManipulationType) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } this.fireManipulationType = fireManipulationType; - setFields(); - start(); + this.setFields(); + this.start(); } public void setFields() { @@ -80,102 +80,108 @@ public void setFields() { } public void click() { - if (System.currentTimeMillis() - getStartTime() > 1500) { - if (!firing && !charging) { - charging = true; - focalPoint = GeneralMethods.getTargetedLocation(player, shieldRange * 2); - origin = player.getLocation().clone(); + if (System.currentTimeMillis() - this.getStartTime() > 1500) { + if (!this.firing && !this.charging) { + this.charging = true; + this.focalPoint = GeneralMethods.getTargetedLocation(this.player, this.shieldRange * 2); + this.origin = this.player.getLocation().clone(); } } } @Override public void progress() { - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } - if (!firing && !charging) { - if (!player.isSneaking()) { - bPlayer.addCooldown(this, shieldCooldown); - remove(); + if (!this.firing && !this.charging) { + if (!this.player.isSneaking()) { + this.bPlayer.addCooldown(this, this.shieldCooldown); + this.remove(); return; - } else if (System.currentTimeMillis() - getStartTime() > maxDuration) { - bPlayer.addCooldown(this, shieldCooldown); - remove(); + } else if (System.currentTimeMillis() - this.getStartTime() > this.maxDuration) { + this.bPlayer.addCooldown(this, this.shieldCooldown); + this.remove(); return; } - Location targetLocation = GeneralMethods.getTargetedLocation(player, shieldRange); - points.put(targetLocation, System.currentTimeMillis()); - for (Location point : points.keySet()) { - if (System.currentTimeMillis() - points.get(point) > 1500) { - points.remove(point); + final Location targetLocation = GeneralMethods.getTargetedLocation(this.player, this.shieldRange); + this.points.put(targetLocation, System.currentTimeMillis()); + for (final Location point : this.points.keySet()) { + if (System.currentTimeMillis() - this.points.get(point) > 1500) { + this.points.remove(point); return; } ParticleEffect.FLAME.display(point, 0.25F, 0.25F, 0.25F, 0, 12); ParticleEffect.SMOKE.display(point, 0.25F, 0.25F, 0.25F, 0, 6); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(point, 1.2D)) { - if (entity instanceof LivingEntity && entity.getUniqueId() != player.getUniqueId()) { - DamageHandler.damageEntity(entity, shieldDamage, this); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(point, 1.2D)) { + if (entity instanceof LivingEntity && entity.getUniqueId() != this.player.getUniqueId()) { + DamageHandler.damageEntity(entity, this.shieldDamage, this); } } - if (new Random().nextInt(points.keySet().size()) == 0) { + if (new Random().nextInt(this.points.keySet().size()) == 0) { playFirebendingSound(point); } } - } else if (!firing && charging) { - if (!player.isSneaking()) { - remove(); + } else if (!this.firing && this.charging) { + if (!this.player.isSneaking()) { + this.remove(); return; } boolean readyToFire = true; - for (Location point : points.keySet()) { - if (point.distance(focalPoint) > 1) { + for (final Location point : this.points.keySet()) { + if (point.distance(this.focalPoint) > 1) { readyToFire = false; } } if (readyToFire) { - shotPoint = focalPoint.clone(); - firing = true; + this.shotPoint = this.focalPoint.clone(); + this.firing = true; return; } - for (Location point : points.keySet()) { - Vector direction = focalPoint.toVector().subtract(point.toVector()); - point.add(direction.clone().multiply(streamSpeed / 5)); - ParticleEffect.FLAME.display(point, 0.25F, 0.25F, 0.25F, 0, shieldParticles); - ParticleEffect.SMOKE.display(point, 0.25F, 0.25F, 0.25F, 0, shieldParticles / 2); + for (final Location point : this.points.keySet()) { + final Vector direction = this.focalPoint.toVector().subtract(point.toVector()); + point.add(direction.clone().multiply(this.streamSpeed / 5)); + ParticleEffect.FLAME.display(point, 0.25F, 0.25F, 0.25F, 0, this.shieldParticles); + ParticleEffect.SMOKE.display(point, 0.25F, 0.25F, 0.25F, 0, this.shieldParticles / 2); } } else { - Vector direction = player.getLocation().getDirection().clone(); - if (streamSneaking && !player.isSneaking()) { - streamSneaking = false; - streamRemoveTime = System.currentTimeMillis(); - streamSneakDirection = direction; + Vector direction = this.player.getLocation().getDirection().clone(); + if (this.streamSneaking && !this.player.isSneaking()) { + this.streamSneaking = false; + this.streamRemoveTime = System.currentTimeMillis(); + this.streamSneakDirection = direction; } - if (!streamSneaking) { - direction = streamSneakDirection; - if (System.currentTimeMillis() - streamRemoveTime > 1000) { - bPlayer.addCooldown(this, streamCooldown); - remove(); + if (!this.streamSneaking) { + direction = this.streamSneakDirection; + if (System.currentTimeMillis() - this.streamRemoveTime > 1000) { + this.bPlayer.addCooldown(this, this.streamCooldown); + this.remove(); return; } } - shotPoint.add(direction.multiply(streamSpeed)); - if (shotPoint.distance(origin) > streamRange) { - bPlayer.addCooldown(this, streamCooldown); - remove(); + this.shotPoint.add(direction.multiply(this.streamSpeed)); + if (this.shotPoint.distance(this.origin) > this.streamRange) { + this.bPlayer.addCooldown(this, this.streamCooldown); + this.remove(); return; } - ParticleEffect.FLAME.display(shotPoint, 0.5F, 0.5F, 0.5F, 0.01F, streamParticles); - ParticleEffect.SMOKE.display(shotPoint, 0.5F, 0.5F, 0.5F, 0.01F, streamParticles / 2); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(shotPoint, 2)) { - if (entity instanceof LivingEntity && entity.getUniqueId() != player.getUniqueId()) { - DamageHandler.damageEntity(entity, streamDamage, this); + if (GeneralMethods.isSolid(this.shotPoint.getBlock())) { + this.bPlayer.addCooldown(this); + this.remove(); + return; + } + + ParticleEffect.FLAME.display(this.shotPoint, 0.5F, 0.5F, 0.5F, 0.01F, this.streamParticles); + ParticleEffect.SMOKE.display(this.shotPoint, 0.5F, 0.5F, 0.5F, 0.01F, this.streamParticles / 2); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.shotPoint, 2)) { + if (entity instanceof LivingEntity && entity.getUniqueId() != this.player.getUniqueId()) { + DamageHandler.damageEntity(entity, this.streamDamage, this); } } if (new Random().nextInt(5) == 0) { - playFirebendingSound(shotPoint); + playFirebendingSound(this.shotPoint); } } } @@ -207,17 +213,17 @@ public Location getLocation() { @Override public List getLocations() { - List locations = new ArrayList<>(); - locations.addAll(points.keySet()); + final List locations = new ArrayList<>(); + locations.addAll(this.points.keySet()); return locations; } public FireManipulationType getFireManipulationType() { - return fireManipulationType; + return this.fireManipulationType; } - + @Override public double getCollisionRadius() { return 0.4; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/firebending/FireShield.java b/src/com/projectkorra/projectkorra/firebending/FireShield.java index 419988d40..864dc3fc2 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireShield.java +++ b/src/com/projectkorra/projectkorra/firebending/FireShield.java @@ -1,6 +1,5 @@ package com.projectkorra.projectkorra.firebending; -import java.util.ArrayList; import java.util.Random; import org.bukkit.Effect; @@ -23,40 +22,44 @@ public class FireShield extends FireAbility { private boolean shield; private boolean ignite; - private long time; - private long duration; + private long discDuration; + private long shieldDuration; private long interval; - private long cooldown; + private long discCooldown; + private long shieldCooldown; private double radius; private double discRadius; - private double fireTicks; + private double discFireTicks; + private double shieldFireTicks; private Location location; private Random random; + private int increment = 20; - public FireShield(Player player) { + public FireShield(final Player player) { this(player, false); } - public FireShield(Player player, boolean shield) { + public FireShield(final Player player, final boolean shield) { super(player); this.shield = shield; this.ignite = true; - this.interval = getConfig().getLong("Abilities.Fire.FireShield.Interval"); - this.cooldown = shield ? 0 : getConfig().getLong("Abilities.Fire.FireShield.Cooldown"); - this.duration = getConfig().getLong("Abilities.Fire.FireShield.Duration"); - this.radius = getConfig().getDouble("Abilities.Fire.FireShield.Radius"); - this.discRadius = getConfig().getDouble("Abilities.Fire.FireShield.DiscRadius"); - this.fireTicks = getConfig().getDouble("Abilities.Fire.FireShield.FireTicks"); + this.discCooldown = getConfig().getLong("Abilities.Fire.FireShield.Disc.Cooldown"); + this.discDuration = getConfig().getLong("Abilities.Fire.FireShield.Disc.Duration"); + this.discRadius = getConfig().getDouble("Abilities.Fire.FireShield.Disc.Radius"); + this.discFireTicks = getConfig().getDouble("Abilities.Fire.FireShield.Disc.FireTicks"); + this.shieldCooldown = getConfig().getLong("Abilities.Fire.FireShield.Shield.Cooldown"); + this.shieldDuration = getConfig().getLong("Abilities.Fire.FireShield.Shield.Duration"); + this.radius = getConfig().getDouble("Abilities.Fire.FireShield.Shield.Radius"); + this.shieldFireTicks = getConfig().getDouble("Abilities.Fire.FireShield.Shield.FireTicks"); this.random = new Random(); - if (hasAbility(player, FireShield.class) || bPlayer.isOnCooldown("FireShield")) { + if (hasAbility(player, FireShield.class) || this.bPlayer.isOnCooldown("FireShield")) { return; } else if (!player.getEyeLocation().getBlock().isLiquid()) { - time = System.currentTimeMillis(); - start(); + this.start(); if (!shield) { - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } } } @@ -66,9 +69,9 @@ public FireShield(Player player, boolean shield) { * {@link Collision} for the new system. */ @Deprecated - public static boolean isWithinShield(Location loc) { - for (FireShield fshield : getAbilities(FireShield.class)) { - Location playerLoc = fshield.player.getLocation(); + public static boolean isWithinShield(final Location loc) { + for (final FireShield fshield : getAbilities(FireShield.class)) { + final Location playerLoc = fshield.player.getLocation(); if (fshield.shield) { if (!playerLoc.getWorld().equals(loc.getWorld())) { @@ -77,7 +80,7 @@ public static boolean isWithinShield(Location loc) { return true; } } else { - Location tempLoc = playerLoc.clone().add(playerLoc.multiply(fshield.discRadius)); + final Location tempLoc = playerLoc.clone().add(playerLoc.multiply(fshield.discRadius)); if (!tempLoc.getWorld().equals(loc.getWorld())) { return false; } else if (tempLoc.getWorld().equals(loc.getWorld()) && tempLoc.distance(loc) <= fshield.discRadius * fshield.discRadius) { @@ -90,105 +93,90 @@ public static boolean isWithinShield(Location loc) { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; - } else if (!player.isSneaking() && shield) { - remove(); + } else if ((!this.player.isSneaking() && this.shield) || (System.currentTimeMillis() > this.getStartTime() + this.shieldDuration && this.shield && this.shieldDuration > 0)) { + this.remove(); return; - } else if (System.currentTimeMillis() > getStartTime() + duration && !shield) { - remove(); + } else if (System.currentTimeMillis() > this.getStartTime() + this.discDuration && !this.shield) { + this.remove(); return; } - if (System.currentTimeMillis() > time + interval) { - time = System.currentTimeMillis(); + if (this.shield) { + this.location = this.player.getEyeLocation().clone(); - if (shield) { - ArrayList blocks = new ArrayList<>(); - location = player.getEyeLocation().clone(); + for (double theta = 0; theta < 180; theta += this.increment) { + for (double phi = 0; phi < 360; phi += this.increment) { + final double rphi = Math.toRadians(phi); + final double rtheta = Math.toRadians(theta); - for (double theta = 0; theta < 180; theta += 20) { - for (double phi = 0; phi < 360; phi += 20) { - double rphi = Math.toRadians(phi); - double rtheta = Math.toRadians(theta); - - Block block = location.clone().add(radius * Math.cos(rphi) * Math.sin(rtheta), radius * Math.cos(rtheta), radius * Math.sin(rphi) * Math.sin(rtheta)).getBlock(); - if (!blocks.contains(block) && !GeneralMethods.isSolid(block) && !block.isLiquid()) { - blocks.add(block); - } + final Location display = this.location.clone().add(this.radius / 1.5 * Math.cos(rphi) * Math.sin(rtheta), this.radius / 1.5 * Math.cos(rtheta), this.radius / 1.5 * Math.sin(rphi) * Math.sin(rtheta)); + if (this.random.nextInt(6) == 0) { + ParticleEffect.SMOKE.display(display, 0, 0, 0, 0, 1); } - } - - for (Block block : blocks) { - if (!GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - if (random.nextInt(3) == 0) { - ParticleEffect.SMOKE.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 1); - } - ParticleEffect.FLAME.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 1); - if (random.nextInt(7) == 0) { - playFirebendingSound(block.getLocation()); - } + if (this.random.nextInt(4) == 0) { + ParticleEffect.FLAME.display(display, 0.1f, 0.1f, 0.1f, 0.013f, 1); } - } - - for (Block testblock : GeneralMethods.getBlocksAroundPoint(player.getLocation(), radius)) { - if (testblock.getType() == Material.FIRE) { - testblock.setType(Material.AIR); - testblock.getWorld().playEffect(testblock.getLocation(), Effect.EXTINGUISH, 0); + if (this.random.nextInt(7) == 0) { + playFirebendingSound(display); } } + } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, radius)) { - if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { - continue; - } else if (player.getEntityId() != entity.getEntityId() && ignite) { - entity.setFireTicks(120); - new FireDamageTimer(entity, player); - } - } - } else { - ArrayList blocks = new ArrayList<>(); - location = player.getEyeLocation().clone(); - Vector direction = location.getDirection(); - location = location.clone().add(direction.multiply(radius)); - - for (double theta = 0; theta < 360; theta += 20) { - Vector vector = GeneralMethods.getOrthogonalVector(direction, theta, discRadius); - Block block = location.clone().add(vector).getBlock(); - if (!blocks.contains(block) && !GeneralMethods.isSolid(block) && !block.isLiquid()) { - blocks.add(block); - } - } + this.increment += 20; + if (this.increment >= 70) { + this.increment = 20; + } - for (Block block : blocks) { - if (!GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - if (random.nextInt(1) == 0) { - ParticleEffect.SMOKE.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 1); - } - ParticleEffect.FLAME.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 3); - if (random.nextInt(4) == 0) { - playFirebendingSound(block.getLocation()); - } - } + for (final Block testblock : GeneralMethods.getBlocksAroundPoint(this.player.getLocation(), this.radius)) { + if (testblock.getType() == Material.FIRE) { + testblock.setType(Material.AIR); + testblock.getWorld().playEffect(testblock.getLocation(), Effect.EXTINGUISH, 0); } + } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, discRadius)) { - if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { - continue; - } - if (player.getEntityId() != entity.getEntityId() && ignite) { - entity.setFireTicks((int) (fireTicks * 20)); - if (!(entity instanceof LivingEntity)) { - entity.remove(); - } + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.radius)) { + if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { + continue; + } else if (entity instanceof LivingEntity) { + if (this.player.getEntityId() != entity.getEntityId() && this.ignite) { + entity.setFireTicks((int) (this.shieldFireTicks * 20)); + new FireDamageTimer(entity, this.player); } + } else if (entity instanceof Projectile) { + entity.remove(); + } + } + } else { + this.location = this.player.getEyeLocation().clone(); + final Vector direction = this.location.getDirection(); + this.location = this.location.clone().add(direction.multiply(this.radius)); + ParticleEffect.FLAME.display(this.location, 0.2f, 0.2f, 0.2f, 0.023f, 3); + + for (double theta = 0; theta < 360; theta += 20) { + final Vector vector = GeneralMethods.getOrthogonalVector(direction, theta, this.discRadius / 1.5); + final Location display = this.location.clone().add(vector); + if (this.random.nextInt(6) == 0) { + ParticleEffect.SMOKE.display(display, 0, 0, 0, 0, 1); } + ParticleEffect.FLAME.display(display, 0.3f, 0.2f, 0.3f, 0.023f, 2); + if (this.random.nextInt(4) == 0) { + playFirebendingSound(display); + } + } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, discRadius)) { - if (entity instanceof Projectile) { - entity.remove(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.discRadius)) { + if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { + continue; + } else if (entity instanceof LivingEntity) { + if (this.player.getEntityId() != entity.getEntityId() && this.ignite) { + entity.setFireTicks((int) (this.discFireTicks * 20)); + new FireDamageTimer(entity, this.player); } + } else if (entity instanceof Projectile) { + entity.remove(); } } } @@ -201,12 +189,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.shield ? this.shieldCooldown : this.discCooldown; } @Override @@ -221,75 +209,79 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return shield ? radius : discRadius; + return this.shield ? this.radius : this.discRadius; } public boolean isShield() { - return shield; + return this.shield; } - public void setShield(boolean shield) { + public void setShield(final boolean shield) { this.shield = shield; } public boolean isIgnite() { - return ignite; + return this.ignite; } - public void setIgnite(boolean ignite) { + public void setIgnite(final boolean ignite) { this.ignite = ignite; } - public long getTime() { - return time; - } - - public void setTime(long time) { - this.time = time; + public long getDuration() { + return this.shield ? this.shieldDuration : this.discDuration; } - public long getDuration() { - return duration; + public void setDiscDuration(final long duration) { + this.discDuration = duration; } - public void setDuration(long duration) { - this.duration = duration; + public void setShieldDuration(final long duration) { + this.shieldDuration = duration; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getDiscRadius() { - return discRadius; + return this.discRadius; } - public void setDiscRadius(double discRadius) { + public void setDiscRadius(final double discRadius) { this.discRadius = discRadius; } - public double getFireTicks() { - return fireTicks; + public double getFireTicks(final boolean shield) { + return shield ? this.shieldFireTicks : this.discFireTicks; + } + + public void setFireTicks(final double fireTicks, final boolean shield) { + if (shield) { + this.shieldFireTicks = fireTicks; + } else { + this.discFireTicks = fireTicks; + } } - public void setFireTicks(double fireTicks) { - this.fireTicks = fireTicks; + public void setDiscCooldown(final long cooldown) { + this.discCooldown = cooldown; } - public void setCooldown(long cooldown) { - this.cooldown = cooldown; + public void setShieldCooldown(final long cooldown) { + this.shieldCooldown = cooldown; } } diff --git a/src/com/projectkorra/projectkorra/firebending/HeatControl.java b/src/com/projectkorra/projectkorra/firebending/HeatControl.java index a0f381116..56759beb0 100644 --- a/src/com/projectkorra/projectkorra/firebending/HeatControl.java +++ b/src/com/projectkorra/projectkorra/firebending/HeatControl.java @@ -21,11 +21,12 @@ import org.bukkit.util.Vector; import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.FireAbility; +import com.projectkorra.projectkorra.earthbending.lava.LavaFlow; import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.ReflectionHandler.PackageType; import com.projectkorra.projectkorra.util.TempBlock; import com.projectkorra.projectkorra.waterbending.SurgeWave; import com.projectkorra.projectkorra.waterbending.Torrent; @@ -45,21 +46,21 @@ public enum HeatControlType { private HeatControlType heatControlType; - // HeatControl Cook variables + // HeatControl Cook variables. private long cookTime; private long cookInterval; - //HeatControl Extinguish variables + // HeatControl Extinguish variables. private long extinguishCooldown; private double extinguishRadius; - //HeatControl Melt variables + // HeatControl Melt variables. private double meltRange; private double meltRadius; private Location meltLocation; private static final Map MELTED_BLOCKS = new HashMap<>(); - //HeatControl Solidify variables + // HeatControl Solidify variables. private int solidifyRadius; private long solidifyDelay; private long solidifyLastBlockTime; @@ -71,31 +72,31 @@ public enum HeatControlType { private Location solidifyLocation; private Random randy; - public HeatControl(Player player, HeatControlType heatControlType) { + public HeatControl(final Player player, final HeatControlType heatControlType) { super(player); this.heatControlType = heatControlType; - setFields(); + this.setFields(); if (this.heatControlType == HeatControlType.COOK) { if (!isCookable(player.getInventory().getItemInMainHand().getType())) { - remove(); + this.remove(); new HeatControl(player, HeatControlType.SOLIDIFY); return; } - start(); + this.start(); } else if (this.heatControlType == HeatControlType.EXTINGUISH) { - if (bPlayer.isOnCooldown(getName() + "Extinguish")) { - remove(); + if (this.bPlayer.isOnCooldown(this.getName() + "Extinguish")) { + this.remove(); return; } - start(); + this.start(); } else if (this.heatControlType == HeatControlType.MELT) { - meltLocation = GeneralMethods.getTargetedLocation(player, meltRange); - for (Block block : GeneralMethods.getBlocksAroundPoint(meltLocation, meltRadius)) { + this.meltLocation = GeneralMethods.getTargetedLocation(player, this.meltRange); + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.meltLocation, this.meltRadius)) { if (isMeltable(block)) { melt(player, block); @@ -103,16 +104,16 @@ public HeatControl(Player player, HeatControlType heatControlType) { } } else if (this.heatControlType == HeatControlType.SOLIDIFY) { - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; - } else if (getLavaBlock(player, solidifyRange) == null) { - remove(); + } else if (getLavaBlock(player, this.solidifyRange) == null) { + this.remove(); new HeatControl(player, HeatControlType.EXTINGUISH); return; } - solidifyLastBlockTime = System.currentTimeMillis(); - start(); + this.solidifyLastBlockTime = System.currentTimeMillis(); + this.start(); } } @@ -124,12 +125,12 @@ public void setFields() { } else if (this.heatControlType == HeatControlType.EXTINGUISH) { this.extinguishCooldown = getConfig().getLong("Abilities.Fire.HeatControl.Extinguish.Cooldown"); this.extinguishRadius = getConfig().getLong("Abilities.Fire.HeatControl.Extinguish.Radius"); - this.extinguishRadius = getDayFactor(this.extinguishRadius); + this.extinguishRadius = this.getDayFactor(this.extinguishRadius); } else if (this.heatControlType == HeatControlType.MELT) { this.meltRange = getConfig().getDouble("Abilities.Fire.HeatControl.Melt.Range"); this.meltRadius = getConfig().getDouble("Abilities.Fire.HeatControl.Melt.Radius"); - this.meltRange = getDayFactor(this.meltRange); - this.meltRadius = getDayFactor(this.meltRadius); + this.meltRange = this.getDayFactor(this.meltRange); + this.meltRadius = this.getDayFactor(this.meltRadius); } else if (this.heatControlType == HeatControlType.SOLIDIFY) { this.solidifyRadius = 1; this.solidifyDelay = 50; @@ -145,46 +146,46 @@ public void setFields() { @Override public void progress() { - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } if (this.heatControlType == HeatControlType.COOK) { - if (!player.isSneaking()) { - remove(); + if (!this.player.isSneaking()) { + this.remove(); return; } - if (!isCookable(player.getInventory().getItemInMainHand().getType())) { - remove(); + if (!isCookable(this.player.getInventory().getItemInMainHand().getType())) { + this.remove(); return; } - if (System.currentTimeMillis() - cookTime > cookInterval) { - cook(); - cookTime = System.currentTimeMillis(); + if (System.currentTimeMillis() - this.cookTime > this.cookInterval) { + this.cook(); + this.cookTime = System.currentTimeMillis(); return; } - displayCookParticles(); + this.displayCookParticles(); } else if (this.heatControlType == HeatControlType.EXTINGUISH) { - if (!player.isSneaking()) { - bPlayer.addCooldown(getName() + "Extinguish", extinguishCooldown); - remove(); + if (!this.player.isSneaking()) { + this.bPlayer.addCooldown(this.getName() + "Extinguish", this.extinguishCooldown); + this.remove(); return; } - Set blocks = new HashSet<>(); - for (Material material : getTransparentMaterials()) { + final Set blocks = new HashSet<>(); + for (final Material material : getTransparentMaterials()) { blocks.add(material); } - for (Block block : GeneralMethods.getBlocksAroundPoint(player.getLocation(), extinguishRadius)) { - Material material = block.getType(); + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.player.getLocation(), this.extinguishRadius)) { + final Material material = block.getType(); if (material == Material.FIRE && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { block.setType(Material.AIR); @@ -194,57 +195,54 @@ public void progress() { } else if (this.heatControlType == HeatControlType.SOLIDIFY) { - if (solidifyRadius >= solidifyMaxRadius) { - remove(); + if (this.solidifyRadius >= this.solidifyMaxRadius) { + this.remove(); return; } - if (!player.isSneaking()) { - remove(); + if (!this.player.isSneaking()) { + this.remove(); return; } - if (!solidifying) { - solidifying = true; + if (!this.solidifying) { + this.solidifying = true; } - Location targetLocation = GeneralMethods.getTargetedLocation(player, solidifyRange); - //if (isLava(targetLocation.getBlock())) { - // remove(); - // new HeatControl(player, HeatControlType.EXTINGUISH); - //} - resetLocation(targetLocation); - List area = GeneralMethods.getCircle(solidifyLocation, solidifyRadius, 3, true, true, 0); - solidify(area); + final Location targetLocation = GeneralMethods.getTargetedLocation(this.player, this.solidifyRange); + + this.resetLocation(targetLocation); + final List area = GeneralMethods.getCircle(this.solidifyLocation, this.solidifyRadius, 3, true, true, 0); + this.solidify(area); } } private void cook() { - ItemStack cooked = getCooked(player.getInventory().getItemInMainHand()); - HashMap cantFit = player.getInventory().addItem(cooked); - for (int id : cantFit.keySet()) { - player.getWorld().dropItem(player.getEyeLocation(), cantFit.get(id)); + final ItemStack cooked = this.getCooked(this.player.getInventory().getItemInMainHand()); + final HashMap cantFit = this.player.getInventory().addItem(cooked); + for (final int id : cantFit.keySet()) { + this.player.getWorld().dropItem(this.player.getEyeLocation(), cantFit.get(id)); } - int amount = player.getInventory().getItemInMainHand().getAmount(); + final int amount = this.player.getInventory().getItemInMainHand().getAmount(); if (amount == 1) { - player.getInventory().clear(player.getInventory().getHeldItemSlot()); + this.player.getInventory().clear(this.player.getInventory().getHeldItemSlot()); } else { - player.getInventory().getItemInMainHand().setAmount(amount - 1); + this.player.getInventory().getItemInMainHand().setAmount(amount - 1); } } - private ItemStack getCooked(ItemStack is) { + private ItemStack getCooked(final ItemStack is) { ItemStack cooked = new ItemStack(Material.AIR); - Material material = is.getType(); + final Material material = is.getType(); switch (material) { case RAW_BEEF: cooked = new ItemStack(Material.COOKED_BEEF, 1); break; case RAW_FISH: - ItemStack salmon = new ItemStack(Material.RAW_FISH, 1, (short) 1); + final ItemStack salmon = new ItemStack(Material.RAW_FISH, 1, (short) 1); if (is.getDurability() == salmon.getDurability()) { cooked = new ItemStack(Material.COOKED_FISH, 1, (short) 1); } else { @@ -274,28 +272,28 @@ private ItemStack getCooked(ItemStack is) { } public void displayCookParticles() { - ParticleEffect.FLAME.display(player.getLocation().clone().add(0, 1, 0), 0.5F, 0.5F, 0.5F, 0, 3); - ParticleEffect.SMOKE.display(player.getLocation().clone().add(0, 1, 0), 0.5F, 0.5F, 0.5F, 0, 2); + ParticleEffect.FLAME.display(this.player.getLocation().clone().add(0, 1, 0), 0.5F, 0.5F, 0.5F, 0, 3); + ParticleEffect.SMOKE.display(this.player.getLocation().clone().add(0, 1, 0), 0.5F, 0.5F, 0.5F, 0, 2); } - public static boolean isCookable(Material material) { + public static boolean isCookable(final Material material) { return Arrays.asList(COOKABLE_MATERIALS).contains(material); } - public static boolean canBurn(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean canBurn(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return true; } else if (bPlayer.getBoundAbilityName().equals("HeatControl") || hasAbility(player, FireJet.class)) { player.setFireTicks(-1); return false; - } else if (player.getFireTicks() > 80 && bPlayer.canBendPassive(Element.FIRE)) { + } else if (player.getFireTicks() > 80 && bPlayer.canBendPassive(getAbility(HeatControl.class))) { player.setFireTicks(80); } return true; } - public static void melt(Player player, final Block block) { + public static void melt(final Player player, final Block block) { if (GeneralMethods.isRegionProtectedFromBuild(player, "HeatControl", block.getLocation())) { return; } else if (!SurgeWave.canThaw(block)) { @@ -310,7 +308,7 @@ public static void melt(Player player, final Block block) { } if (TempBlock.isTempBlock(block)) { - TempBlock tb = TempBlock.get(block); + final TempBlock tb = TempBlock.get(block); if (PhaseChange.getFrozenBlocksAsTempBlock().contains(tb)) { PhaseChange.thaw(tb); } @@ -324,7 +322,7 @@ public static void melt(Player player, final Block block) { block.setType(Material.AIR); return; } else { - TempBlock tb = new TempBlock(block, Material.WATER, (byte) 0); + final TempBlock tb = new TempBlock(block, Material.WATER, (byte) 0); MELTED_BLOCKS.put(block, tb); new BukkitRunnable() { @@ -338,46 +336,70 @@ public void run() { } } - public void solidify(List area) { - if (System.currentTimeMillis() < solidifyLastBlockTime + solidifyDelay) { + public void solidify(final List area) { + if (System.currentTimeMillis() < this.solidifyLastBlockTime + this.solidifyDelay) { return; } - List lava = new ArrayList(); - for (Location l : area) { + final List lava = new ArrayList(); + for (final Location l : area) { if (isLava(l.getBlock())) { lava.add(l.getBlock()); } } - solidifyLastBlockTime = System.currentTimeMillis(); + this.solidifyLastBlockTime = System.currentTimeMillis(); if (lava.size() == 0) { - solidifyRadius++; + this.solidifyRadius++; return; } - Block b = lava.get(randy.nextInt(lava.size())); + final Block b = lava.get(this.randy.nextInt(lava.size())); + + Material tempRevertMaterial = Material.STONE; + + if (Integer.parseInt(PackageType.getServerVersion().split("_")[1]) > 9) { + tempRevertMaterial = Material.valueOf("MAGMA"); + } final TempBlock tempBlock; if (TempBlock.isTempBlock(b)) { tempBlock = TempBlock.get(b); - tempBlock.setType(Material.MAGMA, (byte) 0); + tempBlock.setType(tempRevertMaterial, (byte) 0); } else { - tempBlock = new TempBlock(b, Material.MAGMA, (byte) 0); + tempBlock = new TempBlock(b, tempRevertMaterial, (byte) 0); + } + + if (LavaFlow.isLavaFlowBlock(tempBlock.getBlock())) { + new BukkitRunnable() { + @Override + public void run() { + if (tempBlock != null) { + ParticleEffect.SMOKE.display(tempBlock.getBlock().getLocation().clone().add(0.5, 1, 0.5), 0.1F, 0.1F, 0.1F, 0.01F, 3); + if (HeatControl.this.randy.nextInt(3) == 0) { + tempBlock.getBlock().getWorld().playSound(tempBlock.getBlock().getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, 0.5F, 1); + } + + LavaFlow.removeBlock(tempBlock.getBlock()); + } + } + }.runTaskLater(ProjectKorra.plugin, 20); + + return; } new BukkitRunnable() { @Override public void run() { if (tempBlock != null) { - boolean bool = Math.random() > .5 ? true : false; - if (solidifyRevert) { + final boolean bool = Math.random() > .5 ? true : false; + if (HeatControl.this.solidifyRevert) { if (bool) { tempBlock.setType(Material.STONE, (byte) 0); } else { tempBlock.setType(Material.COBBLESTONE, (byte) 0); } - tempBlock.setRevertTime(solidifyRevertTime); + tempBlock.setRevertTime(HeatControl.this.solidifyRevertTime); } else { tempBlock.revertBlock(); if (bool) { @@ -388,7 +410,7 @@ public void run() { } ParticleEffect.SMOKE.display(tempBlock.getBlock().getLocation().clone().add(0.5, 1, 0.5), 0.1F, 0.1F, 0.1F, 0.01F, 3); - if (randy.nextInt(3) == 0) { + if (HeatControl.this.randy.nextInt(3) == 0) { tempBlock.getBlock().getWorld().playSound(tempBlock.getBlock().getLocation(), Sound.BLOCK_FIRE_EXTINGUISH, 0.5F, 1); } } @@ -396,15 +418,15 @@ public void run() { }.runTaskLater(ProjectKorra.plugin, 20); } - public void resetLocation(Location loc) { - if (solidifyLocation == null) { - solidifyLocation = loc; + public void resetLocation(final Location loc) { + if (this.solidifyLocation == null) { + this.solidifyLocation = loc; return; } - if (!loc.equals(solidifyLocation)) { - solidifyRadius = 1; - solidifyLocation = loc; + if (!loc.equals(this.solidifyLocation)) { + this.solidifyRadius = 1; + this.solidifyLocation = loc; } } @@ -434,23 +456,22 @@ public String getName() { @Override public Location getLocation() { - return player.getLocation(); + return this.player.getLocation(); } - @SuppressWarnings("deprecation") - public static Block getLavaBlock(Player player, double range) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection().clone().normalize(); + public static Block getLavaBlock(final Player player, final double range) { + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection().clone().normalize(); for (double i = 0; i <= range; i++) { - Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); + final Block block = location.clone().add(vector.clone().multiply(i)).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(player, location)) { continue; } if (isLava(block)) { if (TempBlock.isTempBlock(block)) { - TempBlock tb = TempBlock.get(block); - byte full = 0x0; + final TempBlock tb = TempBlock.get(block); + final byte full = 0x0; if (tb.getState().getRawData() != full && !isLava(tb.getState().getType())) { continue; } @@ -460,10 +481,10 @@ public static Block getLavaBlock(Player player, double range) { } return null; } - + public static Collection getMeltedBlocks() { return MELTED_BLOCKS.values(); - + } } diff --git a/src/com/projectkorra/projectkorra/firebending/Illumination.java b/src/com/projectkorra/projectkorra/firebending/Illumination.java index 0d9eb13f1..e2074ab94 100644 --- a/src/com/projectkorra/projectkorra/firebending/Illumination.java +++ b/src/com/projectkorra/projectkorra/firebending/Illumination.java @@ -26,101 +26,101 @@ public class Illumination extends FireAbility { private TempBlock block; private int oldLevel; - public Illumination(Player player) { + public Illumination(final Player player) { super(player); - this.range = getDayFactor(getConfig().getDouble("Abilities.Fire.Illumination.Range")); + this.range = this.getDayFactor(getConfig().getDouble("Abilities.Fire.Illumination.Range")); this.cooldown = getConfig().getLong("Abilities.Fire.Illumination.Cooldown"); this.lightThreshold = getConfig().getInt("Abilities.Fire.Illumination.LightThreshold"); - Illumination oldIllumination = getAbility(player, Illumination.class); + final Illumination oldIllumination = getAbility(player, Illumination.class); if (oldIllumination != null) { oldIllumination.remove(); return; } - if (bPlayer.isOnCooldown(this)) { + if (this.bPlayer.isOnCooldown(this)) { return; } if (player.getLocation().getBlock().getLightLevel() < this.lightThreshold) { - oldLevel = player.getLocation().getBlock().getLightLevel(); - bPlayer.addCooldown(this); - set(); - start(); + this.oldLevel = player.getLocation().getBlock().getLightLevel(); + this.bPlayer.addCooldown(this); + this.set(); + this.start(); } } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (!bPlayer.isIlluminating()) { - remove(); + if (!this.bPlayer.isIlluminating()) { + this.remove(); return; } - if (bPlayer.hasElement(Element.EARTH) && bPlayer.isTremorSensing()) { - remove(); + if (this.bPlayer.hasElement(Element.EARTH) && this.bPlayer.isTremorSensing()) { + this.remove(); return; } - if (oldLevel > this.lightThreshold) { - remove(); + if (this.oldLevel > this.lightThreshold) { + this.remove(); return; } - - if (block == null) { + + if (this.block == null) { return; } - - if (!player.getWorld().equals(block.getBlock().getWorld())) { - remove(); + + if (!this.player.getWorld().equals(this.block.getBlock().getWorld())) { + this.remove(); return; - } - - if (player.getLocation().distanceSquared(block.getLocation()) > range * range) { - remove(); + } + + if (this.player.getLocation().distanceSquared(this.block.getLocation()) > this.range * this.range) { + this.remove(); return; } - set(); + this.set(); } @Override public void remove() { super.remove(); - revert(); + this.revert(); } private void revert() { - if (block != null) { - BLOCKS.remove(block); - block.revertBlock(); + if (this.block != null) { + BLOCKS.remove(this.block); + this.block.revertBlock(); } } private void set() { - Block standingBlock = player.getLocation().getBlock(); - Block standBlock = standingBlock.getRelative(BlockFace.DOWN); + final Block standingBlock = this.player.getLocation().getBlock(); + final Block standBlock = standingBlock.getRelative(BlockFace.DOWN); - if (!BlazeArc.isIgnitable(player, standingBlock)) { + if (!BlazeArc.isIgnitable(this.player, standingBlock)) { return; } else if (!GeneralMethods.isSolid(standBlock)) { return; - } else if (block != null && standingBlock.equals(block.getBlock())) { + } else if (this.block != null && standingBlock.equals(this.block.getBlock())) { return; } else if (standBlock.getType() == Material.LEAVES || standBlock.getType() == Material.LEAVES_2) { return; } - - revert(); - this.block = new TempBlock(standingBlock, Material.TORCH, (byte)0); - BLOCKS.put(block, player); + + this.revert(); + this.block = new TempBlock(standingBlock, Material.TORCH, (byte) 0); + BLOCKS.put(this.block, this.player); } @Override @@ -130,12 +130,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -149,34 +149,34 @@ public boolean isHarmlessAbility() { } public byte getNormalData() { - return normalData; + return this.normalData; } - public void setNormalData(byte normalData) { + public void setNormalData(final byte normalData) { this.normalData = normalData; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public Material getNormalType() { - return normalType; + return this.normalType; } - public void setNormalType(Material normalType) { + public void setNormalType(final Material normalType) { this.normalType = normalType; } public TempBlock getBlock() { - return block; + return this.block; } - public void setBlock(TempBlock block) { + public void setBlock(final TempBlock block) { this.block = block; } @@ -186,19 +186,20 @@ public static Map getBlocks() { /** * Returns whether the block provided is a torch created by Illumination - * + * * @param block The block being tested */ - public static boolean isIlluminationTorch(Block block) { - for (TempBlock b : BLOCKS.keySet()) { - if (b.getBlock().equals(block)) { - return true; - } + public static boolean isIlluminationTorch(final Block block) { + final TempBlock tempBlock = TempBlock.get(block); + + if (tempBlock == null || block.getType() != Material.TORCH || !BLOCKS.containsKey(tempBlock)) { + return false; } - return false; + + return true; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/firebending/WallOfFire.java b/src/com/projectkorra/projectkorra/firebending/WallOfFire.java index 00656819f..c2c479a2f 100644 --- a/src/com/projectkorra/projectkorra/firebending/WallOfFire.java +++ b/src/com/projectkorra/projectkorra/firebending/WallOfFire.java @@ -39,7 +39,7 @@ public class WallOfFire extends FireAbility { private Location origin; private List blocks; - public WallOfFire(Player player) { + public WallOfFire(final Player player) { super(player); this.active = true; @@ -56,22 +56,22 @@ public WallOfFire(Player player) { this.random = new Random(); this.blocks = new ArrayList<>(); - if (hasAbility(player, WallOfFire.class) && !bPlayer.isAvatarState()) { + if (hasAbility(player, WallOfFire.class) && !this.bPlayer.isAvatarState()) { return; - } else if (bPlayer.isOnCooldown(this)) { + } else if (this.bPlayer.isOnCooldown(this)) { return; } - origin = GeneralMethods.getTargetedLocation(player, range); + this.origin = GeneralMethods.getTargetedLocation(player, this.range); if (isDay(player.getWorld())) { - width = (int) getDayFactor(width); - height = (int) getDayFactor(height); - duration = (long) getDayFactor(duration); - damage = (int) getDayFactor(damage); + this.width = (int) this.getDayFactor(this.width); + this.height = (int) this.getDayFactor(this.height); + this.duration = (long) this.getDayFactor(this.duration); + this.damage = (int) this.getDayFactor(this.damage); } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.width = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.WallOfFire.Width"); this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.WallOfFire.Height"); this.duration = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.WallOfFire.Duration"); @@ -79,56 +79,56 @@ public WallOfFire(Player player) { this.fireTicks = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.WallOfFire.FireTicks"); } - time = System.currentTimeMillis(); - Block block = origin.getBlock(); + this.time = System.currentTimeMillis(); + final Block block = this.origin.getBlock(); if (block.isLiquid() || GeneralMethods.isSolid(block)) { return; } - Vector direction = player.getEyeLocation().getDirection(); - Vector compare = direction.clone(); + final Vector direction = player.getEyeLocation().getDirection(); + final Vector compare = direction.clone(); compare.setY(0); - if (Math.abs(direction.angle(compare)) > Math.toRadians(maxAngle)) { + if (Math.abs(direction.angle(compare)) > Math.toRadians(this.maxAngle)) { return; } - initializeBlocks(); - start(); - bPlayer.addCooldown(this); + this.initializeBlocks(); + this.start(); + this.bPlayer.addCooldown(this); } - private void affect(Entity entity) { + private void affect(final Entity entity) { GeneralMethods.setVelocity(entity, new Vector(0, 0, 0)); if (entity instanceof LivingEntity) { - Block block = ((LivingEntity) entity).getEyeLocation().getBlock(); + final Block block = ((LivingEntity) entity).getEyeLocation().getBlock(); if (TempBlock.isTempBlock(block) && isIce(block)) { return; } - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); AirAbility.breakBreathbendingHold(entity); } - entity.setFireTicks((int) (fireTicks * 20)); - new FireDamageTimer(entity, player); + entity.setFireTicks((int) (this.fireTicks * 20)); + new FireDamageTimer(entity, this.player); } private void damage() { - double radius = height; - if (radius < width) { - radius = width; + double radius = this.height; + if (radius < this.width) { + radius = this.width; } radius = radius + 1; - List entities = GeneralMethods.getEntitiesAroundPoint(origin, radius); - if (entities.contains(player)) { - entities.remove(player); + final List entities = GeneralMethods.getEntitiesAroundPoint(this.origin, radius); + if (entities.contains(this.player)) { + entities.remove(this.player); } - for (Entity entity : entities) { + for (final Entity entity : entities) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } - for (Block block : blocks) { + for (final Block block : this.blocks) { if (entity.getLocation().distanceSquared(block.getLocation()) <= 1.5 * 1.5) { - affect(entity); + this.affect(entity); break; } } @@ -136,21 +136,21 @@ private void damage() { } private void display() { - for (Block block : blocks) { - if (!isTransparent(block)) { + for (final Block block : this.blocks) { + if (!this.isTransparent(block)) { continue; } ParticleEffect.FLAME.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 3); ParticleEffect.SMOKE.display(block.getLocation(), 0.6F, 0.6F, 0.6F, 0, 1); - if (random.nextInt(7) == 0) { + if (this.random.nextInt(7) == 0) { playFirebendingSound(block.getLocation()); } } } private void initializeBlocks() { - Vector direction = player.getEyeLocation().getDirection(); + Vector direction = this.player.getEyeLocation().getDirection(); direction = direction.normalize(); Vector ortholr = GeneralMethods.getOrthogonalVector(direction, 0, 1); @@ -159,19 +159,19 @@ private void initializeBlocks() { Vector orthoud = GeneralMethods.getOrthogonalVector(direction, 90, 1); orthoud = orthoud.normalize(); - double w = width; - double h = height; + final double w = this.width; + final double h = this.height; for (double i = -w; i <= w; i++) { for (double j = -h; j <= h; j++) { - Location location = origin.clone().add(orthoud.clone().multiply(j)); + Location location = this.origin.clone().add(orthoud.clone().multiply(j)); location = location.add(ortholr.clone().multiply(i)); if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { continue; } - Block block = location.getBlock(); - if (!blocks.contains(block)) { - blocks.add(block); + final Block block = location.getBlock(); + if (!this.blocks.contains(block)) { + this.blocks.add(block); } } } @@ -179,26 +179,26 @@ private void initializeBlocks() { @Override public void progress() { - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); - if (time - getStartTime() > cooldown) { - remove(); + if (this.time - this.getStartTime() > this.cooldown) { + this.remove(); return; - } else if (!active) { + } else if (!this.active) { return; - } else if (time - getStartTime() > duration) { - active = false; + } else if (this.time - this.getStartTime() > this.duration) { + this.active = false; return; } - if (time - getStartTime() > intervalTick * interval) { - intervalTick++; - display(); + if (this.time - this.getStartTime() > this.intervalTick * this.interval) { + this.intervalTick++; + this.display(); } - if (time - getStartTime() > damageTick * damageInterval) { - damageTick++; - damage(); + if (this.time - this.getStartTime() > this.damageTick * this.damageInterval) { + this.damageTick++; + this.damage(); } } @@ -209,12 +209,12 @@ public String getName() { @Override public Location getLocation() { - return origin; + return this.origin; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -229,130 +229,130 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (Block block : blocks) { + final ArrayList locations = new ArrayList<>(); + for (final Block block : this.blocks) { locations.add(block.getLocation()); } return locations; } public boolean isActive() { - return active; + return this.active; } - public void setActive(boolean active) { + public void setActive(final boolean active) { this.active = active; } public int getDamageTick() { - return damageTick; + return this.damageTick; } - public void setDamageTick(int damageTick) { + public void setDamageTick(final int damageTick) { this.damageTick = damageTick; } public int getIntervalTick() { - return intervalTick; + return this.intervalTick; } - public void setIntervalTick(int intervalTick) { + public void setIntervalTick(final int intervalTick) { this.intervalTick = intervalTick; } public int getRange() { - return range; + return this.range; } - public void setRange(int range) { + public void setRange(final int range) { this.range = range; } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public int getWidth() { - return width; + return this.width; } - public void setWidth(int width) { + public void setWidth(final int width) { this.width = width; } public int getDamage() { - return damage; + return this.damage; } - public void setDamage(int damage) { + public void setDamage(final int damage) { this.damage = damage; } public long getDamageInterval() { - return damageInterval; + return this.damageInterval; } - public void setDamageInterval(long damageInterval) { + public void setDamageInterval(final long damageInterval) { this.damageInterval = damageInterval; } public long getDuration() { - return duration; + return this.duration; } - public void setDuration(long duration) { + public void setDuration(final long duration) { this.duration = duration; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getFireTicks() { - return fireTicks; + return this.fireTicks; } - public void setFireTicks(double fireTicks) { + public void setFireTicks(final double fireTicks) { this.fireTicks = fireTicks; } public double getMaxAngle() { - return maxAngle; + return this.maxAngle; } - public void setMaxAngle(double maxAngle) { + public void setMaxAngle(final double maxAngle) { this.maxAngle = maxAngle; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public List getBlocks() { - return blocks; + return this.blocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/firebending/combo/FireComboStream.java b/src/com/projectkorra/projectkorra/firebending/combo/FireComboStream.java index e2f9ea80a..d83fd2d23 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/FireComboStream.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/FireComboStream.java @@ -22,12 +22,11 @@ import com.projectkorra.projectkorra.util.ParticleEffect; /*** - * Is only here for legacy purposes. All fire combos - * used to use a form of this stream for all their - * progress methods. If someone else was reliant on - * that, they can use this ability instead. + * Is only here for legacy purposes. All fire combos used to use a form of this + * stream for all their progress methods. If someone else was reliant on that, + * they can use this ability instead. */ -public class FireComboStream extends BukkitRunnable { +public class FireComboStream extends BukkitRunnable { private boolean useNewParticles; private boolean cancelled; private boolean collides; @@ -37,20 +36,20 @@ public class FireComboStream extends BukkitRunnable { private int checkCollisionCounter; private float spread; private double collisionRadius; - private double speed; - private double distance; + private final double speed; + private final double distance; private double damage; private double fireTicks; private double knockback; ParticleEffect particleEffect; - private Player player; - private BendingPlayer bPlayer; - private CoreAbility coreAbility; - private Vector direction; - private Location initialLocation; - private Location location; - - public FireComboStream(Player player, CoreAbility coreAbility, Vector direction, Location location, double distance, double speed) { + private final Player player; + private final BendingPlayer bPlayer; + private final CoreAbility coreAbility; + private final Vector direction; + private final Location initialLocation; + private final Location location; + + public FireComboStream(final Player player, final CoreAbility coreAbility, final Vector direction, final Location location, final double distance, final double speed) { this.useNewParticles = false; this.cancelled = false; this.collides = true; @@ -70,57 +69,61 @@ public FireComboStream(Player player, CoreAbility coreAbility, Vector direction, this.location = location.clone(); this.distance = distance; } - + @Override public void run() { - Block block = location.getBlock(); + final Block block = this.location.getBlock(); if (block.getRelative(BlockFace.UP).getType() != Material.AIR && !ElementalAbility.isPlant(block)) { - remove(); + this.remove(); return; } - for (int i = 0; i < density; i++) { - if (useNewParticles) { - particleEffect.display(location, spread, spread, spread, 0, 1); + for (int i = 0; i < this.density; i++) { + if (this.useNewParticles) { + this.particleEffect.display(this.location, this.spread, this.spread, this.spread, 0, 1); } else { - location.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, 0, 15); + this.location.getWorld().playEffect(this.location, Effect.MOBSPAWNER_FLAMES, 0, 15); } } - location.add(direction.normalize().multiply(speed)); - if (initialLocation.distanceSquared(location) > distance * distance) { - remove(); + if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { + this.remove(); + return; + } + + this.location.add(this.direction.normalize().multiply(this.speed)); + if (this.initialLocation.distanceSquared(this.location) > this.distance * this.distance) { + this.remove(); return; - } else if (collides && checkCollisionCounter % checkCollisionDelay == 0) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { - if (entity instanceof LivingEntity && !entity.equals(coreAbility.getPlayer()) && !entity.isDead()) { - collision((LivingEntity) entity, direction, coreAbility); + } else if (this.collides && this.checkCollisionCounter % this.checkCollisionDelay == 0) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { + if (entity instanceof LivingEntity && !entity.equals(this.coreAbility.getPlayer()) && !entity.isDead()) { + this.collision((LivingEntity) entity, this.direction, this.coreAbility); } } } - checkCollisionCounter++; - if (singlePoint) { - remove(); + this.checkCollisionCounter++; + if (this.singlePoint) { + this.remove(); } } - - public void collision(LivingEntity entity, Vector direction, CoreAbility coreAbility) { - if (GeneralMethods.isRegionProtectedFromBuild(player, "Blaze", entity.getLocation())) { + + public void collision(final LivingEntity entity, final Vector direction, final CoreAbility coreAbility) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, "Blaze", entity.getLocation())) { return; } entity.getLocation().getWorld().playSound(entity.getLocation(), Sound.ENTITY_VILLAGER_HURT, 0.3f, 0.3f); if (coreAbility.getName().equalsIgnoreCase("FireKick")) { - FireKick fireKick = CoreAbility.getAbility(player, FireKick.class); - + final FireKick fireKick = CoreAbility.getAbility(this.player, FireKick.class); + if (!fireKick.getAffectedEntities().contains(entity)) { fireKick.getAffectedEntities().add(entity); - DamageHandler.damageEntity(entity, damage, coreAbility); - coreAbility.remove(); + DamageHandler.damageEntity(entity, this.damage, coreAbility); } } else if (coreAbility.getName().equalsIgnoreCase("FireSpin")) { - FireSpin fireSpin = (FireSpin) CoreAbility.getAbility(player, FireSpin.class); - + final FireSpin fireSpin = CoreAbility.getAbility(this.player, FireSpin.class); + if (entity instanceof Player) { if (Commands.invincible.contains(((Player) entity).getName())) { return; @@ -128,36 +131,35 @@ public void collision(LivingEntity entity, Vector direction, CoreAbility coreAbi } if (!fireSpin.getAffectedEntities().contains(entity)) { fireSpin.getAffectedEntities().add(entity); - double newKnockback = bPlayer.isAvatarState() ? knockback + 0.5 : knockback; - DamageHandler.damageEntity(entity, damage, coreAbility); + final double newKnockback = this.bPlayer.isAvatarState() ? this.knockback + 0.5 : this.knockback; + DamageHandler.damageEntity(entity, this.damage, coreAbility); entity.setVelocity(direction.normalize().multiply(newKnockback)); - coreAbility.remove(); } } else if (coreAbility.getName().equalsIgnoreCase("JetBlaze")) { - JetBlaze jetBlaze = (JetBlaze) CoreAbility.getAbility(player, JetBlaze.class); - + final JetBlaze jetBlaze = CoreAbility.getAbility(this.player, JetBlaze.class); + if (!jetBlaze.getAffectedEntities().contains(entity)) { jetBlaze.getAffectedEntities().add(entity); - DamageHandler.damageEntity(entity, damage, coreAbility); - entity.setFireTicks((int) (fireTicks * 20)); - new FireDamageTimer(entity, player); + DamageHandler.damageEntity(entity, this.damage, coreAbility); + entity.setFireTicks((int) (this.fireTicks * 20)); + new FireDamageTimer(entity, this.player); } } else if (coreAbility.getName().equalsIgnoreCase("FireWheel")) { - FireWheel fireWheel = (FireWheel) CoreAbility.getAbility(player, FireWheel.class); - + final FireWheel fireWheel = CoreAbility.getAbility(this.player, FireWheel.class); + if (!fireWheel.getAffectedEntities().contains(entity)) { fireWheel.getAffectedEntities().add(entity); - DamageHandler.damageEntity(entity, damage, coreAbility); - entity.setFireTicks((int) (fireTicks * 20)); - new FireDamageTimer(entity, player); + DamageHandler.damageEntity(entity, this.damage, coreAbility); + entity.setFireTicks((int) (this.fireTicks * 20)); + new FireDamageTimer(entity, this.player); this.remove(); } } } - + @Override public void cancel() { - remove(); + this.remove(); } public Vector getDirection() { @@ -169,59 +171,59 @@ public Location getLocation() { } public boolean isCancelled() { - return cancelled; + return this.cancelled; } public void remove() { super.cancel(); this.cancelled = true; } - + public CoreAbility getAbility() { - return coreAbility; + return this.coreAbility; } - public void setCheckCollisionDelay(int delay) { + public void setCheckCollisionDelay(final int delay) { this.checkCollisionDelay = delay; } - public void setCollides(boolean b) { + public void setCollides(final boolean b) { this.collides = b; } - public void setCollisionRadius(double radius) { + public void setCollisionRadius(final double radius) { this.collisionRadius = radius; } - public void setDensity(int density) { + public void setDensity(final int density) { this.density = density; } - - public void setDamage(double damage) { + + public void setDamage(final double damage) { this.damage = damage; } - - public void setKnockback(double knockback) { + + public void setKnockback(final double knockback) { this.knockback = knockback; } - - public void setFireTicks(double fireTicks) { + + public void setFireTicks(final double fireTicks) { this.fireTicks = fireTicks; } - public void setParticleEffect(ParticleEffect effect) { + public void setParticleEffect(final ParticleEffect effect) { this.particleEffect = effect; } - public void setSinglePoint(boolean b) { + public void setSinglePoint(final boolean b) { this.singlePoint = b; } - public void setSpread(float spread) { + public void setSpread(final float spread) { this.spread = spread; } - public void setUseNewParticles(boolean b) { - useNewParticles = b; + public void setUseNewParticles(final boolean b) { + this.useNewParticles = b; } } diff --git a/src/com/projectkorra/projectkorra/firebending/combo/FireKick.java b/src/com/projectkorra/projectkorra/firebending/combo/FireKick.java index bd95ed803..15b2ff0c7 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/FireKick.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/FireKick.java @@ -16,6 +16,7 @@ import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.util.ClickType; public class FireKick extends FireAbility implements ComboAbility { @@ -28,10 +29,10 @@ public class FireKick extends FireAbility implements ComboAbility { private ArrayList affectedEntities; private ArrayList tasks; - public FireKick(Player player) { + public FireKick(final Player player) { super(player); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } @@ -43,13 +44,13 @@ public FireKick(Player player) { this.cooldown = getConfig().getLong("Abilities.Fire.FireKick.Cooldown"); this.speed = getConfig().getLong("Abilities.Fire.FireKick.Speed"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; - this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.Damage"); - this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.Range"); + this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireKick.Damage"); + this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireKick.Range"); } - start(); + this.start(); } @Override @@ -64,51 +65,51 @@ public boolean isCollidable() { @Override public void progress() { - for (int i = 0; i < tasks.size(); i++) { - BukkitRunnable br = tasks.get(i); + for (int i = 0; i < this.tasks.size(); i++) { + final BukkitRunnable br = this.tasks.get(i); if (br instanceof FireComboStream) { - FireComboStream fs = (FireComboStream) br; + final FireComboStream fs = (FireComboStream) br; if (fs.isCancelled()) { - tasks.remove(fs); + this.tasks.remove(fs); } } } - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (destination == null) { - if (bPlayer.isOnCooldown("FireKick") && !bPlayer.isAvatarState()) { - remove(); + if (this.destination == null) { + if (this.bPlayer.isOnCooldown("FireKick") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - bPlayer.addCooldown("FireKick", cooldown); - Vector eyeDir = player.getEyeLocation().getDirection().normalize().multiply(range); - destination = player.getEyeLocation().add(eyeDir); + this.bPlayer.addCooldown("FireKick", this.cooldown); + final Vector eyeDir = this.player.getEyeLocation().getDirection().normalize().multiply(this.range); + this.destination = this.player.getEyeLocation().add(eyeDir); - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_HORSE_JUMP, 0.5f, 0f); - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 0.5f, 1f); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_HORSE_JUMP, 0.5f, 0f); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 0.5f, 1f); for (int i = -30; i <= 30; i += 5) { - Vector vec = GeneralMethods.getDirection(player.getLocation(), destination.clone()); + Vector vec = GeneralMethods.getDirection(this.player.getLocation(), this.destination.clone()); vec = GeneralMethods.rotateXZ(vec, i); - FireComboStream fs = new FireComboStream(player, this, vec, player.getLocation(), range, speed); + final FireComboStream fs = new FireComboStream(this.player, this, vec, this.player.getLocation(), this.range, this.speed); fs.setSpread(0.2F); fs.setDensity(5); fs.setUseNewParticles(true); - fs.setDamage(damage); - if (tasks.size() % 3 != 0) { + fs.setDamage(this.damage); + if (this.tasks.size() % 3 != 0) { fs.setCollides(false); } fs.runTaskTimer(ProjectKorra.plugin, 0, 1L); - tasks.add(fs); - player.getWorld().playSound(player.getLocation(), Sound.ITEM_FLINTANDSTEEL_USE, 0.5f, 1f); + this.tasks.add(fs); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ITEM_FLINTANDSTEEL_USE, 0.5f, 1f); } - } else if (tasks.size() == 0) { - remove(); + } else if (this.tasks.size() == 0) { + this.remove(); return; } @@ -117,22 +118,21 @@ public void progress() { @Override public void remove() { super.remove(); - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { if (collision.isRemovingFirst()) { - ArrayList newTasks = new ArrayList<>(); - double collisionDistanceSquared = Math.pow(getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); + final ArrayList newTasks = new ArrayList<>(); + final double collisionDistanceSquared = Math.pow(this.getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); // Remove all of the streams that are by this specific ourLocation. - // Don't just do a single stream at a time or this algorithm becomes O(n^2) with - // Collision's detection algorithm. - for (BukkitRunnable task : getTasks()) { + // Don't just do a single stream at a time or this algorithm becomes O(n^2) with Collision's detection algorithm. + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; if (stream.getLocation().distanceSquared(collision.getLocationSecond()) > collisionDistanceSquared) { newTasks.add(stream); } else { @@ -142,16 +142,16 @@ public void handleCollision(Collision collision) { newTasks.add(task); } } - setTasks(newTasks); + this.setTasks(newTasks); } } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (BukkitRunnable task : getTasks()) { + final ArrayList locations = new ArrayList<>(); + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; locations.add(stream.getLocation()); } } @@ -170,33 +170,43 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public Location getLocation() { - return location; + return this.location; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new FireKick(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList fireKick = new ArrayList<>(); + fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); + fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); + fireKick.add(new AbilityInformation("FireBlast", ClickType.SHIFT_DOWN)); + fireKick.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); + return fireKick; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setTasks(ArrayList tasks) { + public void setTasks(final ArrayList tasks) { this.tasks = tasks; } -} \ No newline at end of file + + @Override + public String getInstructions() { + return "FireBlast > FireBlast > (Hold sneak) > FireBlast"; + } +} diff --git a/src/com/projectkorra/projectkorra/firebending/combo/FireSpin.java b/src/com/projectkorra/projectkorra/firebending/combo/FireSpin.java index 76433898a..211604798 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/FireSpin.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/FireSpin.java @@ -17,6 +17,7 @@ import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.util.Collision; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.util.ClickType; public class FireSpin extends FireAbility implements ComboAbility { @@ -28,15 +29,15 @@ public class FireSpin extends FireAbility implements ComboAbility { private Location destination; private ArrayList affectedEntities; private ArrayList tasks; - - public FireSpin(Player player) { + + public FireSpin(final Player player) { super(player); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - - if (player.getLocation().getBlock().getType() == Material.WATER || player.getLocation().getBlock().getType() == Material.STATIONARY_WATER){ + + if (player.getLocation().getBlock().getType() == Material.WATER || player.getLocation().getBlock().getType() == Material.STATIONARY_WATER) { return; } @@ -49,86 +50,85 @@ public FireSpin(Player player) { this.knockback = getConfig().getDouble("Abilities.Fire.FireSpin.Knockback"); this.speed = getConfig().getDouble("Abilities.Fire.FireSpin.Speed"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireSpin.Damage"); this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireSpin.Range"); this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireSpin.Knockback"); } - - start(); + + this.start(); } @Override public void progress() { - for (int i = 0; i < tasks.size(); i++) { - BukkitRunnable br = tasks.get(i); + for (int i = 0; i < this.tasks.size(); i++) { + final BukkitRunnable br = this.tasks.get(i); if (br instanceof FireComboStream) { - FireComboStream fs = (FireComboStream) br; + final FireComboStream fs = (FireComboStream) br; if (fs.isCancelled()) { - tasks.remove(fs); + this.tasks.remove(fs); } } } - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - - if (destination == null) { - if (bPlayer.isOnCooldown("FireSpin") && !bPlayer.isAvatarState()) { - remove(); + + if (this.destination == null) { + if (this.bPlayer.isOnCooldown("FireSpin") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - bPlayer.addCooldown("FireSpin", cooldown); - destination = player.getEyeLocation().add(range, 0, range); - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 0.5f, 0.5f); + this.bPlayer.addCooldown("FireSpin", this.cooldown); + this.destination = this.player.getEyeLocation().add(this.range, 0, this.range); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 0.5f, 0.5f); for (int i = 0; i <= 360; i += 5) { - Vector vec = GeneralMethods.getDirection(player.getLocation(), destination.clone()); + Vector vec = GeneralMethods.getDirection(this.player.getLocation(), this.destination.clone()); vec = GeneralMethods.rotateXZ(vec, i - 180); vec.setY(0); - FireComboStream fs = new FireComboStream(player, this, vec, player.getLocation().clone().add(0, 1, 0), range, speed); + final FireComboStream fs = new FireComboStream(this.player, this, vec, this.player.getLocation().clone().add(0, 1, 0), this.range, this.speed); fs.setSpread(0.0F); fs.setDensity(1); fs.setUseNewParticles(true); - fs.setDamage(damage); - fs.setKnockback(knockback); - if (tasks.size() % 10 != 0) { + fs.setDamage(this.damage); + fs.setKnockback(this.knockback); + if (this.tasks.size() % 10 != 0) { fs.setCollides(false); } fs.runTaskTimer(ProjectKorra.plugin, 0, 1L); - tasks.add(fs); + this.tasks.add(fs); } } - if (tasks.size() == 0) { - remove(); + if (this.tasks.size() == 0) { + this.remove(); return; } } - + @Override public void remove() { super.remove(); - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } - + @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { if (collision.isRemovingFirst()) { - ArrayList newTasks = new ArrayList<>(); - double collisionDistanceSquared = Math.pow(getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); + final ArrayList newTasks = new ArrayList<>(); + final double collisionDistanceSquared = Math.pow(this.getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); // Remove all of the streams that are by this specific ourLocation. - // Don't just do a single stream at a time or this algorithm becomes O(n^2) with - // Collision's detection algorithm. - for (BukkitRunnable task : getTasks()) { + // Don't just do a single stream at a time or this algorithm becomes O(n^2) with Collision's detection algorithm. + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; if (stream.getLocation().distanceSquared(collision.getLocationSecond()) > collisionDistanceSquared) { newTasks.add(stream); } else { @@ -138,30 +138,36 @@ public void handleCollision(Collision collision) { newTasks.add(task); } } - setTasks(newTasks); + this.setTasks(newTasks); } } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (BukkitRunnable task : getTasks()) { + final ArrayList locations = new ArrayList<>(); + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; locations.add(stream.getLocation()); } } return locations; } - + @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new FireSpin(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList fireSpin = new ArrayList<>(); + fireSpin.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); + fireSpin.add(new AbilityInformation("FireBlast", ClickType.LEFT_CLICK)); + fireSpin.add(new AbilityInformation("FireShield", ClickType.LEFT_CLICK)); + fireSpin.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); + fireSpin.add(new AbilityInformation("FireShield", ClickType.SHIFT_UP)); + return fireSpin; } @Override @@ -171,7 +177,7 @@ public boolean isSneakAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -181,7 +187,7 @@ public String getName() { @Override public Location getLocation() { - return player.getLocation(); + return this.player.getLocation(); } @Override @@ -190,14 +196,19 @@ public boolean isHarmlessAbility() { } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } - + public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setTasks(ArrayList tasks) { + public void setTasks(final ArrayList tasks) { this.tasks = tasks; } -} \ No newline at end of file + + @Override + public String getInstructions() { + return "FireBlast > FireBlast > FireShield (Left Click) > FireShield (Tap Shift)"; + } +} diff --git a/src/com/projectkorra/projectkorra/firebending/combo/FireWheel.java b/src/com/projectkorra/projectkorra/firebending/combo/FireWheel.java index a68221bfd..88cb82558 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/FireWheel.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/FireWheel.java @@ -18,6 +18,7 @@ import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.firebending.util.FireDamageTimer; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.DamageHandler; import com.projectkorra.projectkorra.util.ParticleEffect; @@ -29,114 +30,129 @@ public class FireWheel extends FireAbility implements ComboAbility { private long cooldown; private double range; private int height; - private double radius; + private int radius; private double speed; private double fireTicks; private double damage; private ArrayList affectedEntities; - public FireWheel(Player player) { + public FireWheel(final Player player) { super(player); - - if (bPlayer.isOnCooldown("FireWheel") && !bPlayer.isAvatarState()) { - remove(); + + if (this.bPlayer.isOnCooldown("FireWheel") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - + this.damage = getConfig().getDouble("Abilities.Fire.FireWheel.Damage"); this.range = getConfig().getDouble("Abilities.Fire.FireWheel.Range"); this.speed = getConfig().getDouble("Abilities.Fire.FireWheel.Speed"); this.cooldown = getConfig().getLong("Abilities.Fire.FireWheel.Cooldown"); this.fireTicks = getConfig().getDouble("Abilities.Fire.FireWheel.FireTicks"); this.height = getConfig().getInt("Abilities.Fire.FireWheel.Height"); - this.radius = getConfig().getDouble("Abilities.Fire.FireWheel.Radius"); - - bPlayer.addCooldown(this); - origin = player.getLocation(); - affectedEntities = new ArrayList(); + + this.bPlayer.addCooldown(this); + this.affectedEntities = new ArrayList(); if (GeneralMethods.getTopBlock(player.getLocation(), 3, 3) == null) { - remove(); + this.remove(); return; } - location = player.getLocation().clone(); - location.setPitch(0); - direction = location.getDirection().clone().normalize(); - direction.setY(0); - - if (bPlayer.isAvatarState()) { + this.location = player.getLocation().clone(); + this.location.setPitch(0); + this.direction = this.location.getDirection().clone().normalize(); + this.direction.setY(0); + + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireWheel.Damage"); this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireWheel.Range"); this.speed = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireWheel.Speed"); this.fireTicks = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireWheel.FireTicks"); this.height = getConfig().getInt("Abilities.Avatar.AvatarState.Fire.FireWheel.Height"); - this.radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.FireWheel.Radius"); } - - start(); + + this.radius = this.height - 1; + this.origin = player.getLocation().clone().add(0, this.radius, 0); + + this.start(); } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new FireWheel(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList fireWheel = new ArrayList<>(); + fireWheel.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); + fireWheel.add(new AbilityInformation("FireShield", ClickType.RIGHT_CLICK_BLOCK)); + fireWheel.add(new AbilityInformation("FireShield", ClickType.RIGHT_CLICK_BLOCK)); + fireWheel.add(new AbilityInformation("Blaze", ClickType.SHIFT_UP)); + return fireWheel; } @Override public void progress() { - if (location.distanceSquared(origin) > range * range) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this) || GeneralMethods.isRegionProtectedFromBuild(this.player, this.location)) { + this.remove(); + return; + } + if (this.location.distanceSquared(this.origin) > this.range * this.range) { + this.remove(); return; } - Block topBlock = GeneralMethods.getTopBlock(location, 2, 4); + Block topBlock = GeneralMethods.getTopBlock(this.location, this.radius, this.radius + 2); if (topBlock.getType().equals(Material.SNOW)) { topBlock.breakNaturally(); topBlock = topBlock.getRelative(BlockFace.DOWN); } if (topBlock == null || isWater(topBlock)) { - remove(); + this.remove(); return; } else if (topBlock.getType() == Material.FIRE) { topBlock = topBlock.getRelative(BlockFace.DOWN); } else if (ElementalAbility.isPlant(topBlock)) { topBlock.breakNaturally(); topBlock = topBlock.getRelative(BlockFace.DOWN); + } else if (topBlock.getType() == Material.AIR) { + this.remove(); + return; + } else if (GeneralMethods.isSolid(topBlock.getRelative(BlockFace.UP)) || isWater(topBlock.getRelative(BlockFace.UP))) { + this.remove(); + return; } - location.setY(topBlock.getY() + height); + this.location.setY(topBlock.getY() + this.height); for (double i = -180; i <= 180; i += 3) { - Location tempLoc = location.clone(); - Vector newDir = direction.clone().multiply(radius * Math.cos(Math.toRadians(i))); + final Location tempLoc = this.location.clone(); + final Vector newDir = this.direction.clone().multiply(this.radius * Math.cos(Math.toRadians(i))); tempLoc.add(newDir); - tempLoc.setY(tempLoc.getY() + (radius * Math.sin(Math.toRadians(i)))); + tempLoc.setY(tempLoc.getY() + (this.radius * Math.sin(Math.toRadians(i)))); ParticleEffect.FLAME.display(tempLoc, 0, 0, 0, 0, 1); } - - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 1.5)) { - if (entity instanceof LivingEntity && !entity.equals(player)) { - if (!affectedEntities.contains(entity)) { - affectedEntities.add((LivingEntity) entity); - DamageHandler.damageEntity(entity, damage, this); - entity.setFireTicks((int) (fireTicks * 20)); - new FireDamageTimer(entity, player); + + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.radius + 0.5)) { + if (entity instanceof LivingEntity && !entity.equals(this.player)) { + if (!this.affectedEntities.contains(entity)) { + this.affectedEntities.add((LivingEntity) entity); + DamageHandler.damageEntity(entity, this.damage, this); + entity.setFireTicks((int) (this.fireTicks * 20)); + new FireDamageTimer(entity, this.player); } } } - location = location.add(direction.clone().multiply(speed)); - location.getWorld().playSound(location, Sound.BLOCK_FIRE_AMBIENT, 1, 1); + this.location = this.location.add(this.direction.clone().multiply(this.speed)); + this.location.getWorld().playSound(this.location, Sound.BLOCK_FIRE_AMBIENT, 1, 1); } - + @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -146,7 +162,7 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override @@ -160,6 +176,11 @@ public boolean isHarmlessAbility() { } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; + } + + @Override + public String getInstructions() { + return "FireShield (Hold Shift) > Right Click a block in front of you twice > Switch to Blaze > Release Shift"; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java b/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java index e5c6b0303..e4fb78877 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java @@ -11,6 +11,7 @@ import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.firebending.FireJet; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.ParticleEffect; public class JetBlast extends FireAbility implements ComboAbility { @@ -21,11 +22,11 @@ public class JetBlast extends FireAbility implements ComboAbility { private double speed; private ArrayList tasks; private long duration; - - public JetBlast(Player player) { + + public JetBlast(final Player player) { super(player); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } @@ -37,53 +38,61 @@ public JetBlast(Player player) { this.cooldown = getConfig().getLong("Abilities.Fire.JetBlast.Cooldown"); this.duration = getConfig().getLong("Abilities.Fire.JetBlast.Duration"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; } - - start(); + + this.start(); } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new JetBlast(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList jetBlast = new ArrayList<>(); + jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); + jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); + jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); + jetBlast.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); + jetBlast.add(new AbilityInformation("FireShield", ClickType.SHIFT_DOWN)); + jetBlast.add(new AbilityInformation("FireShield", ClickType.SHIFT_UP)); + jetBlast.add(new AbilityInformation("FireJet", ClickType.LEFT_CLICK)); + return jetBlast; } @Override public void progress() { - if (System.currentTimeMillis() - time > duration) { - remove(); + if (System.currentTimeMillis() - this.time > this.duration) { + this.remove(); return; - } else if (hasAbility(player, FireJet.class)) { - if (firstTime) { - if (bPlayer.isOnCooldown("JetBlast") && !bPlayer.isAvatarState()) { - remove(); + } else if (hasAbility(this.player, FireJet.class)) { + if (this.firstTime) { + if (this.bPlayer.isOnCooldown("JetBlast") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - bPlayer.addCooldown("JetBlast", cooldown); - firstTime = false; - float spread = 0F; - ParticleEffect.LARGE_EXPLODE.display(player.getLocation(), spread, spread, spread, 0, 1); - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 15, 0F); + this.bPlayer.addCooldown("JetBlast", this.cooldown); + this.firstTime = false; + final float spread = 0F; + ParticleEffect.LARGE_EXPLODE.display(this.player.getLocation(), spread, spread, spread, 0, 1); + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 15, 0F); } - FireJet fj = getAbility(player, FireJet.class); - fj.setSpeed(speed); - fj.setDuration(duration); - - FireComboStream fs = new FireComboStream(player, this, player.getVelocity().clone().multiply(-1), player.getLocation(), 3, 0.5); + final FireJet fj = getAbility(this.player, FireJet.class); + fj.setSpeed(this.speed); + fj.setDuration(this.duration); + + final FireComboStream fs = new FireComboStream(this.player, this, this.player.getVelocity().clone().multiply(-1), this.player.getLocation(), 3, 0.5); fs.setDensity(1); fs.setSpread(0.9F); fs.setUseNewParticles(true); fs.setCollides(false); fs.runTaskTimer(ProjectKorra.plugin, 0, 1L); - tasks.add(fs); + this.tasks.add(fs); } } @@ -94,7 +103,7 @@ public boolean isSneakAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -104,7 +113,7 @@ public String getName() { @Override public Location getLocation() { - return player.getLocation(); + return this.player.getLocation(); } @Override @@ -112,4 +121,9 @@ public boolean isHarmlessAbility() { return false; } -} \ No newline at end of file + @Override + public String getInstructions() { + return "FireJet (Tap Shift) > FireJet (Tap Shift) > FireShield (Tap Shift) > FireJet"; + } + +} diff --git a/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java b/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java index a13c11545..24af5e5d4 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java @@ -13,6 +13,7 @@ import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; import com.projectkorra.projectkorra.firebending.FireJet; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.ParticleEffect; public class JetBlaze extends FireAbility implements ComboAbility { @@ -28,11 +29,11 @@ public class JetBlaze extends FireAbility implements ComboAbility { private ArrayList affectedEntities; private ArrayList tasks; private long duration; - - public JetBlaze(Player player) { + + public JetBlaze(final Player player) { super(player); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } @@ -46,56 +47,64 @@ public JetBlaze(Player player) { this.speed = getConfig().getDouble("Abilities.Fire.JetBlaze.Speed"); this.cooldown = getConfig().getLong("Abilities.Fire.JetBlaze.Cooldown"); this.fireTicks = getConfig().getDouble("Abilities.Fire.JetBlaze.FireTicks"); - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.JetBlaze.Damage"); this.fireTicks = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.JetBlaze.FireTicks"); } - - start(); + + this.start(); } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new JetBlaze(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList jetBlaze = new ArrayList<>(); + jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); + jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); + jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_DOWN)); + jetBlaze.add(new AbilityInformation("FireJet", ClickType.SHIFT_UP)); + jetBlaze.add(new AbilityInformation("Blaze", ClickType.SHIFT_DOWN)); + jetBlaze.add(new AbilityInformation("Blaze", ClickType.SHIFT_UP)); + jetBlaze.add(new AbilityInformation("FireJet", ClickType.LEFT_CLICK)); + return jetBlaze; } @Override public void progress() { - if (firstTime) { - if (bPlayer.isOnCooldown("JetBlaze") && !bPlayer.isAvatarState()) { - remove(); + if (this.firstTime) { + if (this.bPlayer.isOnCooldown("JetBlaze") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - bPlayer.addCooldown("JetBlaze", cooldown); - firstTime = false; - } else if (System.currentTimeMillis() - time > duration) { - remove(); + this.bPlayer.addCooldown("JetBlaze", this.cooldown); + this.firstTime = false; + } else if (System.currentTimeMillis() - this.time > this.duration) { + this.remove(); return; - } else if (hasAbility(player, FireJet.class)) { - direction = player.getVelocity().clone().multiply(-1); - FireJet fj = getAbility(player, FireJet.class); - fj.setSpeed(speed); - fj.setDuration(duration); + } else if (hasAbility(this.player, FireJet.class)) { + this.direction = this.player.getVelocity().clone().multiply(-1); + final FireJet fj = getAbility(this.player, FireJet.class); + fj.setSpeed(this.speed); + fj.setDuration(this.duration); - FireComboStream fs = new FireComboStream(player, this, direction, player.getLocation(), 5, 1); + final FireComboStream fs = new FireComboStream(this.player, this, this.direction, this.player.getLocation(), 5, 1); fs.setDensity(8); fs.setSpread(1.0F); fs.setUseNewParticles(true); fs.setCollisionRadius(3); fs.setParticleEffect(ParticleEffect.LARGE_SMOKE); - fs.setDamage(damage); - fs.setFireTicks(fireTicks); + fs.setDamage(this.damage); + fs.setFireTicks(this.fireTicks); fs.runTaskTimer(ProjectKorra.plugin, 0, 1L); - tasks.add(fs); - if (progressCounter % 4 == 0) { - player.getWorld().playSound(player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 1, 0F); + this.tasks.add(fs); + if (this.progressCounter % 4 == 0) { + this.player.getWorld().playSound(this.player.getLocation(), Sound.ENTITY_CREEPER_PRIMED, 1, 0F); } } } @@ -107,7 +116,7 @@ public boolean isSneakAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -117,15 +126,20 @@ public String getName() { @Override public Location getLocation() { - return player.getLocation(); + return this.player.getLocation(); } @Override public boolean isHarmlessAbility() { return false; } - + public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; + } + + @Override + public String getInstructions() { + return "FireJet (Tap Shift) > FireJet (Tap Shift) > Blaze (Tap Shift) > FireJet"; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/firebending/combustion/Combustion.java b/src/com/projectkorra/projectkorra/firebending/combustion/Combustion.java index 72b0c4bbb..00e2160f0 100644 --- a/src/com/projectkorra/projectkorra/firebending/combustion/Combustion.java +++ b/src/com/projectkorra/projectkorra/firebending/combustion/Combustion.java @@ -1,5 +1,13 @@ package com.projectkorra.projectkorra.firebending.combustion; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.AirAbility; @@ -9,14 +17,6 @@ import com.projectkorra.projectkorra.util.DamageHandler; import com.projectkorra.projectkorra.util.ParticleEffect; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - public class Combustion extends CombustionAbility { private static final int MAX_TICKS = 10000; @@ -34,10 +34,10 @@ public class Combustion extends CombustionAbility { private Location origin; private Vector direction; - public Combustion(Player player) { + public Combustion(final Player player) { super(player); - if (hasAbility(player, Combustion.class) || !bPlayer.canBend(this)) { + if (hasAbility(player, Combustion.class) || !this.bPlayer.canBend(this)) { return; } @@ -51,26 +51,26 @@ public Combustion(Player player) { this.range = getConfig().getDouble("Abilities.Fire.Combustion.Range"); this.origin = player.getEyeLocation(); this.direction = player.getEyeLocation().getDirection().normalize(); - this.location = origin.clone(); + this.location = this.origin.clone(); - if (bPlayer.isAvatarState()) { - range = AvatarState.getValue(range); - damage = AvatarState.getValue(damage); + if (this.bPlayer.isAvatarState()) { + this.range = AvatarState.getValue(this.range); + this.damage = AvatarState.getValue(this.damage); } else if (isDay(player.getWorld())) { - range = getDayFactor(range); - damage = getDayFactor(damage); + this.range = this.getDayFactor(this.range); + this.damage = this.getDayFactor(this.damage); } - if (GeneralMethods.isRegionProtectedFromBuild(this, GeneralMethods.getTargetedLocation(player, range))) { + if (GeneralMethods.isRegionProtectedFromBuild(this, GeneralMethods.getTargetedLocation(player, this.range))) { return; } - start(); - bPlayer.addCooldown(this); + this.start(); + this.bPlayer.addCooldown(this); } - public static void explode(Player player) { - Combustion combustion = getAbility(player, Combustion.class); + public static void explode(final Player player) { + final Combustion combustion = getAbility(player, Combustion.class); if (combustion != null) { combustion.createExplosion(combustion.location, combustion.power, combustion.breakBlocks); ParticleEffect.EXPLODE.display(combustion.location, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 3); @@ -82,8 +82,8 @@ public static void explode(Player player) { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeAroundPoint(Location loc, double radius) { - for (Combustion combustion : getAbilities(Combustion.class)) { + public static boolean removeAroundPoint(final Location loc, final double radius) { + for (final Combustion combustion : getAbilities(Combustion.class)) { if (combustion.location.getWorld().equals(loc.getWorld())) { if (combustion.location.distanceSquared(loc) <= radius * radius) { explode(combustion.getPlayer()); @@ -96,62 +96,62 @@ public static boolean removeAroundPoint(Location loc, double radius) { } private void advanceLocation() { - ParticleEffect.FIREWORKS_SPARK.display(location, (float) Math.random() / 2, (float) Math.random() / 2, (float) Math.random() / 2, 0, 5); - ParticleEffect.FLAME.display(location, (float) Math.random() / 2, (float) Math.random() / 2, (float) Math.random() / 2, 0, 2); - playCombustionSound(location); - location = location.add(direction.clone().multiply(speedFactor)); + ParticleEffect.FIREWORKS_SPARK.display(this.location, (float) Math.random() / 2, (float) Math.random() / 2, (float) Math.random() / 2, 0, 5); + ParticleEffect.FLAME.display(this.location, (float) Math.random() / 2, (float) Math.random() / 2, (float) Math.random() / 2, 0, 2); + playCombustionSound(this.location); + this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); } - private void createExplosion(Location block, float power, boolean canBreakBlocks) { + private void createExplosion(final Location block, final float power, final boolean canBreakBlocks) { if (canFireGrief()) { block.getWorld().createExplosion(block.getX(), block.getY(), block.getZ(), power, true, canBreakBlocks); } - for (Entity entity : block.getWorld().getEntities()) { + for (final Entity entity : block.getWorld().getEntities()) { if (entity instanceof LivingEntity) { - if (entity.getLocation().distanceSquared(block) < radius * radius) { // They are close enough to the explosion. - DamageHandler.damageEntity((LivingEntity) entity, damage, this); + if (entity.getLocation().distanceSquared(block) < this.radius * this.radius) { // They are close enough to the explosion. + DamageHandler.damageEntity(entity, this.damage, this); AirAbility.breakBreathbendingHold(entity); } } } - remove(); + this.remove(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; - } else if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); return; } - speedFactor = speed * (ProjectKorra.time_step / 1000.0); - ticks++; - if (ticks > MAX_TICKS) { - remove(); + this.speedFactor = this.speed * (ProjectKorra.time_step / 1000.0); + this.ticks++; + if (this.ticks > MAX_TICKS) { + this.remove(); return; - } else if (location.distanceSquared(origin) > range * range) { - remove(); + } else if (this.location.distanceSquared(this.origin) > this.range * this.range) { + this.remove(); return; } - Block block = location.getBlock(); + final Block block = this.location.getBlock(); if (block != null) { if (block.getType() != Material.AIR && !isWater(block)) { - createExplosion(block.getLocation(), power, breakBlocks); + this.createExplosion(block.getLocation(), this.power, this.breakBlocks); } } - for (Entity entity : location.getWorld().getEntities()) { + for (final Entity entity : this.location.getWorld().getEntities()) { if (entity instanceof LivingEntity) { - if (entity.getLocation().distanceSquared(location) <= 4 && !entity.equals(player)) { - createExplosion(location, power, breakBlocks); + if (entity.getLocation().distanceSquared(this.location) <= 4 && !entity.equals(this.player)) { + this.createExplosion(this.location, this.power, this.breakBlocks); } } } - advanceLocation(); + this.advanceLocation(); } @Override @@ -161,15 +161,15 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; + if (this.location != null) { + return this.location; } - return origin; + return this.origin; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -184,86 +184,86 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public boolean isBreakBlocks() { - return breakBlocks; + return this.breakBlocks; } - public void setBreakBlocks(boolean breakBlocks) { + public void setBreakBlocks(final boolean breakBlocks) { this.breakBlocks = breakBlocks; } public int getTicks() { - return ticks; + return this.ticks; } - public void setTicks(int ticks) { + public void setTicks(final int ticks) { this.ticks = ticks; } public float getPower() { - return power; + return this.power; } - public void setPower(float power) { + public void setPower(final float power) { this.power = power; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getSpeedFactor() { - return speedFactor; + return this.speedFactor; } - public void setSpeedFactor(double speedFactor) { + public void setSpeedFactor(final double speedFactor) { this.speedFactor = speedFactor; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } @@ -271,11 +271,11 @@ public static long getMaxTicks() { return MAX_TICKS; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java b/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java index 8ce360d9a..86c1c3373 100644 --- a/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java +++ b/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java @@ -55,10 +55,10 @@ public static enum State { private ArrayList tasks; private ArrayList locations; - public Lightning(Player player) { + public Lightning(final Player player) { super(player); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } if (hasAbility(player, Lightning.class)) { @@ -94,17 +94,17 @@ public Lightning(Player player) { this.chargeTime = getConfig().getLong("Abilities.Fire.Lightning.ChargeTime"); this.cooldown = getConfig().getLong("Abilities.Fire.Lightning.Cooldown"); - this.range = getDayFactor(this.range); - this.subArcChance = getDayFactor(this.subArcChance); - this.damage = getDayFactor(this.damage); - this.maxChainArcs = getDayFactor(this.maxChainArcs); - this.chainArcChance = getDayFactor(this.chainArcChance); - this.chainRange = getDayFactor(this.chainRange); - this.waterArcRange = getDayFactor(this.waterArcRange); - this.stunChance = getDayFactor(this.stunChance); - this.stunDuration = getDayFactor(this.stunDuration); - - if (bPlayer.isAvatarState()) { + this.range = this.getDayFactor(this.range); + this.subArcChance = this.getDayFactor(this.subArcChance); + this.damage = this.getDayFactor(this.damage); + this.maxChainArcs = this.getDayFactor(this.maxChainArcs); + this.chainArcChance = this.getDayFactor(this.chainArcChance); + this.chainRange = this.getDayFactor(this.chainRange); + this.waterArcRange = this.getDayFactor(this.waterArcRange); + this.stunChance = this.getDayFactor(this.stunChance); + this.stunDuration = this.getDayFactor(this.stunDuration); + + if (this.bPlayer.isAvatarState()) { this.chargeTime = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.Lightning.ChargeTime"); this.cooldown = getConfig().getLong("Abilities.Avatar.AvatarState.Fire.Lightning.Cooldown"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Fire.Lightning.Damage"); @@ -113,39 +113,39 @@ public Lightning(Player player) { this.chargeTime = 0; this.cooldown = 0; } - start(); + this.start(); } /** * Damages an entity, and may cause paralysis depending on the config. - * + * * @param lent The LivingEntity that is being damaged */ - public void electrocute(LivingEntity lent) { + public void electrocute(final LivingEntity lent) { playLightningbendingSound(lent.getLocation()); - playLightningbendingSound(player.getLocation()); - DamageHandler.damageEntity(lent, damage, this); + playLightningbendingSound(this.player.getLocation()); + DamageHandler.damageEntity(lent, this.damage, this); - if (Math.random() <= stunChance) { - MovementHandler mh = new MovementHandler(lent); - mh.stop((long) stunDuration, Element.LIGHTNING.getColor() + "* Electrocuted *"); + if (Math.random() <= this.stunChance) { + final MovementHandler mh = new MovementHandler(lent, this); + mh.stopWithDuration((long) this.stunDuration, Element.LIGHTNING.getColor() + "* Electrocuted *"); } } /** * Checks if a block is transparent, also considers the ARC_ON_ICE config * option. - * + * * @param player the player that is viewing the block * @param block the block * @return true if the block is transparent */ - private boolean isTransparentForLightning(Player player, Block block) { - if (isTransparent(block)) { + private boolean isTransparentForLightning(final Player player, final Block block) { + if (this.isTransparent(block)) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return false; } else if (isIce(block)) { - return arcOnIce; + return this.arcOnIce; } else { return true; } @@ -157,99 +157,99 @@ private boolean isTransparentForLightning(Player player, Block block) { * Progresses the instance of this ability by 1 tick. This is the heart of * the ability, it checks if it needs to remove itself, and handles the * initial Lightning Arc generation. - * + * * Once all of the arcs have been created then this ability instance gets * removed, but the BukkitRunnables continue until they remove themselves. **/ @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - removeWithTasks(); + if (this.player.isDead() || !this.player.isOnline()) { + this.removeWithTasks(); return; - } else if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + } else if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - locations.clear(); + this.locations.clear(); - if (state == State.START) { - if (bPlayer.isOnCooldown(this)) { - remove(); + if (this.state == State.START) { + if (this.bPlayer.isOnCooldown(this)) { + this.remove(); return; - } else if (System.currentTimeMillis() - time > chargeTime) { - charged = true; + } else if (System.currentTimeMillis() - this.time > this.chargeTime) { + this.charged = true; } - if (charged) { - if (player.isSneaking()) { - Location loc = player.getEyeLocation().add(player.getEyeLocation().getDirection().normalize().multiply(1.2)); + if (this.charged) { + if (this.player.isSneaking()) { + final Location loc = this.player.getEyeLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(1.2)); loc.add(0, 0.3, 0); playLightningbendingParticle(loc, 0.2F, 0.2F, 0.2F); } else { - state = State.MAINBOLT; - bPlayer.addCooldown(this); - Entity target = GeneralMethods.getTargetedEntity(player, range); - origin = player.getEyeLocation(); + this.state = State.MAINBOLT; + this.bPlayer.addCooldown(this); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range); + this.origin = this.player.getEyeLocation(); if (target != null) { - destination = target.getLocation(); + this.destination = target.getLocation(); } else { - destination = player.getEyeLocation().add(player.getEyeLocation().getDirection().normalize().multiply(range)); + this.destination = this.player.getEyeLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(this.range)); } } } else { - if (!player.isSneaking()) { - remove(); + if (!this.player.isSneaking()) { + this.remove(); return; } - Location localLocation1 = player.getLocation(); - double d1 = 0.1570796326794897D; - double d2 = 0.06283185307179587D; - double d3 = 1.0D; - double d4 = 1.0D; - double d5 = d1 * particleRotation; - double d6 = d2 * particleRotation; - double d7 = localLocation1.getX() + d4 * Math.cos(d5); - double d8 = localLocation1.getZ() + d4 * Math.sin(d5); - double newY = (localLocation1.getY() + 1.0D + d4 * Math.cos(d6)); - Location localLocation2 = new Location(player.getWorld(), d7, newY, d8); + final Location localLocation1 = this.player.getLocation(); + final double d1 = 0.1570796326794897D; + final double d2 = 0.06283185307179587D; + final double d3 = 1.0D; + final double d4 = 1.0D; + final double d5 = d1 * this.particleRotation; + final double d6 = d2 * this.particleRotation; + final double d7 = localLocation1.getX() + d4 * Math.cos(d5); + final double d8 = localLocation1.getZ() + d4 * Math.sin(d5); + final double newY = (localLocation1.getY() + 1.0D + d4 * Math.cos(d6)); + final Location localLocation2 = new Location(this.player.getWorld(), d7, newY, d8); playLightningbendingParticle(localLocation2); - particleRotation += 1.0D / d3; + this.particleRotation += 1.0D / d3; } - } else if (state == State.MAINBOLT) { - Arc mainArc = new Arc(origin, destination); + } else if (this.state == State.MAINBOLT) { + final Arc mainArc = new Arc(this.origin, this.destination); mainArc.generatePoints(POINT_GENERATION); - arcs.add(mainArc); - ArrayList subArcs = mainArc.generateArcs(subArcChance, range / 2.0, maxArcAngle); - arcs.addAll(subArcs); - state = State.STRIKE; - } else if (state == State.STRIKE) { - for (int i = 0; i < arcs.size(); i++) { - Arc arc = arcs.get(i); + this.arcs.add(mainArc); + final ArrayList subArcs = mainArc.generateArcs(this.subArcChance, this.range / 2.0, this.maxArcAngle); + this.arcs.addAll(subArcs); + this.state = State.STRIKE; + } else if (this.state == State.STRIKE) { + for (int i = 0; i < this.arcs.size(); i++) { + final Arc arc = this.arcs.get(i); for (int j = 0; j < arc.getAnimationLocations().size() - 1; j++) { final Location iterLoc = arc.getAnimationLocations().get(j).getLocation().clone(); final Location dest = arc.getAnimationLocations().get(j + 1).getLocation().clone(); - if (selfHitClose && player.getLocation().distanceSquared(iterLoc) < 9 && !isTransparentForLightning(player, iterLoc.getBlock()) && !affectedEntities.contains(player)) { - affectedEntities.add(player); - electrocute(player); + if (this.selfHitClose && this.player.getLocation().distanceSquared(iterLoc) < 9 && !this.isTransparentForLightning(this.player, iterLoc.getBlock()) && !this.affectedEntities.contains(this.player)) { + this.affectedEntities.add(this.player); + this.electrocute(this.player); } while (iterLoc.distanceSquared(dest) > 0.15 * 0.15) { - BukkitRunnable task = new LightningParticle(arc, iterLoc.clone(), selfHitWater, waterArcs); - double timer = arc.getAnimationLocations().get(j).getAnimCounter() / 2; + final BukkitRunnable task = new LightningParticle(arc, iterLoc.clone(), this.selfHitWater, this.waterArcs); + final double timer = arc.getAnimationLocations().get(j).getAnimCounter() / 2; task.runTaskTimer(ProjectKorra.plugin, (long) timer, 1); - tasks.add(task); + this.tasks.add(task); iterLoc.add(GeneralMethods.getDirection(iterLoc, dest).normalize().multiply(0.15)); } } - arcs.remove(i); + this.arcs.remove(i); i--; } - if (tasks.size() == 0) { - remove(); + if (this.tasks.size() == 0) { + this.remove(); return; } } @@ -259,11 +259,11 @@ public void progress() { * Removes the instance of this ability and cancels any current runnables */ public void removeWithTasks() { - for (int i = 0; i < tasks.size(); i++) { - tasks.get(i).cancel(); + for (int i = 0; i < this.tasks.size(); i++) { + this.tasks.get(i).cancel(); i--; } - remove(); + this.remove(); } /** @@ -275,24 +275,24 @@ public class AnimationLocation { private Location location; private int animationCounter; - public AnimationLocation(Location loc, int animationCounter) { + public AnimationLocation(final Location loc, final int animationCounter) { this.location = loc; this.animationCounter = animationCounter; } public int getAnimCounter() { - return animationCounter; + return this.animationCounter; } public Location getLocation() { - return location; + return this.location; } - public void setAnimationCounter(int animationCounter) { + public void setAnimationCounter(final int animationCounter) { this.animationCounter = animationCounter; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } } @@ -305,59 +305,59 @@ public void setLocation(Location location) { public class Arc { private int animationCounter; private Vector direction; - private ArrayList points; - private ArrayList animationLocations; - private ArrayList particles; - private ArrayList subArcs; - - public Arc(Location startPoint, Location endPoint) { - points = new ArrayList<>(); - points.add(startPoint.clone()); - points.add(endPoint.clone()); - direction = GeneralMethods.getDirection(startPoint, endPoint); - particles = new ArrayList<>(); - subArcs = new ArrayList<>(); - animationLocations = new ArrayList<>(); - animationCounter = 0; + private final ArrayList points; + private final ArrayList animationLocations; + private final ArrayList particles; + private final ArrayList subArcs; + + public Arc(final Location startPoint, final Location endPoint) { + this.points = new ArrayList<>(); + this.points.add(startPoint.clone()); + this.points.add(endPoint.clone()); + this.direction = GeneralMethods.getDirection(startPoint, endPoint); + this.particles = new ArrayList<>(); + this.subArcs = new ArrayList<>(); + this.animationLocations = new ArrayList<>(); + this.animationCounter = 0; } /** * Stops this Arc from further animating or doing damage. */ public void cancel() { - for (int i = 0; i < particles.size(); i++) { - particles.get(i).cancel(); + for (int i = 0; i < this.particles.size(); i++) { + this.particles.get(i).cancel(); } - for (Arc subArc : subArcs) { + for (final Arc subArc : this.subArcs) { subArc.cancel(); } } /** * Randomly generates subarcs off of this arc. - * + * * @param chance The chance that an arc will be generated for each * specific point in the arc. Note: if you generate a lot of * points then chance will need to be lowered. * @param range The length of each subarc. - * + * **/ - public ArrayList generateArcs(double chance, double range, double maxArcAngle) { - ArrayList arcs = new ArrayList<>(); + public ArrayList generateArcs(final double chance, final double range, final double maxArcAngle) { + final ArrayList arcs = new ArrayList<>(); - for (int i = 0; i < animationLocations.size(); i++) { + for (int i = 0; i < this.animationLocations.size(); i++) { if (Math.random() < chance) { - Location loc = animationLocations.get(i).getLocation(); - double angle = (Math.random() - 0.5) * maxArcAngle * 2; - Vector dir = GeneralMethods.rotateXZ(direction.clone(), angle); - double randRange = (Math.random() * range) + (range / 3.0); + final Location loc = this.animationLocations.get(i).getLocation(); + final double angle = (Math.random() - 0.5) * maxArcAngle * 2; + final Vector dir = GeneralMethods.rotateXZ(this.direction.clone(), angle); + final double randRange = (Math.random() * range) + (range / 3.0); - Location loc2 = loc.clone().add(dir.normalize().multiply(randRange)); - Arc arc = new Arc(loc, loc2); + final Location loc2 = loc.clone().add(dir.normalize().multiply(randRange)); + final Arc arc = new Arc(loc, loc2); - subArcs.add(arc); - arc.setAnimationCounter(animationLocations.get(i).getAnimCounter()); + this.subArcs.add(arc); + arc.setAnimationCounter(this.animationLocations.get(i).getAnimCounter()); arc.generatePoints(POINT_GENERATION); arcs.add(arc); arcs.addAll(arc.generateArcs(chance / 2.0, range / 2.0, maxArcAngle)); @@ -373,69 +373,69 @@ public ArrayList generateArcs(double chance, double range, double maxArcAng * Now that the arc is split into 3 points, we continue this processes * by generating middle points in the two halfs of this arc. This * process continues the amount of times specified. - * + * * @param times The amount of times that the arc will be split in half * causes O(n^2) complexity **/ - public void generatePoints(int times) { + public void generatePoints(final int times) { for (int i = 0; i < times; i++) { - for (int j = 0; j < points.size() - 1; j += 2) { - Location loc1 = points.get(j); - Location loc2 = points.get(j + 1); + for (int j = 0; j < this.points.size() - 1; j += 2) { + final Location loc1 = this.points.get(j); + final Location loc2 = this.points.get(j + 1); double adjac = 0; if (loc1.getWorld().equals(loc2.getWorld())) { adjac = loc1.distance(loc2) / 2; } - double angle = (Math.random() - 0.5) * maxArcAngle; + double angle = (Math.random() - 0.5) * Lightning.this.maxArcAngle; angle += angle >= 0 ? 10 : -10; - double radians = Math.toRadians(angle); - double hypot = adjac / Math.cos(radians); - Vector dir = GeneralMethods.rotateXZ(direction.clone(), angle); - Location newLoc = loc1.clone().add(dir.normalize().multiply(hypot)); + final double radians = Math.toRadians(angle); + final double hypot = adjac / Math.cos(radians); + final Vector dir = GeneralMethods.rotateXZ(this.direction.clone(), angle); + final Location newLoc = loc1.clone().add(dir.normalize().multiply(hypot)); newLoc.add(0, (Math.random() - 0.5) / 2.0, 0); - points.add(j + 1, newLoc); + this.points.add(j + 1, newLoc); } } - for (int i = 0; i < points.size(); i++) { - animationLocations.add(new AnimationLocation(points.get(i), animationCounter)); - animationCounter++; + for (int i = 0; i < this.points.size(); i++) { + this.animationLocations.add(new AnimationLocation(this.points.get(i), this.animationCounter)); + this.animationCounter++; } } public int getAnimationCounter() { - return animationCounter; + return this.animationCounter; } - public void setAnimationCounter(int animationCounter) { + public void setAnimationCounter(final int animationCounter) { this.animationCounter = animationCounter; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public ArrayList getPoints() { - return points; + return this.points; } public ArrayList getAnimationLocations() { - return animationLocations; + return this.animationLocations; } public ArrayList getParticles() { - return particles; + return this.particles; } public ArrayList getSubArcs() { - return subArcs; + return this.subArcs; } } @@ -443,7 +443,7 @@ public ArrayList getSubArcs() { /** * A Runnable Particle that continuously displays itself until it reaches a * certain time limit. - * + * * These LightningParticles do the actual checking for player collision and * handle damaging any entities. These Runnables also check to see if they * reach water, in which case they will generate subarcs to branch out. @@ -455,7 +455,7 @@ public class LightningParticle extends BukkitRunnable { private Arc arc; private Location location; - public LightningParticle(Arc arc, Location location, boolean selfHitWater, int waterArcs) { + public LightningParticle(final Arc arc, final Location location, final boolean selfHitWater, final int waterArcs) { this.arc = arc; this.location = location; this.selfHitWater = selfHitWater; @@ -467,7 +467,7 @@ public LightningParticle(Arc arc, Location location, boolean selfHitWater, int w @Override public void cancel() { super.cancel(); - tasks.remove(this); + Lightning.this.tasks.remove(this); } /** @@ -476,76 +476,72 @@ public void cancel() { */ @Override public void run() { - playLightningbendingParticle(location, 0F, 0F, 0F); - count++; - if (count > 5) { + playLightningbendingParticle(this.location, 0F, 0F, 0F); + this.count++; + if (this.count > 5) { this.cancel(); - } else if (count == 1) { - if (!isTransparentForLightning(player, location.getBlock())) { - arc.cancel(); + } else if (this.count == 1) { + if (!Lightning.this.isTransparentForLightning(Lightning.this.player, this.location.getBlock())) { + this.arc.cancel(); return; } - Block block = location.getBlock(); - // We only want to consider this particle as part of the location - // on the its first tick, when it actually does the electrocution. + final Block block = this.location.getBlock(); + // We only want to consider this particle as part of the location on the its first tick, when it actually does the electrocution. // The later ticks are just for visual purposes. - locations.add(block.getLocation()); + Lightning.this.locations.add(block.getLocation()); - // Handle Water electrocution - if (!hitWater && (isWater(block) || (arcOnIce && isIce(block)))) { - hitWater = true; + // Handle Water electrocution. + if (!Lightning.this.hitWater && (isWater(block) || (Lightning.this.arcOnIce && isIce(block)))) { + Lightning.this.hitWater = true; if (isIce(block)) { - hitIce = true; + Lightning.this.hitIce = true; } - for (int i = 0; i < waterArcs; i++) { - Location origin = location.clone(); + for (int i = 0; i < this.waterArcs; i++) { + final Location origin = this.location.clone(); origin.add(new Vector((Math.random() - 0.5) * 2, 0, (Math.random() - 0.5) * 2)); - destination = origin.clone().add(new Vector((Math.random() - 0.5) * waterArcRange, Math.random() - 0.7, (Math.random() - 0.5) * waterArcRange)); - Arc newArc = new Arc(origin, destination); + Lightning.this.destination = origin.clone().add(new Vector((Math.random() - 0.5) * Lightning.this.waterArcRange, Math.random() - 0.7, (Math.random() - 0.5) * Lightning.this.waterArcRange)); + final Arc newArc = new Arc(origin, Lightning.this.destination); newArc.generatePoints(POINT_GENERATION); - arcs.add(newArc); + Lightning.this.arcs.add(newArc); } } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2.5)) { - /* - * If the player is in water we will electrocute them only - * if they are standing in water. If the lightning hit ice - * we can electrocute them all the time. - */ - if (entity.equals(player) && !(selfHitWater && hitWater && isWater(player.getLocation().getBlock())) && !(selfHitWater && hitIce)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2.5)) { + + // If the player is in water we will electrocute them only if they are standing in water. If the lightning hit ice we can electrocute them all the time. + if (entity.equals(Lightning.this.player) && !(this.selfHitWater && Lightning.this.hitWater && isWater(Lightning.this.player.getLocation().getBlock())) && !(this.selfHitWater && Lightning.this.hitIce)) { continue; } - if (entity instanceof LivingEntity && !affectedEntities.contains(entity)) { - affectedEntities.add(entity); - LivingEntity lent = (LivingEntity) entity; + if (entity instanceof LivingEntity && !Lightning.this.affectedEntities.contains(entity)) { + Lightning.this.affectedEntities.add(entity); + final LivingEntity lent = (LivingEntity) entity; if (lent instanceof Player) { playLightningbendingSound(lent.getLocation()); - playLightningbendingSound(player.getLocation()); - Player p = (Player) lent; - Lightning light = getAbility(p, Lightning.class); + playLightningbendingSound(Lightning.this.player.getLocation()); + final Player p = (Player) lent; + final Lightning light = getAbility(p, Lightning.class); if (light != null && light.state == State.START) { light.charged = true; - remove(); + Lightning.this.remove(); return; } } - electrocute(lent); + Lightning.this.electrocute(lent); - // Handle Chain Lightning - if (maxChainArcs >= 1 && Math.random() <= chainArcChance) { - maxChainArcs--; - for (Entity ent : GeneralMethods.getEntitiesAroundPoint(lent.getLocation(), chainRange)) { - if (!ent.equals(player) && !ent.equals(lent) && ent instanceof LivingEntity && !affectedEntities.contains(ent)) { - origin = lent.getLocation().add(0, 1, 0); - destination = ent.getLocation().add(0, 1, 0); - Arc newArc = new Arc(origin, destination); + // Handle Chain Lightning. + if (Lightning.this.maxChainArcs >= 1 && Math.random() <= Lightning.this.chainArcChance) { + Lightning.this.maxChainArcs--; + for (final Entity ent : GeneralMethods.getEntitiesAroundPoint(lent.getLocation(), Lightning.this.chainRange)) { + if (!ent.equals(Lightning.this.player) && !ent.equals(lent) && ent instanceof LivingEntity && !Lightning.this.affectedEntities.contains(ent)) { + Lightning.this.origin = lent.getLocation().add(0, 1, 0); + Lightning.this.destination = ent.getLocation().add(0, 1, 0); + final Arc newArc = new Arc(Lightning.this.origin, Lightning.this.destination); newArc.generatePoints(POINT_GENERATION); - arcs.add(newArc); - cancel(); + Lightning.this.arcs.add(newArc); + this.cancel(); return; } } @@ -556,42 +552,42 @@ public void run() { } public boolean isSelfHitWater() { - return selfHitWater; + return this.selfHitWater; } - public void setSelfHitWater(boolean selfHitWater) { + public void setSelfHitWater(final boolean selfHitWater) { this.selfHitWater = selfHitWater; } public int getCount() { - return count; + return this.count; } - public void setCount(int count) { + public void setCount(final int count) { this.count = count; } public int getWaterArcs() { - return waterArcs; + return this.waterArcs; } - public void setWaterArcs(int waterArcs) { + public void setWaterArcs(final int waterArcs) { this.waterArcs = waterArcs; } public Arc getArc() { - return arc; + return this.arc; } - public void setArc(Arc arc) { + public void setArc(final Arc arc) { this.arc = arc; } public Location getLocation() { - return location; + return this.location; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } } @@ -603,12 +599,12 @@ public String getName() { @Override public Location getLocation() { - return origin; + return this.origin; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -623,195 +619,195 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return arcs.size() > 0; + return this.arcs.size() > 0; } @Override public List getLocations() { - return locations; + return this.locations; } public boolean isCharged() { - return charged; + return this.charged; } - public void setCharged(boolean charged) { + public void setCharged(final boolean charged) { this.charged = charged; } public boolean isHitWater() { - return hitWater; + return this.hitWater; } - public void setHitWater(boolean hitWater) { + public void setHitWater(final boolean hitWater) { this.hitWater = hitWater; } public boolean isHitIce() { - return hitIce; + return this.hitIce; } - public void setHitIce(boolean hitIce) { + public void setHitIce(final boolean hitIce) { this.hitIce = hitIce; } public boolean isSelfHitWater() { - return selfHitWater; + return this.selfHitWater; } - public void setSelfHitWater(boolean selfHitWater) { + public void setSelfHitWater(final boolean selfHitWater) { this.selfHitWater = selfHitWater; } public boolean isSelfHitClose() { - return selfHitClose; + return this.selfHitClose; } - public void setSelfHitClose(boolean selfHitClose) { + public void setSelfHitClose(final boolean selfHitClose) { this.selfHitClose = selfHitClose; } public boolean isArcOnIce() { - return arcOnIce; + return this.arcOnIce; } - public void setArcOnIce(boolean arcOnIce) { + public void setArcOnIce(final boolean arcOnIce) { this.arcOnIce = arcOnIce; } public int getWaterArcs() { - return waterArcs; + return this.waterArcs; } - public void setWaterArcs(int waterArcs) { + public void setWaterArcs(final int waterArcs) { this.waterArcs = waterArcs; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(double chargeTime) { + public void setChargeTime(final double chargeTime) { this.chargeTime = chargeTime; } public double getSubArcChance() { - return subArcChance; + return this.subArcChance; } - public void setSubArcChance(double subArcChance) { + public void setSubArcChance(final double subArcChance) { this.subArcChance = subArcChance; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getMaxChainArcs() { - return maxChainArcs; + return this.maxChainArcs; } - public void setMaxChainArcs(double maxChainArcs) { + public void setMaxChainArcs(final double maxChainArcs) { this.maxChainArcs = maxChainArcs; } public double getChainRange() { - return chainRange; + return this.chainRange; } - public void setChainRange(double chainRange) { + public void setChainRange(final double chainRange) { this.chainRange = chainRange; } public double getWaterArcRange() { - return waterArcRange; + return this.waterArcRange; } - public void setWaterArcRange(double waterArcRange) { + public void setWaterArcRange(final double waterArcRange) { this.waterArcRange = waterArcRange; } public double getChainArcChance() { - return chainArcChance; + return this.chainArcChance; } - public void setChainArcChance(double chainArcChance) { + public void setChainArcChance(final double chainArcChance) { this.chainArcChance = chainArcChance; } public double getStunChance() { - return stunChance; + return this.stunChance; } - public void setStunChance(double stunChance) { + public void setStunChance(final double stunChance) { this.stunChance = stunChance; } public double getStunDuration() { - return stunDuration; + return this.stunDuration; } - public void setStunDuration(double stunDuration) { + public void setStunDuration(final double stunDuration) { this.stunDuration = stunDuration; } public double getMaxArcAngle() { - return maxArcAngle; + return this.maxArcAngle; } - public void setMaxArcAngle(double maxArcAngle) { + public void setMaxArcAngle(final double maxArcAngle) { this.maxArcAngle = maxArcAngle; } public double getParticleRotation() { - return particleRotation; + return this.particleRotation; } - public void setParticleRotation(double particleRotation) { + public void setParticleRotation(final double particleRotation) { this.particleRotation = particleRotation; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public State getState() { - return state; + return this.state; } - public void setState(State state) { + public void setState(final State state) { this.state = state; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } @@ -820,18 +816,18 @@ public static int getPointGeneration() { } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getArcs() { - return arcs; + return this.arcs; } public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/firebending/passive/FirePassive.java b/src/com/projectkorra/projectkorra/firebending/passive/FirePassive.java index 100df7876..8e567fd86 100644 --- a/src/com/projectkorra/projectkorra/firebending/passive/FirePassive.java +++ b/src/com/projectkorra/projectkorra/firebending/passive/FirePassive.java @@ -1,10 +1,8 @@ package com.projectkorra.projectkorra.firebending.passive; -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.Element; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.command.Commands; import com.projectkorra.projectkorra.configuration.ConfigManager; @@ -13,19 +11,17 @@ public class FirePassive { - public static void handlePassive() { + public static void handle(final Player player) { if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { return; } - for (Player player : Bukkit.getOnlinePlayers()) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (bPlayer != null && bPlayer.canBendPassive(Element.FIRE) && bPlayer.canUsePassive(Element.FIRE)) { - if (bPlayer != null && !CoreAbility.hasAbility(player, Illumination.class) && !CoreAbility.hasAbility(player, Tremorsense.class) && bPlayer.canBendIgnoreBinds(CoreAbility.getAbility("Illumination")) && ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.Illumination.Passive")) { - if (bPlayer.isIlluminating()) { - new Illumination(player); - } + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + if (bPlayer != null && bPlayer.canBendPassive(CoreAbility.getAbility(Illumination.class)) && bPlayer.canUsePassive(CoreAbility.getAbility(Illumination.class))) { + if (bPlayer != null && !CoreAbility.hasAbility(player, Illumination.class) && !CoreAbility.hasAbility(player, Tremorsense.class) && bPlayer.canBendIgnoreBinds(CoreAbility.getAbility("Illumination")) && ConfigManager.defaultConfig.get().getBoolean("Abilities.Fire.Illumination.Passive")) { + if (bPlayer.isIlluminating()) { + new Illumination(player); } } } } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/firebending/util/FireDamageTimer.java b/src/com/projectkorra/projectkorra/firebending/util/FireDamageTimer.java index ad07d1139..8a4c4897a 100644 --- a/src/com/projectkorra/projectkorra/firebending/util/FireDamageTimer.java +++ b/src/com/projectkorra/projectkorra/firebending/util/FireDamageTimer.java @@ -1,16 +1,16 @@ package com.projectkorra.projectkorra.firebending.util; -import com.projectkorra.projectkorra.Element; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.firebending.HeatControl; -import com.projectkorra.projectkorra.util.DamageHandler; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.firebending.HeatControl; +import com.projectkorra.projectkorra.util.DamageHandler; public class FireDamageTimer { @@ -20,7 +20,7 @@ public class FireDamageTimer { private static final Map INSTANCES = new ConcurrentHashMap<>(); private static final Map TIMES = new ConcurrentHashMap<>(); - public FireDamageTimer(Entity entity, Player source) { + public FireDamageTimer(final Entity entity, final Player source) { if (entity.getEntityId() == source.getEntityId()) { return; } @@ -28,10 +28,10 @@ public FireDamageTimer(Entity entity, Player source) { INSTANCES.put(entity, source); } - public static boolean isEnflamed(Entity entity) { + public static boolean isEnflamed(final Entity entity) { if (INSTANCES.containsKey(entity)) { if (TIMES.containsKey(entity)) { - long time = TIMES.get(entity); + final long time = TIMES.get(entity); if (System.currentTimeMillis() < time + BUFFER) { return false; } @@ -43,17 +43,17 @@ public static boolean isEnflamed(Entity entity) { } } - public static void dealFlameDamage(Entity entity) { + public static void dealFlameDamage(final Entity entity) { if (INSTANCES.containsKey(entity) && entity instanceof LivingEntity) { if (entity instanceof Player) { if (!HeatControl.canBurn((Player) entity)) { return; } } - LivingEntity Lentity = (LivingEntity) entity; - Player source = INSTANCES.get(entity); + final LivingEntity Lentity = (LivingEntity) entity; + final Player source = INSTANCES.get(entity); - //damages the entity + // damages the entity. DamageHandler.damageEntity(Lentity, source, DAMAGE, CoreAbility.getAbilitiesByElement(Element.FIRE).get(0)); if (entity.getFireTicks() > MAX_TICKS) { @@ -63,7 +63,7 @@ public static void dealFlameDamage(Entity entity) { } public static void handleFlames() { - for (Entity entity : INSTANCES.keySet()) { + for (final Entity entity : INSTANCES.keySet()) { if (entity.getFireTicks() <= 0) { INSTANCES.remove(entity); } diff --git a/src/com/projectkorra/projectkorra/firebending/util/FirebendingManager.java b/src/com/projectkorra/projectkorra/firebending/util/FirebendingManager.java index 8613792a7..e62ef7d4a 100644 --- a/src/com/projectkorra/projectkorra/firebending/util/FirebendingManager.java +++ b/src/com/projectkorra/projectkorra/firebending/util/FirebendingManager.java @@ -3,20 +3,19 @@ import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.FireAbility; import com.projectkorra.projectkorra.firebending.BlazeArc; -import com.projectkorra.projectkorra.firebending.passive.FirePassive; public class FirebendingManager implements Runnable { public ProjectKorra plugin; - public FirebendingManager(ProjectKorra plugin) { + public FirebendingManager(final ProjectKorra plugin) { this.plugin = plugin; } + @Override public void run() { BlazeArc.handleDissipation(); FireDamageTimer.handleFlames(); - FirePassive.handlePassive(); BlazeArc.dissipateAll(); FireAbility.removeFire(); } diff --git a/src/com/projectkorra/projectkorra/object/HorizontalVelocityTracker.java b/src/com/projectkorra/projectkorra/object/HorizontalVelocityTracker.java index 3f5cb80f5..48d7ef8f1 100644 --- a/src/com/projectkorra/projectkorra/object/HorizontalVelocityTracker.java +++ b/src/com/projectkorra/projectkorra/object/HorizontalVelocityTracker.java @@ -16,7 +16,6 @@ import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.Ability; import com.projectkorra.projectkorra.ability.ElementalAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.event.HorizontalVelocityChangeEvent; @@ -40,59 +39,61 @@ public class HorizontalVelocityTracker { public static String[] abils = { "AirBlast", "AirBurst", "AirSuction", "Bloodbending" }; - public HorizontalVelocityTracker(Entity e, Player instigator, long delay, Ability ability) { - if (!ProjectKorra.plugin.getConfig().getBoolean("Properties.HorizontalCollisionPhysics.Enabled")) + public HorizontalVelocityTracker(final Entity e, final Player instigator, final long delay, final Ability ability) { + if (!ProjectKorra.plugin.getConfig().getBoolean("Properties.HorizontalCollisionPhysics.Enabled")) { return; + } remove(e); - entity = e; + this.entity = e; this.instigator = instigator; - fireTime = System.currentTimeMillis(); + this.fireTime = System.currentTimeMillis(); this.delay = delay; - thisVelocity = e.getVelocity().clone(); - launchLocation = e.getLocation().clone(); - impactLocation = launchLocation.clone(); + this.thisVelocity = e.getVelocity().clone(); + this.launchLocation = e.getLocation().clone(); + this.impactLocation = this.launchLocation.clone(); this.delay = delay; - abil = ability; - update(); - instances.put(entity, this); + this.abil = ability; + this.update(); + instances.put(this.entity, this); } public void update() { - if (System.currentTimeMillis() < fireTime + delay) { + if (System.currentTimeMillis() < this.fireTime + this.delay) { return; } - if (entity.isOnGround()) { - remove(); + if (this.entity.isOnGround()) { + this.remove(); return; } - lastVelocity = thisVelocity.clone(); - thisVelocity = entity.getVelocity().clone(); + this.lastVelocity = this.thisVelocity.clone(); + this.thisVelocity = this.entity.getVelocity().clone(); - Vector diff = thisVelocity.subtract(lastVelocity); + final Vector diff = this.thisVelocity.subtract(this.lastVelocity); - List blocks = GeneralMethods.getBlocksAroundPoint(entity.getLocation(), 1.5); + final List blocks = GeneralMethods.getBlocksAroundPoint(this.entity.getLocation(), 1.5); - for (Block b : blocks) { - if (WaterAbility.isWater(b)) { - remove(); + for (final Block b : blocks) { + if (ElementalAbility.isWater(b)) { + this.remove(); return; } } - if (thisVelocity.length() < lastVelocity.length()) { + if (this.thisVelocity.length() < this.lastVelocity.length()) { if ((diff.getX() > 1 || diff.getX() < -1) || (diff.getZ() > 1 || diff.getZ() < -1)) { - impactLocation = entity.getLocation(); - for (Block b : blocks) { - if (b.getType() == Material.BARRIER && barrier == false) + this.impactLocation = this.entity.getLocation(); + for (final Block b : blocks) { + if (b.getType() == Material.BARRIER && this.barrier == false) { return; - if (GeneralMethods.isSolid(b) && (entity.getLocation().getBlock().getRelative(BlockFace.EAST, 1).equals(b) || entity.getLocation().getBlock().getRelative(BlockFace.NORTH, 1).equals(b) || entity.getLocation().getBlock().getRelative(BlockFace.WEST, 1).equals(b) || entity.getLocation().getBlock().getRelative(BlockFace.SOUTH, 1).equals(b))) { - if (!ElementalAbility.isTransparent(instigator, b)) { - hasBeenDamaged = true; - ProjectKorra.plugin.getServer().getPluginManager().callEvent(new HorizontalVelocityChangeEvent(entity, instigator, lastVelocity, thisVelocity, diff, launchLocation, impactLocation, abil)); - remove(); + } + if (GeneralMethods.isSolid(b) && (this.entity.getLocation().getBlock().getRelative(BlockFace.EAST, 1).equals(b) || this.entity.getLocation().getBlock().getRelative(BlockFace.NORTH, 1).equals(b) || this.entity.getLocation().getBlock().getRelative(BlockFace.WEST, 1).equals(b) || this.entity.getLocation().getBlock().getRelative(BlockFace.SOUTH, 1).equals(b))) { + if (!ElementalAbility.isTransparent(this.instigator, b)) { + this.hasBeenDamaged = true; + ProjectKorra.plugin.getServer().getPluginManager().callEvent(new HorizontalVelocityChangeEvent(this.entity, this.instigator, this.lastVelocity, this.thisVelocity, diff, this.launchLocation, this.impactLocation, this.abil)); + this.remove(); return; } } @@ -102,24 +103,26 @@ public void update() { } public static void updateAll() { - for (Entity e : instances.keySet()) + for (final Entity e : instances.keySet()) { if (e != null && !e.isDead() && instances.get(e) != null) { instances.get(e).update(); } else { instances.remove(e); } + } } public void remove() { - instances.remove(entity); + instances.remove(this.entity); } - public static void remove(Entity e) { - if (instances.containsKey(e)) + public static void remove(final Entity e) { + if (instances.containsKey(e)) { instances.remove(e); + } } - public static boolean hasBeenDamagedByHorizontalVelocity(Entity e) { + public static boolean hasBeenDamagedByHorizontalVelocity(final Entity e) { if (instances.containsKey(e)) { return instances.get(e).hasBeenDamaged; } diff --git a/src/com/projectkorra/projectkorra/object/PlayerFlyData.java b/src/com/projectkorra/projectkorra/object/PlayerFlyData.java index 07187f8f5..020f2c171 100644 --- a/src/com/projectkorra/projectkorra/object/PlayerFlyData.java +++ b/src/com/projectkorra/projectkorra/object/PlayerFlyData.java @@ -2,29 +2,29 @@ public class PlayerFlyData { - private boolean canFly; - private boolean isFlying; + private final boolean canFly; + private final boolean isFlying; - public PlayerFlyData(boolean canFly, boolean isFlying) { + public PlayerFlyData(final boolean canFly, final boolean isFlying) { this.canFly = canFly; this.isFlying = isFlying; } /** * Does the player have access to fly mode? - * + * * @return */ public boolean canFly() { - return canFly; + return this.canFly; } /** * Was the player flying? - * + * * @return */ public boolean isFlying() { - return isFlying; + return this.isFlying; } } diff --git a/src/com/projectkorra/projectkorra/object/Preset.java b/src/com/projectkorra/projectkorra/object/Preset.java index 41b6df5c7..94f9c74e0 100644 --- a/src/com/projectkorra/projectkorra/object/Preset.java +++ b/src/com/projectkorra/projectkorra/object/Preset.java @@ -22,7 +22,7 @@ /** * A savable association of abilities and hotbar slots, stored per player. - * + * * @author kingbirdy * */ @@ -42,19 +42,19 @@ public class Preset { static String updateQuery1 = "UPDATE pk_presets SET slot"; static String updateQuery2 = " = ? WHERE uuid = ? AND name = ?"; - private UUID uuid; - private HashMap abilities; - private String name; + private final UUID uuid; + private final HashMap abilities; + private final String name; /** * Creates a new {@link Preset} - * + * * @param uuid The UUID of the Player who the Preset belongs to * @param name The name of the Preset * @param abilities A HashMap of the abilities to be saved in the Preset, * keyed to the slot they're bound to */ - public Preset(UUID uuid, String name, HashMap abilities) { + public Preset(final UUID uuid, final String name, final HashMap abilities) { this.uuid = uuid; this.name = name; this.abilities = abilities; @@ -66,38 +66,40 @@ public Preset(UUID uuid, String name, HashMap abilities) { /** * Unload a Player's Presets from those stored in memory. - * + * * @param player The Player who's Presets should be unloaded */ - public static void unloadPreset(Player player) { - UUID uuid = player.getUniqueId(); + public static void unloadPreset(final Player player) { + final UUID uuid = player.getUniqueId(); presets.remove(uuid); } /** * Load a Player's Presets into memory. - * + * * @param player The Player who's Presets should be loaded */ public static void loadPresets(final Player player) { new BukkitRunnable() { @Override public void run() { - UUID uuid = player.getUniqueId(); - if (uuid == null) + final UUID uuid = player.getUniqueId(); + if (uuid == null) { return; + } try { - PreparedStatement ps = DBConnection.sql.getConnection().prepareStatement(loadQuery); + final PreparedStatement ps = DBConnection.sql.getConnection().prepareStatement(loadQuery); ps.setString(1, uuid.toString()); - ResultSet rs = ps.executeQuery(); + final ResultSet rs = ps.executeQuery(); if (rs.next()) { // Presets exist. int i = 0; do { - HashMap moves = new HashMap(); + final HashMap moves = new HashMap(); for (int total = 1; total <= 9; total++) { - String slot = rs.getString("slot" + total); - if (slot != null) + final String slot = rs.getString("slot" + total); + if (slot != null) { moves.put(total, slot); + } } new Preset(uuid, rs.getString("name"), moves); i++; @@ -106,7 +108,7 @@ public void run() { ProjectKorra.log.info("Loaded " + i + " presets for " + player.getName()); } } - catch (SQLException ex) { + catch (final SQLException ex) { ex.printStackTrace(); } } @@ -115,32 +117,31 @@ public void run() { /** * Reload a Player's Presets from those stored in memory. - * + * * @param player The Player who's Presets should be unloaded */ - public static void reloadPreset(Player player) { + public static void reloadPreset(final Player player) { unloadPreset(player); loadPresets(player); } /** * Binds the abilities from a Preset for the given Player. - * + * * @param player The Player the Preset should be bound for * @param name The name of the Preset that should be bound * @return True if all abilities were successfully bound, or false otherwise */ - public static boolean bindPreset(Player player, Preset preset) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static boolean bindPreset(final Player player, final Preset preset) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return false; } - @SuppressWarnings("unchecked") - HashMap abilities = (HashMap) preset.abilities.clone(); + final HashMap abilities = (HashMap) preset.abilities.clone(); boolean boundAll = true; for (int i = 1; i <= 9; i++) { - CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); + final CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); if (coreAbil != null && !bPlayer.canBind(coreAbil)) { abilities.remove(i); boundAll = false; @@ -152,17 +153,17 @@ public static boolean bindPreset(Player player, Preset preset) { /** * Checks if a Preset with a certain name exists for a given Player. - * + * * @param player The player who's Presets should be checked * @param name The name of the Preset to look for * @return true if the Preset exists, false otherwise */ - public static boolean presetExists(Player player, String name) { + public static boolean presetExists(final Player player, final String name) { if (!presets.containsKey(player.getUniqueId())) { return false; } boolean exists = false; - for (Preset preset : presets.get(player.getUniqueId())) { + for (final Preset preset : presets.get(player.getUniqueId())) { if (preset.name.equalsIgnoreCase(name)) { exists = true; } @@ -172,16 +173,16 @@ public static boolean presetExists(Player player, String name) { /** * Gets a Preset for the specified Player. - * + * * @param Player The Player who's Preset should be gotten * @param name The name of the Preset to get * @return The Preset, if it exists, or null otherwise */ - public static Preset getPreset(Player player, String name) { + public static Preset getPreset(final Player player, final String name) { if (!presets.containsKey(player.getUniqueId())) { return null; } - for (Preset preset : presets.get(player.getUniqueId())) { + for (final Preset preset : presets.get(player.getUniqueId())) { if (preset.name.equalsIgnoreCase(name)) { return preset; } @@ -190,18 +191,19 @@ public static Preset getPreset(Player player, String name) { } public static void loadExternalPresets() { - HashMap> presets = new HashMap>(); - for (String name : config.getKeys(false)) { - if (!presets.containsKey(name)) + final HashMap> presets = new HashMap>(); + for (final String name : config.getKeys(false)) { + if (!presets.containsKey(name)) { if (!config.getStringList(name).isEmpty() && config.getStringList(name).size() <= 9) { presets.put(name.toLowerCase(), (ArrayList) config.getStringList(name)); } + } } externalPresets = presets; } - public static boolean externalPresetExists(String name) { - for (String preset : externalPresets.keySet()) { + public static boolean externalPresetExists(final String name) { + for (final String preset : externalPresets.keySet()) { if (name.equalsIgnoreCase(preset)) { return true; } @@ -211,16 +213,17 @@ public static boolean externalPresetExists(String name) { /** * Gets the contents of a Preset for the specified Player. - * + * * @param player The Player who's Preset should be gotten * @param name The name of the Preset who's contents should be gotten * @return HashMap of ability names keyed to hotbar slots, if the Preset * exists, or null otherwise */ - public static HashMap getPresetContents(Player player, String name) { - if (!presets.containsKey(player.getUniqueId())) + public static HashMap getPresetContents(final Player player, final String name) { + if (!presets.containsKey(player.getUniqueId())) { return null; - for (Preset preset : presets.get(player.getUniqueId())) { + } + for (final Preset preset : presets.get(player.getUniqueId())) { if (preset.name.equalsIgnoreCase(name)) { return preset.abilities; } @@ -228,27 +231,27 @@ public static HashMap getPresetContents(Player player, String n return null; } - public static boolean bindExternalPreset(Player player, String name) { + public static boolean bindExternalPreset(final Player player, final String name) { boolean boundAll = true; int slot = 0; - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return false; } - HashMap abilities = new HashMap(); + final HashMap abilities = new HashMap(); if (externalPresetExists(name.toLowerCase())) { - for (String ability : externalPresets.get(name.toLowerCase())) { + for (final String ability : externalPresets.get(name.toLowerCase())) { slot++; - CoreAbility coreAbil = CoreAbility.getAbility(ability); + final CoreAbility coreAbil = CoreAbility.getAbility(ability); if (coreAbil != null) { abilities.put(slot, coreAbil.getName()); } } for (int i = 1; i <= 9; i++) { - CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); + final CoreAbility coreAbil = CoreAbility.getAbility(abilities.get(i)); if (coreAbil != null && !bPlayer.canBind(coreAbil)) { abilities.remove(i); boundAll = false; @@ -265,20 +268,20 @@ public static boolean bindExternalPreset(Player player, String name) { */ public void delete() { try { - PreparedStatement ps = DBConnection.sql.getConnection().prepareStatement(deleteQuery); - ps.setString(1, uuid.toString()); - ps.setString(2, name); + final PreparedStatement ps = DBConnection.sql.getConnection().prepareStatement(deleteQuery); + ps.setString(1, this.uuid.toString()); + ps.setString(2, this.name); ps.execute(); - presets.get(uuid).remove(this); + presets.get(this.uuid).remove(this); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } /** * Gets the name of the preset. - * + * * @return The name of the preset */ public String getName() { @@ -291,33 +294,33 @@ public String getName() { public void save(final Player player) { try { PreparedStatement ps = DBConnection.sql.getConnection().prepareStatement(loadNameQuery); - ps.setString(1, uuid.toString()); - ps.setString(2, name); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { //if the preset doesn't exist in the DB, create it + ps.setString(1, this.uuid.toString()); + ps.setString(2, this.name); + final ResultSet rs = ps.executeQuery(); + if (!rs.next()) { // if the preset doesn't exist in the DB, create it. ps = DBConnection.sql.getConnection().prepareStatement(insertQuery); - ps.setString(1, uuid.toString()); - ps.setString(2, name); + ps.setString(1, this.uuid.toString()); + ps.setString(2, this.name); ps.execute(); } } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } - for (final Integer i : abilities.keySet()) { + for (final Integer i : this.abilities.keySet()) { new BukkitRunnable() { PreparedStatement ps; @Override public void run() { try { - ps = DBConnection.sql.getConnection().prepareStatement(updateQuery1 + i + updateQuery2); - ps.setString(1, abilities.get(i)); - ps.setString(2, uuid.toString()); - ps.setString(3, name); - ps.execute(); + this.ps = DBConnection.sql.getConnection().prepareStatement(updateQuery1 + i + updateQuery2); + this.ps.setString(1, Preset.this.abilities.get(i)); + this.ps.setString(2, Preset.this.uuid.toString()); + this.ps.setString(3, Preset.this.name); + this.ps.execute(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } @@ -332,7 +335,7 @@ public void run() { Thread.sleep(1500); reloadPreset(player); } - catch (InterruptedException e) { + catch (final InterruptedException e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/storage/DBConnection.java b/src/com/projectkorra/projectkorra/storage/DBConnection.java index b9ad85291..73cd5c153 100644 --- a/src/com/projectkorra/projectkorra/storage/DBConnection.java +++ b/src/com/projectkorra/projectkorra/storage/DBConnection.java @@ -2,21 +2,28 @@ import java.sql.DatabaseMetaData; import java.sql.SQLException; + import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class DBConnection { public static Database sql; - public static String host; - public static int port; - public static String db; - public static String user; - public static String pass; - public static boolean isOpen = false; + private static String host; + private static int port; + private static String db; + private static String user; + private static String pass; + private static boolean isOpen = false; public static void init() { + DBConnection.host = ConfigManager.getConfig().getString("Storage.MySQL.host"); + DBConnection.port = ConfigManager.getConfig().getInt("Storage.MySQL.port"); + DBConnection.pass = ConfigManager.getConfig().getString("Storage.MySQL.pass"); + DBConnection.db = ConfigManager.getConfig().getString("Storage.MySQL.db"); + DBConnection.user = ConfigManager.getConfig().getString("Storage.MySQL.user"); if (ProjectKorra.plugin.getConfig().getString("Storage.engine").equalsIgnoreCase("mysql")) { sql = new MySQL(ProjectKorra.log, "Establishing MySQL Connection...", host, port, user, pass, db); if (((MySQL) sql).open() == null) { @@ -24,17 +31,15 @@ public static void init() { GeneralMethods.stopPlugin(); return; } - isOpen = true; ProjectKorra.log.info("Database connection established."); - if (!sql.tableExists("pk_players")) { ProjectKorra.log.info("Creating pk_players table"); - String query = "CREATE TABLE `pk_players` (" + "`uuid` varchar(36) NOT NULL," + "`player` varchar(16) NOT NULL," + "`element` varchar(255)," + "`subelement` varchar(255)," + "`permaremoved` varchar(5)," + "`slot1` varchar(255)," + "`slot2` varchar(255)," + "`slot3` varchar(255)," + "`slot4` varchar(255)," + "`slot5` varchar(255)," + "`slot6` varchar(255)," + "`slot7` varchar(255)," + "`slot8` varchar(255)," + "`slot9` varchar(255)," + " PRIMARY KEY (uuid));"; + final String query = "CREATE TABLE `pk_players` (" + "`uuid` varchar(36) NOT NULL," + "`player` varchar(16) NOT NULL," + "`element` varchar(255)," + "`subelement` varchar(255)," + "`permaremoved` varchar(5)," + "`slot1` varchar(255)," + "`slot2` varchar(255)," + "`slot3` varchar(255)," + "`slot4` varchar(255)," + "`slot5` varchar(255)," + "`slot6` varchar(255)," + "`slot7` varchar(255)," + "`slot8` varchar(255)," + "`slot9` varchar(255)," + " PRIMARY KEY (uuid));"; sql.modifyQuery(query, false); } else { try { - DatabaseMetaData md = sql.connection.getMetaData(); + final DatabaseMetaData md = sql.connection.getMetaData(); if (!md.getColumns(null, null, "pk_players", "subelement").next()) { ProjectKorra.log.info("Updating Database with subelements..."); sql.getConnection().setAutoCommit(false); @@ -45,14 +50,23 @@ public static void init() { ProjectKorra.log.info("Database Updated."); } } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } - if (!sql.tableExists("pk_presets")) { ProjectKorra.log.info("Creating pk_presets table"); - String query = "CREATE TABLE `pk_presets` (" + "`uuid` varchar(36) NOT NULL," + "`name` varchar(255) NOT NULL," + "`slot1` varchar(255)," + "`slot2` varchar(255)," + "`slot3` varchar(255)," + "`slot4` varchar(255)," + "`slot5` varchar(255)," + "`slot6` varchar(255)," + "`slot7` varchar(255)," + "`slot8` varchar(255)," + "`slot9` varchar(255)," + " PRIMARY KEY (uuid, name));"; + final String query = "CREATE TABLE `pk_presets` (" + "`uuid` varchar(36) NOT NULL," + "`name` varchar(255) NOT NULL," + "`slot1` varchar(255)," + "`slot2` varchar(255)," + "`slot3` varchar(255)," + "`slot4` varchar(255)," + "`slot5` varchar(255)," + "`slot6` varchar(255)," + "`slot7` varchar(255)," + "`slot8` varchar(255)," + "`slot9` varchar(255)," + " PRIMARY KEY (uuid, name));"; + sql.modifyQuery(query, false); + } + if (!sql.tableExists("pk_cooldown_ids")) { + ProjectKorra.log.info("Creating pk_cooldown_ids table"); + final String query = "CREATE TABLE `pk_cooldown_ids` (id INTEGER PRIMARY KEY AUTO_INCREMENT, cooldown_name VARCHAR(256) NOT NULL);"; + sql.modifyQuery(query, false); + } + if (!sql.tableExists("pk_cooldowns")) { + ProjectKorra.log.info("Creating pk_cooldowns table"); + final String query = "CREATE TABLE `pk_cooldowns` (uuid VARCHAR(36) PRIMARY KEY, cooldown_id INTEGER NOT NULL, value BIGINT);"; sql.modifyQuery(query, false); } } else { @@ -62,15 +76,14 @@ public static void init() { GeneralMethods.stopPlugin(); return; } - isOpen = true; if (!sql.tableExists("pk_players")) { ProjectKorra.log.info("Creating pk_players table."); - String query = "CREATE TABLE `pk_players` (" + "`uuid` TEXT(36) PRIMARY KEY," + "`player` TEXT(16)," + "`element` TEXT(255)," + "`subelement` TEXT(255)," + "`permaremoved` TEXT(5)," + "`slot1` TEXT(255)," + "`slot2` TEXT(255)," + "`slot3` TEXT(255)," + "`slot4` TEXT(255)," + "`slot5` TEXT(255)," + "`slot6` TEXT(255)," + "`slot7` TEXT(255)," + "`slot8` TEXT(255)," + "`slot9` TEXT(255));"; + final String query = "CREATE TABLE `pk_players` (" + "`uuid` TEXT(36) PRIMARY KEY," + "`player` TEXT(16)," + "`element` TEXT(255)," + "`subelement` TEXT(255)," + "`permaremoved` TEXT(5)," + "`slot1` TEXT(255)," + "`slot2` TEXT(255)," + "`slot3` TEXT(255)," + "`slot4` TEXT(255)," + "`slot5` TEXT(255)," + "`slot6` TEXT(255)," + "`slot7` TEXT(255)," + "`slot8` TEXT(255)," + "`slot9` TEXT(255));"; sql.modifyQuery(query, false); } else { try { - DatabaseMetaData md = sql.connection.getMetaData(); + final DatabaseMetaData md = sql.connection.getMetaData(); if (!md.getColumns(null, null, "pk_players", "subelement").next()) { ProjectKorra.log.info("Updating Database with subelements..."); sql.getConnection().setAutoCommit(false); @@ -82,14 +95,23 @@ public static void init() { } } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } - if (!sql.tableExists("pk_presets")) { ProjectKorra.log.info("Creating pk_presets table"); - String query = "CREATE TABLE `pk_presets` (" + "`uuid` TEXT(36)," + "`name` TEXT(255)," + "`slot1` TEXT(255)," + "`slot2` TEXT(255)," + "`slot3` TEXT(255)," + "`slot4` TEXT(255)," + "`slot5` TEXT(255)," + "`slot6` TEXT(255)," + "`slot7` TEXT(255)," + "`slot8` TEXT(255)," + "`slot9` TEXT(255)," + "PRIMARY KEY (uuid, name));"; + final String query = "CREATE TABLE `pk_presets` (" + "`uuid` TEXT(36)," + "`name` TEXT(255)," + "`slot1` TEXT(255)," + "`slot2` TEXT(255)," + "`slot3` TEXT(255)," + "`slot4` TEXT(255)," + "`slot5` TEXT(255)," + "`slot6` TEXT(255)," + "`slot7` TEXT(255)," + "`slot8` TEXT(255)," + "`slot9` TEXT(255)," + "PRIMARY KEY (uuid, name));"; + sql.modifyQuery(query, false); + } + if (!sql.tableExists("pk_cooldown_ids")) { + ProjectKorra.log.info("Creating pk_cooldown_ids table"); + final String query = "CREATE TABLE `pk_cooldown_ids` (id INTEGER PRIMARY KEY AUTOINCREMENT, cooldown_name TEXT(256) NOT NULL);"; + sql.modifyQuery(query, false); + } + if (!sql.tableExists("pk_cooldowns")) { + ProjectKorra.log.info("Creating pk_cooldowns table"); + final String query = "CREATE TABLE `pk_cooldowns` (uuid TEXT(36) PRIMARY KEY, cooldown_id INTEGER NOT NULL, value BIGINT);"; sql.modifyQuery(query, false); } } diff --git a/src/com/projectkorra/projectkorra/storage/Database.java b/src/com/projectkorra/projectkorra/storage/Database.java index a834699bf..efa2d52e9 100644 --- a/src/com/projectkorra/projectkorra/storage/Database.java +++ b/src/com/projectkorra/projectkorra/storage/Database.java @@ -1,16 +1,16 @@ package com.projectkorra.projectkorra.storage; -import com.projectkorra.projectkorra.ProjectKorra; - -import org.bukkit.scheduler.BukkitRunnable; - import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.PreparedStatement; import java.util.logging.Logger; +import org.bukkit.scheduler.BukkitRunnable; + +import com.projectkorra.projectkorra.ProjectKorra; + public abstract class Database { protected final Logger log; @@ -18,7 +18,7 @@ public abstract class Database { protected final String dbprefix; protected Connection connection = null; - public Database(Logger log, String prefix, String dbprefix) { + public Database(final Logger log, final String prefix, final String dbprefix) { this.log = log; this.prefix = prefix; this.dbprefix = dbprefix; @@ -29,8 +29,8 @@ public Database(Logger log, String prefix, String dbprefix) { * * @param message The string to print to console */ - protected void printInfo(String message) { - log.info(prefix + dbprefix + message); + protected void printInfo(final String message) { + this.log.info(this.prefix + this.dbprefix + message); } /** @@ -40,11 +40,12 @@ protected void printInfo(String message) { * @param severe If {@param severe} is true print an error, else print a * warning */ - protected void printErr(String message, boolean severe) { - if (severe) - log.severe(prefix + dbprefix + message); - else - log.warning(prefix + dbprefix + message); + protected void printErr(final String message, final boolean severe) { + if (severe) { + this.log.severe(this.prefix + this.dbprefix + message); + } else { + this.log.warning(this.prefix + this.dbprefix + message); + } } /** @@ -53,7 +54,7 @@ protected void printErr(String message, boolean severe) { * @return Connection if exists, else null */ public Connection getConnection() { - return connection; + return this.connection; } /** @@ -67,11 +68,11 @@ public Connection getConnection() { * Close connection to Database. */ public void close() { - if (connection != null) { + if (this.connection != null) { try { - connection.close(); + this.connection.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } else { @@ -86,7 +87,7 @@ public void close() { * @param query Query to run */ public void modifyQuery(final String query) { - modifyQuery(query, true); + this.modifyQuery(query, true); } /** @@ -100,11 +101,11 @@ public void modifyQuery(final String query, final boolean async) { new BukkitRunnable() { @Override public void run() { - doQuery(query); + Database.this.doQuery(query); } }.runTaskAsynchronously(ProjectKorra.plugin); } else { - doQuery(query); + this.doQuery(query); } } @@ -114,14 +115,17 @@ public void run() { * @param query Query to run * @return Result set of ran query */ - public ResultSet readQuery(String query) { + public ResultSet readQuery(final String query) { try { - PreparedStatement stmt = connection.prepareStatement(query); - ResultSet rs = stmt.executeQuery(); + if (this.connection == null || this.connection.isClosed()) { + this.open(); + } + final PreparedStatement stmt = this.connection.prepareStatement(query); + final ResultSet rs = stmt.executeQuery(); return rs; } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); return null; } @@ -129,18 +133,43 @@ public ResultSet readQuery(String query) { /** * Check database to see if a table exists. - * + * * @param table Table name to check * @return true if table exists, else false */ - public boolean tableExists(String table) { + public boolean tableExists(final String table) { try { - DatabaseMetaData dmd = connection.getMetaData(); - ResultSet rs = dmd.getTables(null, null, table, null); + if (this.connection == null || this.connection.isClosed()) { + this.open(); + } + final DatabaseMetaData dmd = this.connection.getMetaData(); + final ResultSet rs = dmd.getTables(null, null, table, null); return rs.next(); } - catch (Exception e) { + catch (final Exception e) { + e.printStackTrace(); + return false; + } + } + + /** + * Check database to see if column exists within table. + * + * @param table Table name to check + * @param column Column name to check + * @return true if column exists within table, else false + */ + public boolean columnExists(final String table, final String column) { + try { + if (this.connection == null || this.connection.isClosed()) { + this.open(); + } + final DatabaseMetaData dmd = this.connection.getMetaData(); + final ResultSet rs = dmd.getColumns(null, null, table, column); + return rs.next(); + } + catch (final Exception e) { e.printStackTrace(); return false; } @@ -148,11 +177,14 @@ public boolean tableExists(String table) { private synchronized void doQuery(final String query) { try { - PreparedStatement stmt = connection.prepareStatement(query); + if (this.connection == null || this.connection.isClosed()) { + this.open(); + } + final PreparedStatement stmt = this.connection.prepareStatement(query); stmt.execute(); stmt.close(); } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/storage/MySQL.java b/src/com/projectkorra/projectkorra/storage/MySQL.java index 859d1159a..cbf49015f 100644 --- a/src/com/projectkorra/projectkorra/storage/MySQL.java +++ b/src/com/projectkorra/projectkorra/storage/MySQL.java @@ -9,11 +9,11 @@ public class MySQL extends Database { private String host = "localhost"; private int port = 3306; - private String user; + private final String user; private String pass = ""; - private String database; + private final String database; - public MySQL(Logger log, String prefix, String host, int port, String user, String pass, String database) { + public MySQL(final Logger log, final String prefix, final String host, final int port, final String user, final String pass, final String database) { super(log, prefix, "[MySQL] "); this.host = host; this.port = port; @@ -22,7 +22,7 @@ public MySQL(Logger log, String prefix, String host, int port, String user, Stri this.database = database; } - public MySQL(Logger log, String prefix, String user, String pass, String database) { + public MySQL(final Logger log, final String prefix, final String user, final String pass, final String database) { super(log, prefix, "[MySQL] "); this.user = user; this.pass = pass; @@ -34,18 +34,18 @@ public Connection open() { try { Class.forName("com.mysql.jdbc.Driver"); - String url = "jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database; + final String url = "jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database; this.connection = DriverManager.getConnection(url, this.user, this.pass); this.printInfo("Connection established!"); return this.connection; } - catch (ClassNotFoundException e) { + catch (final ClassNotFoundException e) { this.printErr("JDBC driver not found!", true); return null; } - catch (SQLException e) { + catch (final SQLException e) { e.printStackTrace(); this.printErr("MYSQL exception during connection.", true); return null; diff --git a/src/com/projectkorra/projectkorra/storage/SQLite.java b/src/com/projectkorra/projectkorra/storage/SQLite.java index 1d0c581d7..a891d1092 100644 --- a/src/com/projectkorra/projectkorra/storage/SQLite.java +++ b/src/com/projectkorra/projectkorra/storage/SQLite.java @@ -7,16 +7,16 @@ import java.util.logging.Logger; public class SQLite extends Database { - private String location; - private String database; - private File SQLfile; + private final String location; + private final String database; + private final File SQLfile; - public SQLite(Logger log, String prefix, String database, String location) { + public SQLite(final Logger log, final String prefix, final String database, final String location) { super(log, prefix, "[SQLite] "); this.database = database; this.location = location; - File folder = new File(this.location); + final File folder = new File(this.location); if (!folder.exists()) { folder.mkdirs(); @@ -35,11 +35,11 @@ public Connection open() { return this.connection; } - catch (ClassNotFoundException e) { + catch (final ClassNotFoundException e) { this.printErr("JDBC driver not found!", true); return null; } - catch (SQLException e) { + catch (final SQLException e) { this.printErr("SQLite exception during connection.", true); return null; } diff --git a/src/com/projectkorra/projectkorra/util/ActionBar.java b/src/com/projectkorra/projectkorra/util/ActionBar.java index baeadaf71..24fa71206 100644 --- a/src/com/projectkorra/projectkorra/util/ActionBar.java +++ b/src/com/projectkorra/projectkorra/util/ActionBar.java @@ -32,7 +32,7 @@ public class ActionBar { sendPacket = ReflectionHandler.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); initialised = true; } - catch (ReflectiveOperationException e) { + catch (final ReflectiveOperationException e) { initialised = false; } } @@ -41,31 +41,31 @@ public static boolean isInitialised() { return initialised; } - public static boolean sendActionBar(String message, Player... player) { + public static boolean sendActionBar(final String message, final Player... player) { if (!initialised) { return false; } try { - Object o = chatSer.newInstance(message); + final Object o = chatSer.newInstance(message); Object packet; if (version >= 12) { packet = packetChat.newInstance(o, PackageType.MINECRAFT_SERVER.getClass("ChatMessageType").getEnumConstants()[2]); } else { - packet = packetChat.newInstance(o, (byte)2); + packet = packetChat.newInstance(o, (byte) 2); } sendTo(packet, player); } - catch (ReflectiveOperationException e) { + catch (final ReflectiveOperationException e) { e.printStackTrace(); initialised = false; } return initialised; } - private static void sendTo(Object packet, Player... player) throws ReflectiveOperationException { - for (Player p : player) { - Object entityplayer = getHandle.invoke(p); - Object PlayerConnection = playerConnection.get(entityplayer); + private static void sendTo(final Object packet, final Player... player) throws ReflectiveOperationException { + for (final Player p : player) { + final Object entityplayer = getHandle.invoke(p); + final Object PlayerConnection = playerConnection.get(entityplayer); sendPacket.invoke(PlayerConnection, packet); } } diff --git a/src/com/projectkorra/projectkorra/util/Attribute.java b/src/com/projectkorra/projectkorra/util/Attribute.java index 69a4bd37e..052da5b96 100644 --- a/src/com/projectkorra/projectkorra/util/Attribute.java +++ b/src/com/projectkorra/projectkorra/util/Attribute.java @@ -7,10 +7,10 @@ public class Attribute { - public static boolean setField(CoreAbility ability, String field, Object value) { + public static boolean setField(final CoreAbility ability, final String field, final Object value) { try { - Field _field = ability.getClass().getDeclaredField(field); - boolean oldVisibility = _field.isAccessible(); + final Field _field = ability.getClass().getDeclaredField(field); + final boolean oldVisibility = _field.isAccessible(); _field.setAccessible(true); try { _field.set(ability, value); @@ -31,13 +31,13 @@ public static boolean setField(CoreAbility ability, String field, Object value) return true; } - public static Object getField(CoreAbility ability, String field) { + public static Object getField(final CoreAbility ability, final String field) { try { - Field _field = ability.getClass().getDeclaredField(field); - boolean oldVisibility = _field.isAccessible(); + final Field _field = ability.getClass().getDeclaredField(field); + final boolean oldVisibility = _field.isAccessible(); _field.setAccessible(true); try { - Object object = _field.get(ability); + final Object object = _field.get(ability); _field.setAccessible(oldVisibility); return object; } diff --git a/src/com/projectkorra/projectkorra/util/BlockCacheElement.java b/src/com/projectkorra/projectkorra/util/BlockCacheElement.java index cfe7c73cd..66fd12c34 100644 --- a/src/com/projectkorra/projectkorra/util/BlockCacheElement.java +++ b/src/com/projectkorra/projectkorra/util/BlockCacheElement.java @@ -10,7 +10,7 @@ public class BlockCacheElement { private boolean allowed; private long time; - public BlockCacheElement(Player player, Block block, String ability, boolean allowed, long time) { + public BlockCacheElement(final Player player, final Block block, final String ability, final boolean allowed, final long time) { this.player = player; this.block = block; this.ability = ability; @@ -19,42 +19,42 @@ public BlockCacheElement(Player player, Block block, String ability, boolean all } public String getAbility() { - return ability; + return this.ability; } public Block getBlock() { - return block; + return this.block; } public Player getPlayer() { - return player; + return this.player; } public long getTime() { - return time; + return this.time; } public boolean isAllowed() { - return allowed; + return this.allowed; } - public void setAbility(String ability) { + public void setAbility(final String ability) { this.ability = ability; } - public void setAllowed(boolean allowed) { + public void setAllowed(final boolean allowed) { this.allowed = allowed; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } - public void setPlayer(Player player) { + public void setPlayer(final Player player) { this.player = player; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } diff --git a/src/com/projectkorra/projectkorra/util/BlockSource.java b/src/com/projectkorra/projectkorra/util/BlockSource.java index 4aec7e8cc..0ed2f22e8 100644 --- a/src/com/projectkorra/projectkorra/util/BlockSource.java +++ b/src/com/projectkorra/projectkorra/util/BlockSource.java @@ -1,10 +1,6 @@ package com.projectkorra.projectkorra.util; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.ability.EarthAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.HashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -12,13 +8,18 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; -import java.util.HashMap; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; /** * BlockSource is a class that handles water and earth bending sources. When a * Player left clicks or presses shift the update method is called which * attempts to update the player's sources. - * + * * In this class ClickType refers to the way in which the source was selected. * For example, Surge has two different ways to select a source, one involving * shift and another involving left clicks. @@ -27,7 +28,7 @@ public class BlockSource { /** * An enum representation of the source types available for bending * abilities. - * + * * @author kingbirdy */ public static enum BlockSourceType { @@ -38,34 +39,33 @@ public static enum BlockSourceType { private static FileConfiguration config = ConfigManager.defaultConfig.get(); // The player should never need to grab source blocks from farther than this. private static double MAX_RANGE = config.getDouble("Abilities.Water.WaterManipulation.SelectRange"); - //private static boolean tempblock = config.getBoolean("Properties.Water.CanBendFromBentBlocks"); /** * Updates all of the player's sources. - * + * * @param player the player performing the bending. * @param clickType either {@link ClickType}.SHIFT_DOWN or * ClickType.LEFT_CLICK */ - public static void update(Player player, ClickType clickType) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void update(final Player player, final ClickType clickType) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } - CoreAbility coreAbil = bPlayer.getBoundAbility(); + final CoreAbility coreAbil = bPlayer.getBoundAbility(); if (coreAbil == null) { return; } if (coreAbil instanceof WaterAbility) { - Block waterBlock = WaterAbility.getWaterSourceBlock(player, MAX_RANGE, true); + final Block waterBlock = WaterAbility.getWaterSourceBlock(player, MAX_RANGE, true); if (waterBlock != null) { putSource(player, waterBlock, BlockSourceType.WATER, clickType); - if (WaterAbility.isPlant(waterBlock)) { + if (ElementalAbility.isPlant(waterBlock)) { putSource(player, waterBlock, BlockSourceType.PLANT, clickType); } - if (WaterAbility.isIce(waterBlock)) { + if (ElementalAbility.isIce(waterBlock)) { putSource(player, waterBlock, BlockSourceType.ICE, clickType); } if (WaterAbility.isSnow(waterBlock)) { @@ -73,19 +73,19 @@ public static void update(Player player, ClickType clickType) { } } } else if (coreAbil instanceof EarthAbility) { - Block earthBlock = EarthAbility.getEarthSourceBlock(player, null, MAX_RANGE); + final Block earthBlock = EarthAbility.getEarthSourceBlock(player, null, MAX_RANGE); if (earthBlock != null) { putSource(player, earthBlock, BlockSourceType.EARTH, clickType); - if (EarthAbility.isMetal(earthBlock)) { + if (ElementalAbility.isMetal(earthBlock)) { putSource(player, earthBlock, BlockSourceType.METAL, clickType); } } - // We need to handle lava differently, since getEarthSourceBlock doesn't account for - // lava. We should only select the lava source if it is closer than the earth. - Block lavaBlock = EarthAbility.getLavaSourceBlock(player, MAX_RANGE); - double earthDist = earthBlock != null ? earthBlock.getLocation().distanceSquared(player.getLocation()) : Double.MAX_VALUE; - double lavaDist = lavaBlock != null ? lavaBlock.getLocation().distanceSquared(player.getLocation()) : Double.MAX_VALUE; + // We need to handle lava differently, since getEarthSourceBlock doesn't account for lava. + // We should only select the lava source if it is closer than the earth. + final Block lavaBlock = EarthAbility.getLavaSourceBlock(player, MAX_RANGE); + final double earthDist = earthBlock != null ? earthBlock.getLocation().distanceSquared(player.getLocation()) : Double.MAX_VALUE; + final double lavaDist = lavaBlock != null ? lavaBlock.getLocation().distanceSquared(player.getLocation()) : Double.MAX_VALUE; if (lavaBlock != null && lavaDist <= earthDist) { putSource(player, null, BlockSourceType.EARTH, clickType); putSource(player, lavaBlock, BlockSourceType.LAVA, clickType); @@ -95,34 +95,33 @@ public static void update(Player player, ClickType clickType) { /** * Helper method to create and update a specific source. - * + * * @param player a player. * @param block the block that is considered a source. * @param sourceType the elemental type of the block. * @param clickType the type of click, either SHIFT_DOWN or LEFT_CLICK. */ - private static void putSource(Player player, Block block, BlockSourceType sourceType, ClickType clickType) { + private static void putSource(final Player player, final Block block, final BlockSourceType sourceType, final ClickType clickType) { if (!playerSources.containsKey(player)) { playerSources.put(player, new HashMap>()); } if (!playerSources.get(player).containsKey(sourceType)) { playerSources.get(player).put(sourceType, new HashMap()); } - BlockSourceInformation info = new BlockSourceInformation(player, block, sourceType, clickType); + final BlockSourceInformation info = new BlockSourceInformation(player, block, sourceType, clickType); playerSources.get(player).get(sourceType).put(clickType, info); } /** * Access a block's source information, depending on a * {@link BlockSourceType} and {@link ClickType}. - * + * * @param player the player that is trying to bend. * @param clickType the action that was performed to access the source, * either ClickType.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid bendable block, or null if none was found. */ - public static BlockSourceInformation getBlockSourceInformation(Player player, BlockSourceType sourceType, ClickType clickType) { - + public static BlockSourceInformation getBlockSourceInformation(final Player player, final BlockSourceType sourceType, final ClickType clickType) { if (!playerSources.containsKey(player)) { return null; } else if (!playerSources.get(player).containsKey(sourceType)) { @@ -136,7 +135,7 @@ public static BlockSourceInformation getBlockSourceInformation(Player player, Bl /** * Access a block source information depending on a range, * {@link BlockSourceType}, and {@link ClickType}. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param sourceType the elemental type of block to find. @@ -144,15 +143,15 @@ public static BlockSourceInformation getBlockSourceInformation(Player player, Bl * either ClickType.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid bendable block, or null if none was found. */ - public static BlockSourceInformation getValidBlockSourceInformation(Player player, double range, BlockSourceType sourceType, ClickType clickType) { - BlockSourceInformation blockInfo = getBlockSourceInformation(player, sourceType, clickType); + public static BlockSourceInformation getValidBlockSourceInformation(final Player player, final double range, final BlockSourceType sourceType, final ClickType clickType) { + final BlockSourceInformation blockInfo = getBlockSourceInformation(player, sourceType, clickType); return isStillAValidSource(blockInfo, range, clickType) ? blockInfo : null; } /** * Access a specific type of source block depending on a range and * {@link ClickType}. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param sourceType the elemental type of block to find. @@ -160,8 +159,8 @@ public static BlockSourceInformation getValidBlockSourceInformation(Player playe * either ClickType.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid bendable block, or null if none was found. */ - public static Block getSourceBlock(Player player, double range, BlockSourceType sourceType, ClickType clickType) { - BlockSourceInformation info = getValidBlockSourceInformation(player, range, sourceType, clickType); + public static Block getSourceBlock(final Player player, final double range, final BlockSourceType sourceType, final ClickType clickType) { + final BlockSourceInformation info = getValidBlockSourceInformation(player, range, sourceType, clickType); if (info != null) { if (TempBlock.isTempBlock(info.getBlock()) && !WaterAbility.isBendableWaterTempBlock(info.getBlock())) { return null; @@ -174,33 +173,33 @@ public static Block getSourceBlock(Player player, double range, BlockSourceType /** * Attempts to access a Water bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @return a valid Water bendable block, or null if none was found. */ - public static Block getWaterSourceBlock(Player player, double range) { + public static Block getWaterSourceBlock(final Player player, final double range) { return getWaterSourceBlock(player, range, ClickType.LEFT_CLICK); } /** * Attempts to access a Water bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, * either {@link ClickType}.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid Water bendable block, or null if none was found. */ - public static Block getWaterSourceBlock(Player player, double range, ClickType clickType) { + public static Block getWaterSourceBlock(final Player player, final double range, final ClickType clickType) { return getWaterSourceBlock(player, range, clickType, true, true, true); } /** * Attempts to access a Water bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param allowWater true if water blocks are allowed. @@ -208,14 +207,14 @@ public static Block getWaterSourceBlock(Player player, double range, ClickType c * @param allowPlant true if plant blocks are allowed. * @return a valid Water bendable block, or null if none was found. */ - public static Block getWaterSourceBlock(Player player, double range, boolean allowWater, boolean allowIce, boolean allowPlant) { + public static Block getWaterSourceBlock(final Player player, final double range, final boolean allowWater, final boolean allowIce, final boolean allowPlant) { return getWaterSourceBlock(player, range, ClickType.LEFT_CLICK, allowWater, allowIce, allowPlant); } /** * Attempts to access a Water bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, @@ -225,14 +224,14 @@ public static Block getWaterSourceBlock(Player player, double range, boolean all * @param allowPlant true if plant blocks are allowed. * @return a valid Water bendable block, or null if none was found. */ - public static Block getWaterSourceBlock(Player player, double range, ClickType clickType, boolean allowWater, boolean allowIce, boolean allowPlant) { + public static Block getWaterSourceBlock(final Player player, final double range, final ClickType clickType, final boolean allowWater, final boolean allowIce, final boolean allowPlant) { return getWaterSourceBlock(player, range, clickType, allowWater, allowIce, allowPlant, true, true); } /** * Attempts to access a Water bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, @@ -244,29 +243,33 @@ public static Block getWaterSourceBlock(Player player, double range, ClickType c * that may have been created by a WaterBottle. * @return a valid Water bendable block, or null if none was found. */ - public static Block getWaterSourceBlock(Player player, double range, ClickType clickType, boolean allowWater, boolean allowIce, boolean allowPlant, boolean allowSnow, boolean allowWaterBottles) { + public static Block getWaterSourceBlock(final Player player, final double range, final ClickType clickType, final boolean allowWater, final boolean allowIce, final boolean allowPlant, final boolean allowSnow, final boolean allowWaterBottles) { Block sourceBlock = null; if (allowWaterBottles) { - // Check the block in front of the player's eyes, it may have been created by a - // WaterBottle. + // Check the block in front of the player's eyes, it may have been created by a WaterBottle. sourceBlock = WaterAbility.getWaterSourceBlock(player, range, allowPlant); if (sourceBlock == null || (sourceBlock.getWorld().equals(player.getWorld()) && sourceBlock.getLocation().distance(player.getEyeLocation()) > 3)) { sourceBlock = null; } } - if (allowWater && sourceBlock == null) { - sourceBlock = getSourceBlock(player, range, BlockSourceType.WATER, clickType); - } - if (allowIce && sourceBlock == null) { - sourceBlock = getSourceBlock(player, range, BlockSourceType.ICE, clickType); - } - if (allowPlant && sourceBlock == null) { - sourceBlock = getSourceBlock(player, range, BlockSourceType.PLANT, clickType); - } - if (allowSnow && sourceBlock == null) { - sourceBlock = getSourceBlock(player, range, BlockSourceType.SNOW, clickType); + final boolean dynamic = ConfigManager.getConfig().getBoolean("Properties.Water.DynamicSourcing"); + if (dynamic && sourceBlock == null) { + if (allowWater && sourceBlock == null) { + sourceBlock = getSourceBlock(player, range, BlockSourceType.WATER, clickType); + } + if (allowIce && sourceBlock == null) { + sourceBlock = getSourceBlock(player, range, BlockSourceType.ICE, clickType); + } + if (allowPlant && sourceBlock == null) { + sourceBlock = getSourceBlock(player, range, BlockSourceType.PLANT, clickType); + } + if (allowSnow && sourceBlock == null) { + sourceBlock = getSourceBlock(player, range, BlockSourceType.SNOW, clickType); + } + } else { + sourceBlock = WaterAbility.getWaterSourceBlock(player, range, allowPlant); } - if (sourceBlock != null && !sourceBlock.getType().equals(Material.AIR) && (WaterAbility.isWater(sourceBlock) || WaterAbility.isPlant(sourceBlock) || WaterAbility.isSnow(sourceBlock) || WaterAbility.isIce(sourceBlock))) { + if (sourceBlock != null && !sourceBlock.getType().equals(Material.AIR) && (ElementalAbility.isWater(sourceBlock) || ElementalAbility.isPlant(sourceBlock) || WaterAbility.isSnow(sourceBlock) || ElementalAbility.isIce(sourceBlock))) { if (TempBlock.isTempBlock(sourceBlock) && !WaterAbility.isBendableWaterTempBlock(sourceBlock)) { return null; } @@ -278,21 +281,21 @@ public static Block getWaterSourceBlock(Player player, double range, ClickType c /** * Attempts to access a Earth bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, * either {@link ClickType}.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid Earth bendable block, or null if none was found. */ - public static Block getEarthSourceBlock(Player player, double range, ClickType clickType) { + public static Block getEarthSourceBlock(final Player player, final double range, final ClickType clickType) { return getEarthSourceBlock(player, range, clickType, true); } /** * Attempts to access a Earth bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, @@ -302,25 +305,27 @@ public static Block getEarthSourceBlock(Player player, double range, ClickType c * block. * @return a valid Earth bendable block, or null if none was found. */ - public static Block getEarthSourceBlock(Player player, double range, ClickType clickType, boolean allowNearbySubstitute) { + public static Block getEarthSourceBlock(final Player player, final double range, final ClickType clickType, final boolean allowNearbySubstitute) { Block sourceBlock = getSourceBlock(player, range, BlockSourceType.EARTH, clickType); - - if (sourceBlock == null && allowNearbySubstitute) { - BlockSourceInformation blockInfo = getBlockSourceInformation(player, BlockSourceType.EARTH, clickType); + final boolean dynamic = ConfigManager.getConfig().getBoolean("Properties.Earth.DynamicSourcing"); + if (dynamic && sourceBlock == null && allowNearbySubstitute) { + final BlockSourceInformation blockInfo = getBlockSourceInformation(player, BlockSourceType.EARTH, clickType); if (blockInfo == null) { return null; } - Block tempBlock = blockInfo.getBlock(); + final Block tempBlock = blockInfo.getBlock(); if (tempBlock == null) { return null; } - Location loc = tempBlock.getLocation(); + final Location loc = tempBlock.getLocation(); sourceBlock = EarthAbility.getNearbyEarthBlock(loc, 3, 1); if (sourceBlock == null || !sourceBlock.getLocation().getWorld().equals(player.getWorld()) || Math.abs(sourceBlock.getLocation().distance(player.getEyeLocation())) > range || !EarthAbility.isEarthbendable(player, sourceBlock)) { return null; } + } else { + sourceBlock = getSourceBlock(player, range, BlockSourceType.EARTH, clickType); } return sourceBlock; } @@ -328,35 +333,35 @@ public static Block getEarthSourceBlock(Player player, double range, ClickType c /** * Attempts to access a Lava bendable block that was recently shifted or * clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, * either {@link ClickType}.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid Lava bendable block, or null if none was found. */ - public static Block getLavaSourceBlock(Player player, double range, ClickType clickType) { + public static Block getLavaSourceBlock(final Player player, final double range, final ClickType clickType) { return getSourceBlock(player, range, BlockSourceType.LAVA, clickType); } /** * Attempts to access a Lava bendable block or an Earth block that was * recently shifted or clicked on by the player. - * + * * @param player the player that is trying to bend. * @param range the maximum range to access the block. * @param clickType the action that was performed to access the source, * either {@link ClickType}.SHIFT_DOWN or ClickType.LEFT_CLICK. * @return a valid Earth or Lava bendable block, or null if none was found. */ - public static Block getEarthOrLavaSourceBlock(Player player, double range, ClickType clickType) { + public static Block getEarthOrLavaSourceBlock(final Player player, final double range, final ClickType clickType) { /* * When Lava is selected as a source it automatically overrides the * previous Earth based source. Only one of these types can exist, so if * Lava exists then we know Earth is null. */ - Block earthBlock = getEarthSourceBlock(player, range, clickType); - BlockSourceInformation lavaBlockInfo = getValidBlockSourceInformation(player, range, BlockSourceType.LAVA, clickType); + final Block earthBlock = getEarthSourceBlock(player, range, clickType); + final BlockSourceInformation lavaBlockInfo = getValidBlockSourceInformation(player, range, BlockSourceType.LAVA, clickType); if (earthBlock != null) { return earthBlock; } else if (lavaBlockInfo != null) { @@ -369,12 +374,12 @@ public static Block getEarthOrLavaSourceBlock(Player player, double range, Click * Determines if a BlockSourceInformation is valid, depending on the players * range from the source, and if the source has not been modified since the * time that it was first created. - * + * * @param info the source information. * @param range the maximum bending range. * @return true if it is valid. */ - private static boolean isStillAValidSource(BlockSourceInformation info, double range, ClickType clickType) { + private static boolean isStillAValidSource(final BlockSourceInformation info, final double range, final ClickType clickType) { if (info == null || info.getBlock() == null) { return false; } else if (info.getClickType() != clickType) { @@ -387,13 +392,13 @@ private static boolean isStillAValidSource(BlockSourceInformation info, double r return false; } else if (info.getSourceType() == BlockSourceType.ICE && !WaterAbility.isIcebendable(info.getPlayer(), info.getBlock().getType(), false)) { return false; - } else if (info.getSourceType() == BlockSourceType.PLANT && (!WaterAbility.isPlant(info.getBlock()) || !WaterAbility.isWaterbendable(info.getPlayer(), null, info.getBlock()))) { + } else if (info.getSourceType() == BlockSourceType.PLANT && (!ElementalAbility.isPlant(info.getBlock()) || !WaterAbility.isWaterbendable(info.getPlayer(), null, info.getBlock()))) { return false; } else if (info.getSourceType() == BlockSourceType.EARTH && !EarthAbility.isEarthbendable(info.getPlayer(), info.getBlock())) { return false; - } else if (info.getSourceType() == BlockSourceType.METAL && (!EarthAbility.isMetal(info.getBlock()) || !EarthAbility.isEarthbendable(info.getPlayer(), info.getBlock()))) { + } else if (info.getSourceType() == BlockSourceType.METAL && (!ElementalAbility.isMetal(info.getBlock()) || !EarthAbility.isEarthbendable(info.getPlayer(), info.getBlock()))) { return false; - } else if (info.getSourceType() == BlockSourceType.LAVA && (!EarthAbility.isLava(info.getBlock()) || !EarthAbility.isLavabendable(info.getPlayer(), info.getBlock()))) { + } else if (info.getSourceType() == BlockSourceType.LAVA && (!ElementalAbility.isLava(info.getBlock()) || !EarthAbility.isLavabendable(info.getPlayer(), info.getBlock()))) { return false; } return true; diff --git a/src/com/projectkorra/projectkorra/util/BlockSourceInformation.java b/src/com/projectkorra/projectkorra/util/BlockSourceInformation.java index 8df21b102..35ca98063 100644 --- a/src/com/projectkorra/projectkorra/util/BlockSourceInformation.java +++ b/src/com/projectkorra/projectkorra/util/BlockSourceInformation.java @@ -1,13 +1,13 @@ package com.projectkorra.projectkorra.util; -import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; - import org.bukkit.block.Block; import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.util.BlockSource.BlockSourceType; + /** * The information for a bending source block. - * + * * @author kingbirdy */ public class BlockSourceInformation { @@ -19,13 +19,13 @@ public class BlockSourceInformation { /** * Creates a new BlockSourceInformation. - * + * * @param player The player the source belongs to * @param block The source block * @param sourceType What {@link BlockSourceType source type} the block is * @param clickType */ - public BlockSourceInformation(Player player, Block block, BlockSourceType sourceType, ClickType clickType) { + public BlockSourceInformation(final Player player, final Block block, final BlockSourceType sourceType, final ClickType clickType) { this.player = player; this.block = block; this.sourceType = sourceType; @@ -35,91 +35,91 @@ public BlockSourceInformation(Player player, Block block, BlockSourceType source /** * Gets the source block. - * + * * @return The source block */ public Block getBlock() { - return block; + return this.block; } /** * Sets a new source block. - * + * * @param block The new source block. */ - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } /** * Get what {@link BlockSourceType source type} the source is. - * + * * @return The block's source type */ public BlockSourceType getSourceType() { - return sourceType; + return this.sourceType; } /** * Sets the source type. - * + * * @param sourceType The new source type. */ - public void setSourceType(BlockSourceType sourceType) { + public void setSourceType(final BlockSourceType sourceType) { this.sourceType = sourceType; } /** * Gets when the source was created. - * + * * @return The source's creation time */ public long getCreationTime() { - return creationTime; + return this.creationTime; } /** * Sets the source's creation time. - * + * * @param creationTime The new creation time */ - public void setCreationTime(long creationTime) { + public void setCreationTime(final long creationTime) { this.creationTime = creationTime; } /** * Get the player the source belongs to. - * + * * @return The player the source belongs to */ public Player getPlayer() { - return player; + return this.player; } /** * Sets the player the source belongs to. - * + * * @param player The player the source will belong to */ - public void setPlayer(Player player) { + public void setPlayer(final Player player) { this.player = player; } /** * Gets the {@link ClickType} used to select the source. - * + * * @return The ClickType used to select the source */ public ClickType getClickType() { - return clickType; + return this.clickType; } /** * Sets the source's {@link ClickType}. - * + * * @param clickType The ClickType to set */ - public void setClickType(ClickType clickType) { + public void setClickType(final ClickType clickType) { this.clickType = clickType; } } diff --git a/src/com/projectkorra/projectkorra/util/ClickType.java b/src/com/projectkorra/projectkorra/util/ClickType.java index c19563458..9afc0aa75 100644 --- a/src/com/projectkorra/projectkorra/util/ClickType.java +++ b/src/com/projectkorra/projectkorra/util/ClickType.java @@ -13,12 +13,12 @@ public enum ClickType { */ LEFT_CLICK, /** - * For any instance of right clicking that isn't with an entity or a block - * (Right clicking air will not work). + * Player has left clicked and hit an entity. */ LEFT_CLICK_ENTITY, /** - * Player has left clicked and hit an entity. + * For any instance of right clicking that isn't with an entity or a block + * (Right clicking air will not work). */ RIGHT_CLICK, /** @@ -36,5 +36,9 @@ public enum ClickType { /** * The shift key being released. */ - SHIFT_UP; + SHIFT_UP, + /** + * The item swap hand key was pressed + */ + OFFHAND_TRIGGER; } diff --git a/src/com/projectkorra/projectkorra/util/Cooldown.java b/src/com/projectkorra/projectkorra/util/Cooldown.java new file mode 100644 index 000000000..09eec5c5f --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/Cooldown.java @@ -0,0 +1,26 @@ +package com.projectkorra.projectkorra.util; + +public class Cooldown { + + /** + * The amount of time the cooldown is valid including the system time when + * the cooldown was created + */ + private final long cooldown; + /** If the cooldown should be saved in the database */ + private final boolean database; + + public Cooldown(final long cooldown, final boolean database) { + this.cooldown = cooldown; + this.database = database; + } + + public long getCooldown() { + return this.cooldown; + } + + public boolean isDatabase() { + return this.database; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/DBCooldownManager.java b/src/com/projectkorra/projectkorra/util/DBCooldownManager.java new file mode 100644 index 000000000..f2ef2f1da --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/DBCooldownManager.java @@ -0,0 +1,64 @@ +package com.projectkorra.projectkorra.util; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.storage.DBConnection; +import com.projectkorra.projectkorra.storage.MySQL; + +public class DBCooldownManager { + + public DBCooldownManager() { + this.setupCooldowns(); + } + + public void setupCooldowns() { + // Create pk_cooldown_ids table. + if (!DBConnection.sql.tableExists("pk_cooldown_ids")) { + ProjectKorra.log.info("Creating pk_cooldown_ids table"); + String query = "CREATE TABLE `pk_cooldown_ids` (id INTEGER PRIMARY KEY AUTOINCREMENT, cooldown_name TEXT(256) NOT NULL);"; + if (DBConnection.sql instanceof MySQL) { + query = "CREATE TABLE `pk_cooldown_ids` (id INTEGER PRIMARY KEY AUTO_INCREMENT, cooldown_name VARCHAR(256) NOT NULL);"; + } + DBConnection.sql.modifyQuery(query, false); + } + // Create pk_cooldowns table. + if (!DBConnection.sql.tableExists("pk_cooldowns")) { + ProjectKorra.log.info("Creating pk_cooldowns table"); + String query = "CREATE TABLE `pk_cooldowns` (uuid TEXT(36) PRIMARY KEY, cooldown_id INTEGER NOT NULL, value BIGINT);"; + if (DBConnection.sql instanceof MySQL) { + query = "CREATE TABLE `pk_cooldowns` (uuid VARCHAR(36) PRIMARY KEY, cooldown_id INTEGER NOT NULL, value BIGINT);"; + } + DBConnection.sql.modifyQuery(query, false); + } + } + + public int getCooldownId(final String cooldown, final boolean async) { + try (ResultSet rs = DBConnection.sql.readQuery("SELECT id FROM pk_cooldown_ids WHERE cooldown_name = '" + cooldown + "'")) { + if (rs.next()) { + return rs.getInt("id"); + } else { + DBConnection.sql.modifyQuery("INSERT INTO pk_cooldown_ids (cooldown_name) VALUES ('" + cooldown + "')", async); + return this.getCooldownId(cooldown, async); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + return -1; + } + + public String getCooldownName(final int id) { + try (ResultSet rs = DBConnection.sql.readQuery("SELECT cooldown_name FROM pk_cooldown_ids WHERE id = " + id)) { + if (rs.next()) { + return rs.getString("cooldown_name"); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + return ""; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/DamageHandler.java b/src/com/projectkorra/projectkorra/util/DamageHandler.java index 52354db5e..575c5698e 100644 --- a/src/com/projectkorra/projectkorra/util/DamageHandler.java +++ b/src/com/projectkorra/projectkorra/util/DamageHandler.java @@ -1,13 +1,5 @@ package com.projectkorra.projectkorra.util; -import fr.neatmonster.nocheatplus.checks.CheckType; -import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; - -import com.projectkorra.projectkorra.ability.Ability; -import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.event.AbilityDamageEntityEvent; -import com.projectkorra.projectkorra.event.EntityBendingDeathEvent; - import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -16,18 +8,26 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; +import com.projectkorra.projectkorra.ability.Ability; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.command.Commands; +import com.projectkorra.projectkorra.event.AbilityDamageEntityEvent; +import com.projectkorra.projectkorra.event.EntityBendingDeathEvent; + +import fr.neatmonster.nocheatplus.checks.CheckType; +import fr.neatmonster.nocheatplus.hooks.NCPExemptionManager; + public class DamageHandler { /** * Damages an Entity by amount of damage specified. Starts a * {@link EntityDamageByEntityEvent}. - * + * * @param ability The ability that is used to damage the entity * @param entity The entity that is receiving the damage * @param damage The amount of damage to deal */ - @SuppressWarnings("deprecation") - public static void damageEntity(Entity entity, Player source, double damage, Ability ability, boolean ignoreArmor) { + public static void damageEntity(final Entity entity, Player source, double damage, final Ability ability, boolean ignoreArmor) { if (TempArmor.hasTempArmor((LivingEntity) entity)) { ignoreArmor = true; } @@ -38,7 +38,7 @@ public static void damageEntity(Entity entity, Player source, double damage, Abi source = ability.getPlayer(); } - AbilityDamageEntityEvent damageEvent = new AbilityDamageEntityEvent(entity, ability, damage, ignoreArmor); + final AbilityDamageEntityEvent damageEvent = new AbilityDamageEntityEvent(entity, ability, damage, ignoreArmor); Bukkit.getServer().getPluginManager().callEvent(damageEvent); if (entity instanceof LivingEntity) { if (entity instanceof Player && Commands.invincible.contains(entity.getName())) { @@ -56,17 +56,19 @@ public static void damageEntity(Entity entity, Player source, double damage, Abi } if (((LivingEntity) entity).getHealth() - damage <= 0 && !entity.isDead()) { - EntityBendingDeathEvent event = new EntityBendingDeathEvent(entity, damage, ability); + final EntityBendingDeathEvent event = new EntityBendingDeathEvent(entity, damage, ability); Bukkit.getServer().getPluginManager().callEvent(event); } - EntityDamageByEntityEvent finalEvent = new EntityDamageByEntityEvent(source, entity, DamageCause.CUSTOM, damage); + final EntityDamageByEntityEvent finalEvent = new EntityDamageByEntityEvent(source, entity, DamageCause.CUSTOM, damage); + final double prevHealth = ((LivingEntity) entity).getHealth(); ((LivingEntity) entity).damage(damage, source); + final double nextHealth = ((LivingEntity) entity).getHealth(); entity.setLastDamageCause(finalEvent); if (ignoreArmor) { - if (finalEvent.isApplicable(DamageModifier.ARMOR)) { - finalEvent.setDamage(DamageModifier.ARMOR, 0); - } + if (finalEvent.isApplicable(DamageModifier.ARMOR)) { + finalEvent.setDamage(DamageModifier.ARMOR, 0); + } } if (Bukkit.getPluginManager().isPluginEnabled("NoCheatPlus") && source != null) { @@ -77,16 +79,23 @@ public static void damageEntity(Entity entity, Player source, double damage, Abi NCPExemptionManager.unexempt(source, CheckType.COMBINED_IMPROBABLE); NCPExemptionManager.unexempt(source, CheckType.FIGHT_SELFHIT); } + + if (prevHealth != nextHealth) { + if (entity instanceof Player) { + StatisticsMethods.addStatisticAbility(source.getUniqueId(), CoreAbility.getAbility(ability.getName()), Statistic.PLAYER_DAMAGE, (long) damage); + } + StatisticsMethods.addStatisticAbility(source.getUniqueId(), CoreAbility.getAbility(ability.getName()), Statistic.TOTAL_DAMAGE, (long) damage); + } } } } - public static void damageEntity(Entity entity, Player source, double damage, Ability ability) { + public static void damageEntity(final Entity entity, final Player source, final double damage, final Ability ability) { damageEntity(entity, source, damage, ability, true); } - public static void damageEntity(Entity entity, double damage, Ability ability) { + public static void damageEntity(final Entity entity, final double damage, final Ability ability) { damageEntity(entity, ability.getPlayer(), damage, ability); } } diff --git a/src/com/projectkorra/projectkorra/util/FileExtensionFilter.java b/src/com/projectkorra/projectkorra/util/FileExtensionFilter.java index 323b96b5d..9fcd9538f 100644 --- a/src/com/projectkorra/projectkorra/util/FileExtensionFilter.java +++ b/src/com/projectkorra/projectkorra/util/FileExtensionFilter.java @@ -5,7 +5,7 @@ /** * Checks if a file ends with a certain extension. - * + * * @author kingbirdy * */ @@ -15,15 +15,15 @@ public final class FileExtensionFilter implements FileFilter { /** * Creates a new FileExtensionFilter. - * + * * @param extension the extension to filter for */ - public FileExtensionFilter(String extension) { + public FileExtensionFilter(final String extension) { this.extension = extension; } @Override - public boolean accept(File file) { - return file.getName().endsWith(extension); + public boolean accept(final File file) { + return file.getName().endsWith(this.extension); } } diff --git a/src/com/projectkorra/projectkorra/util/Flight.java b/src/com/projectkorra/projectkorra/util/Flight.java deleted file mode 100644 index a7d490706..000000000 --- a/src/com/projectkorra/projectkorra/util/Flight.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.projectkorra.projectkorra.util; - -import java.util.ArrayList; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.bukkit.GameMode; -import org.bukkit.entity.Player; - -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.airbending.AirScooter; -import com.projectkorra.projectkorra.airbending.AirSpout; -import com.projectkorra.projectkorra.airbending.Tornado; -import com.projectkorra.projectkorra.earthbending.Catapult; -import com.projectkorra.projectkorra.firebending.FireJet; -import com.projectkorra.projectkorra.waterbending.WaterSpout; -import com.projectkorra.projectkorra.waterbending.blood.Bloodbending; - -public class Flight { - - private static Map instances = new ConcurrentHashMap(); - private static long duration = 5000; - - private Player player; - private Player source; - private boolean couldFly = false; - private boolean wasFlying = false; - private long time; - - public Flight(Player player) { - this(player, null); - } - - public Flight(Player player, Player source) { - if (instances.containsKey(player)) { - Flight flight = instances.get(player); - flight.refresh(source); - return; - } - this.couldFly = player.getAllowFlight(); - this.wasFlying = player.isFlying(); - this.player = player; - this.source = source; - this.time = System.currentTimeMillis(); - instances.put(player, this); - } - - @Override - public boolean equals(Object object) { - if (!(object instanceof Flight)) { - return false; - } - Flight flight = (Flight) object; - return flight.player == this.player && flight.source == this.source && flight.couldFly == this.couldFly && flight.wasFlying == this.wasFlying; - } - - public static Player getLaunchedBy(Player player) { - if (instances.containsKey(player)) { - return instances.get(player).source; - } - return null; - } - - public static void handle() { - ArrayList players = new ArrayList<>(); - ArrayList newFlyingPlayers = new ArrayList(); - Set airScooterPlayers = CoreAbility.getPlayers(AirScooter.class); - Set waterSpoutPlayers = CoreAbility.getPlayers(WaterSpout.class); - Set airSpoutPlayers = CoreAbility.getPlayers(AirSpout.class); - - players.addAll(CoreAbility.getPlayers(Tornado.class)); - players.addAll(CoreAbility.getPlayers(FireJet.class)); - players.addAll(CoreAbility.getPlayers(Catapult.class)); - - for (Player player : instances.keySet()) { - Flight flight = instances.get(player); - if (System.currentTimeMillis() <= flight.time + duration) { - if (airScooterPlayers.contains(player) || waterSpoutPlayers.contains(player) || airSpoutPlayers.contains(player)) { - continue; - } - if (Bloodbending.isBloodbent(player)) { - player.setAllowFlight(true); - player.setFlying(false); - continue; - } - - if (players.contains(player)) { - flight.refresh(null); - player.setAllowFlight(true); - if (player.getGameMode() != GameMode.CREATIVE) - player.setFlying(false); - newFlyingPlayers.add(player); - continue; - } - if (flight.source == null) { - flight.revert(); - flight.remove(); - } else { - if (System.currentTimeMillis() >= flight.time + duration) { - flight.revert(); - flight.remove(); - } - } - } else { - flight.revert(); - flight.remove(); - } - } - } - - public static void removeAll() { - for (Player player : instances.keySet()) { - Flight flight = instances.get(player); - if (flight == null) { - instances.remove(player); - continue; - } - flight.revert(); - flight.remove(); - } - } - - private void refresh(Player source) { - this.source = source; - time = System.currentTimeMillis(); - instances.put(player, this); - } - - public void remove() { - if (player == null) { - for (Player player : instances.keySet()) { - if (instances.get(player).equals(this)) { - instances.remove(player); - } - } - return; - } - instances.remove(player); - } - - public void revert() { - if (player == null) { - return; - } - player.setAllowFlight(couldFly); - player.setFlying(wasFlying); - } - -} diff --git a/src/com/projectkorra/projectkorra/util/FlightHandler.java b/src/com/projectkorra/projectkorra/util/FlightHandler.java new file mode 100644 index 000000000..1fa485a15 --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/FlightHandler.java @@ -0,0 +1,224 @@ +package com.projectkorra.projectkorra.util; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.UUID; + +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import com.projectkorra.projectkorra.ProjectKorra; + +public class FlightHandler { + + /** + * A Map containing all Flight instances. + */ + private final Map INSTANCES = new HashMap<>(); + /** + * A PriorityQueue containing all Flight instances which have a specified + * duration. This is used to reduce the number of iterations when cleaning + * up dead instances. + */ + private final PriorityQueue CLEANUP = new PriorityQueue<>(100, new Comparator() { + @Override + public int compare(final FlightAbility f1, final FlightAbility f2) { + return (int) (f1.duration - f2.duration); + } + }); + + public FlightHandler() { + this.startCleanup(); + } + + /** + * Create a new Flight instance for the provided player with an unlimited + * duration. Call {@link FlightHandler#removeInstance(Player)} to remove + * this instance when necessary. + * + * @param player The flying player + * @param identifier The ability using Flight + */ + public void createInstance(final Player player, final String identifier) { + this.createInstance(player, Flight.PERMANENT, identifier); + } + + /** + * Create a new Flight instance for the provided player with an unlimited + * duration. This method will set the source for this Flight instance to the + * second provided player argument. Call + * {@link FlightHandler#removeInstance(Player)} to remove this instance when + * necessary. + * + * @param player The flying player + * @param source The source player + * @param identifier The ability using Flight + */ + public void createInstance(final Player player, final Player source, final String identifier) { + this.createInstance(player, source, Flight.PERMANENT, identifier); + } + + /** + * Create a new Flight instance with the specified duration. This instance + * will automatically be removed with the set delay. + * + * @param player The flying player + * @param duration Flight duration + * @param identifier The ability using Flight + */ + public void createInstance(final Player player, final long duration, final String identifier) { + this.createInstance(player, null, duration, identifier); + } + + /** + * Create a new Flight instance with the specified duration. This method + * will set the source for this Flight instance to the second provided + * player argument. This instance will automatically be removed with the set + * delay. + * + * @param player The flying player + * @param source The source player + * @param duration Flight duration + * @param identifier The ability using Flight + */ + public void createInstance(final Player player, final Player source, final long duration, final String identifier) { + if (this.INSTANCES.containsKey(player.getUniqueId())) { + final Flight flight = this.INSTANCES.get(player.getUniqueId()); + final FlightAbility ability = new FlightAbility(player, identifier, duration); + if (duration != Flight.PERMANENT) { + this.CLEANUP.add(ability); + } + flight.abilities.put(identifier, ability); + } else { + final Flight flight = new Flight(player, source); + final FlightAbility ability = new FlightAbility(player, identifier, duration); + if (duration != Flight.PERMANENT) { + this.CLEANUP.add(ability); + } + flight.abilities.put(identifier, ability); + this.INSTANCES.put(player.getUniqueId(), flight); + } + } + + /** + * Remove a player's Flight status with the provided identifier. If this is + * the last ability using Flight, then their Flight instance shall be + * reverted to its initial state. This method does not need to be called for + * instances with a defined duration, however can be used in this case if + * necessary. + * + * @param player The flying player + * @param identifier The ability using Flight + */ + public void removeInstance(final Player player, final String identifier) { + if (this.INSTANCES.containsKey(player.getUniqueId())) { + final Flight flight = this.INSTANCES.get(player.getUniqueId()); + if (flight.abilities.containsKey(identifier)) { + flight.abilities.remove(identifier); + } + if (flight.abilities.isEmpty()) { + this.wipeInstance(player); + } + } + } + + /** + * Completely wipe all Flight data for the player. Should only be used if it + * is guaranteed they have a Flight instance. + * + * @param player + */ + private void wipeInstance(final Player player) { + final Flight flight = this.INSTANCES.get(player.getUniqueId()); + player.setAllowFlight(flight.couldFly); + player.setFlying(flight.wasFlying); + flight.abilities.values().forEach(ability -> this.CLEANUP.remove(ability)); + this.INSTANCES.remove(player.getUniqueId()); + } + + /** + * Get the provided player's Flight instance. + * + * @param player The flying player + * @return Flight instance + */ + public Flight getInstance(final Player player) { + if (this.INSTANCES.containsKey(player.getUniqueId())) { + return this.INSTANCES.get(player.getUniqueId()); + } + return null; + } + + public void startCleanup() { + new BukkitRunnable() { + @Override + public void run() { + final long currentTime = System.currentTimeMillis(); + while (!FlightHandler.this.CLEANUP.isEmpty()) { + final FlightAbility ability = FlightHandler.this.CLEANUP.peek(); + if (currentTime >= ability.startTime + ability.duration) { + FlightHandler.this.CLEANUP.poll(); + FlightHandler.this.removeInstance(ability.player, ability.identifier); + } else { + break; + } + } + } + }.runTaskTimer(ProjectKorra.plugin, 0, 1); + } + + public static class Flight { + + public static final int PERMANENT = -1; + + private final Player player; + private final Player source; + private final boolean couldFly; + private final boolean wasFlying; + private final Map abilities; + + public Flight(final Player player, final Player source) { + this.player = player; + this.source = source; + this.couldFly = player.getAllowFlight(); + this.wasFlying = player.isFlying(); + this.abilities = new HashMap<>(); + } + + public Player getPlayer() { + return this.player; + } + + public Player getSource() { + return this.source; + } + + @Override + public String toString() { + return "Flight{player=" + this.player.getName() + ",source=" + (this.source != null ? this.source.getName() : "null") + ",couldFly=" + this.couldFly + ",wasFlying=" + this.wasFlying + ",abilities=" + this.abilities + "}"; + } + } + + public static class FlightAbility { + + private final Player player; + private final String identifier; + private final long duration; + private final long startTime; + + public FlightAbility(final Player player, final String identifier, final long duration) { + this.player = player; + this.identifier = identifier; + this.duration = duration; + this.startTime = System.currentTimeMillis(); + } + + @Override + public String toString() { + return "FlightAbility{player=" + this.player.getName() + ",identifier=" + this.identifier + ",duration=" + this.duration + ",startTime=" + this.startTime + "}"; + } + } + +} diff --git a/src/com/projectkorra/projectkorra/util/Information.java b/src/com/projectkorra/projectkorra/util/Information.java index 5e0b9c5d6..ca494077c 100644 --- a/src/com/projectkorra/projectkorra/util/Information.java +++ b/src/com/projectkorra/projectkorra/util/Information.java @@ -10,7 +10,7 @@ public class Information { private static int ID = Integer.MIN_VALUE; private String string; - private int id; + private final int id; private int integer; private long time; private double value; @@ -23,93 +23,93 @@ public class Information { private Player player; public Information() { - id = ID++; + this.id = ID++; if (ID >= Integer.MAX_VALUE) { ID = Integer.MIN_VALUE; } } public Block getBlock() { - return block; + return this.block; } public byte getData() { - return data; + return this.data; } public double getDouble() { - return value; + return this.value; } public int getID() { - return id; + return this.id; } public int getInteger() { - return integer; + return this.integer; } public Location getLocation() { - return location; + return this.location; } public Player getPlayer() { - return player; + return this.player; } public BlockState getState() { - return state; + return this.state; } public String getString() { - return string; + return this.string; } public long getTime() { - return time; + return this.time; } public Material getType() { - return type; + return this.type; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } - public void setDouble(double value) { + public void setDouble(final double value) { this.value = value; } - public void setInteger(int integer) { + public void setInteger(final int integer) { this.integer = integer; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - public void setPlayer(Player player) { + public void setPlayer(final Player player) { this.player = player; } - public void setState(BlockState state) { + public void setState(final BlockState state) { this.state = state; } - public void setString(String string) { + public void setString(final String string) { this.string = string; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } - public void setType(Material type) { + public void setType(final Material type) { this.type = type; } diff --git a/src/com/projectkorra/projectkorra/util/Metrics.java b/src/com/projectkorra/projectkorra/util/Metrics.java index 2cd9378d3..693defeec 100644 --- a/src/com/projectkorra/projectkorra/util/Metrics.java +++ b/src/com/projectkorra/projectkorra/util/Metrics.java @@ -1,13 +1,5 @@ package com.projectkorra.projectkorra.util; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import javax.net.ssl.HttpsURLConnection; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; @@ -25,6 +17,15 @@ import java.util.logging.Level; import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.ServicePriority; +import org.bukkit.plugin.java.JavaPlugin; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + /** * bStats collects some data for plugin authors. * @@ -32,998 +33,758 @@ */ public class Metrics { - static { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String(new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's' }); - final String examplePackage = new String(new byte[] { 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e' }); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final JavaPlugin plugin; - - // A list with all custom charts - private final List charts = new ArrayList<>(); - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public Metrics(JavaPlugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - if (config.getBoolean("enabled", true)) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - if (chart == null) { - throw new IllegalArgumentException("Chart cannot be null!"); - } - charts.add(chart); - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, new Runnable() { - @Override - public void run() { - submitData(); - } - }); - } - }, 1000*60*5, 1000*60*30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - for (CustomChart customChart : charts) { - // Add the data of the custom charts - JSONObject chart = customChart.getRequestJsonObject(); - if (chart == null) { // If the chart is null, we skip it - continue; - } - customCharts.add(chart); - } - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JSONObject getServerData() { - // Minecraft specific data - int playerAmount = Bukkit.getOnlinePlayers().size(); - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = org.bukkit.Bukkit.getVersion(); - bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - private void submitData() { - final JSONObject data = getServerData(); - - JSONArray pluginData = new JSONArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - } catch (NoSuchFieldException ignored) { - continue; // Continue "searching" - } - // Found one! - try { - pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } - } - - data.put("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - - /** - * Represents a custom chart. - */ - public static abstract class CustomChart { - - // The id of the chart - protected final String chartId; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public CustomChart(String chartId) { - if (chartId == null || chartId.isEmpty()) { - throw new IllegalArgumentException("ChartId cannot be null or empty!"); - } - this.chartId = chartId; - } - - protected JSONObject getRequestJsonObject() { - JSONObject chart = new JSONObject(); - chart.put("chartId", chartId); - try { - JSONObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - chart.put("data", data); - } catch (Throwable t) { - if (logFailedRequests) { - Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return chart; - } - - protected abstract JSONObject getChartData(); - - } - - /** - * Represents a custom simple pie. - */ - public static abstract class SimplePie extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimplePie(String chartId) { - super(chartId); - } - - /** - * Gets the value of the pie. - * - * @return The value of the pie. - */ - public abstract String getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - String value = getValue(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - } - - /** - * Represents a custom advanced pie. - */ - public static abstract class AdvancedPie extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedPie(String chartId) { - super(chartId); - } - - /** - * Gets the values of the pie. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The values of the pie. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - } - - /** - * Represents a custom single line chart. - */ - public static abstract class SingleLineChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SingleLineChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @return The value of the chart. - */ - public abstract int getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - int value = getValue(); - if (value == 0) { - // Null = skip the chart - return null; - } - data.put("value", value); - return data; - } - - } - - /** - * Represents a custom multi line chart. - */ - public static abstract class MultiLineChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public MultiLineChart(String chartId) { - super(chartId); - } - - /** - * Gets the values of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The values of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple bar chart. - */ - public static abstract class SimpleBarChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimpleBarChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - JSONArray categoryValues = new JSONArray(); - categoryValues.add(entry.getValue()); - values.put(entry.getKey(), categoryValues); - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom advanced bar chart. - */ - public static abstract class AdvancedBarChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedBarChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - continue; // Skip this invalid - } - allSkipped = false; - JSONArray categoryValues = new JSONArray(); - for (int categoryValue : entry.getValue()) { - categoryValues.add(categoryValue); - } - values.put(entry.getKey(), categoryValues); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * Represents a custom simple map chart. - */ - public static abstract class SimpleMapChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public SimpleMapChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @return The value of the chart. - */ - public abstract Country getValue(); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - Country value = getValue(); - - if (value == null) { - // Null = skip the chart - return null; - } - data.put("value", value.getCountryIsoTag()); - return data; - } - - } - - /** - * Represents a custom advanced map chart. - */ - public static abstract class AdvancedMapChart extends CustomChart { - - /** - * Class constructor. - * - * @param chartId The id of the chart. - */ - public AdvancedMapChart(String chartId) { - super(chartId); - } - - /** - * Gets the value of the chart. - * - * @param valueMap Just an empty map. The only reason it exists is to make your life easier. - * You don't have to create a map yourself! - * @return The value of the chart. - */ - public abstract HashMap getValues(HashMap valueMap); - - @Override - protected JSONObject getChartData() { - JSONObject data = new JSONObject(); - JSONObject values = new JSONObject(); - HashMap map = getValues(new HashMap()); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - continue; // Skip this invalid - } - allSkipped = false; - values.put(entry.getKey().getCountryIsoTag(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - data.put("values", values); - return data; - } - - } - - /** - * A enum which is used for custom maps. - */ - public enum Country { - - /** - * bStats will use the country of the server. - */ - AUTO_DETECT("AUTO", "Auto Detected"), - - ANDORRA("AD", "Andorra"), - UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"), - AFGHANISTAN("AF", "Afghanistan"), - ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"), - ANGUILLA("AI", "Anguilla"), - ALBANIA("AL", "Albania"), - ARMENIA("AM", "Armenia"), - NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"), - ANGOLA("AO", "Angola"), - ANTARCTICA("AQ", "Antarctica"), - ARGENTINA("AR", "Argentina"), - AMERICAN_SAMOA("AS", "American Samoa"), - AUSTRIA("AT", "Austria"), - AUSTRALIA("AU", "Australia"), - ARUBA("AW", "Aruba"), - ALAND_ISLANDS("AX", "Åland Islands"), - AZERBAIJAN("AZ", "Azerbaijan"), - BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"), - BARBADOS("BB", "Barbados"), - BANGLADESH("BD", "Bangladesh"), - BELGIUM("BE", "Belgium"), - BURKINA_FASO("BF", "Burkina Faso"), - BULGARIA("BG", "Bulgaria"), - BAHRAIN("BH", "Bahrain"), - BURUNDI("BI", "Burundi"), - BENIN("BJ", "Benin"), - SAINT_BARTHELEMY("BL", "Saint Barthélemy"), - BERMUDA("BM", "Bermuda"), - BRUNEI("BN", "Brunei"), - BOLIVIA("BO", "Bolivia"), - BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"), - BRAZIL("BR", "Brazil"), - BAHAMAS("BS", "Bahamas"), - BHUTAN("BT", "Bhutan"), - BOUVET_ISLAND("BV", "Bouvet Island"), - BOTSWANA("BW", "Botswana"), - BELARUS("BY", "Belarus"), - BELIZE("BZ", "Belize"), - CANADA("CA", "Canada"), - COCOS_ISLANDS("CC", "Cocos Islands"), - THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"), - CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"), - CONGO("CG", "Congo"), - SWITZERLAND("CH", "Switzerland"), - COTE_D_IVOIRE("CI", "Côte d'Ivoire"), - COOK_ISLANDS("CK", "Cook Islands"), - CHILE("CL", "Chile"), - CAMEROON("CM", "Cameroon"), - CHINA("CN", "China"), - COLOMBIA("CO", "Colombia"), - COSTA_RICA("CR", "Costa Rica"), - CUBA("CU", "Cuba"), - CAPE_VERDE("CV", "Cape Verde"), - CURACAO("CW", "Curaçao"), - CHRISTMAS_ISLAND("CX", "Christmas Island"), - CYPRUS("CY", "Cyprus"), - CZECH_REPUBLIC("CZ", "Czech Republic"), - GERMANY("DE", "Germany"), - DJIBOUTI("DJ", "Djibouti"), - DENMARK("DK", "Denmark"), - DOMINICA("DM", "Dominica"), - DOMINICAN_REPUBLIC("DO", "Dominican Republic"), - ALGERIA("DZ", "Algeria"), - ECUADOR("EC", "Ecuador"), - ESTONIA("EE", "Estonia"), - EGYPT("EG", "Egypt"), - WESTERN_SAHARA("EH", "Western Sahara"), - ERITREA("ER", "Eritrea"), - SPAIN("ES", "Spain"), - ETHIOPIA("ET", "Ethiopia"), - FINLAND("FI", "Finland"), - FIJI("FJ", "Fiji"), - FALKLAND_ISLANDS("FK", "Falkland Islands"), - MICRONESIA("FM", "Micronesia"), - FAROE_ISLANDS("FO", "Faroe Islands"), - FRANCE("FR", "France"), - GABON("GA", "Gabon"), - UNITED_KINGDOM("GB", "United Kingdom"), - GRENADA("GD", "Grenada"), - GEORGIA("GE", "Georgia"), - FRENCH_GUIANA("GF", "French Guiana"), - GUERNSEY("GG", "Guernsey"), - GHANA("GH", "Ghana"), - GIBRALTAR("GI", "Gibraltar"), - GREENLAND("GL", "Greenland"), - GAMBIA("GM", "Gambia"), - GUINEA("GN", "Guinea"), - GUADELOUPE("GP", "Guadeloupe"), - EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"), - GREECE("GR", "Greece"), - SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"), - GUATEMALA("GT", "Guatemala"), - GUAM("GU", "Guam"), - GUINEA_BISSAU("GW", "Guinea-Bissau"), - GUYANA("GY", "Guyana"), - HONG_KONG("HK", "Hong Kong"), - HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"), - HONDURAS("HN", "Honduras"), - CROATIA("HR", "Croatia"), - HAITI("HT", "Haiti"), - HUNGARY("HU", "Hungary"), - INDONESIA("ID", "Indonesia"), - IRELAND("IE", "Ireland"), - ISRAEL("IL", "Israel"), - ISLE_OF_MAN("IM", "Isle Of Man"), - INDIA("IN", "India"), - BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"), - IRAQ("IQ", "Iraq"), - IRAN("IR", "Iran"), - ICELAND("IS", "Iceland"), - ITALY("IT", "Italy"), - JERSEY("JE", "Jersey"), - JAMAICA("JM", "Jamaica"), - JORDAN("JO", "Jordan"), - JAPAN("JP", "Japan"), - KENYA("KE", "Kenya"), - KYRGYZSTAN("KG", "Kyrgyzstan"), - CAMBODIA("KH", "Cambodia"), - KIRIBATI("KI", "Kiribati"), - COMOROS("KM", "Comoros"), - SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"), - NORTH_KOREA("KP", "North Korea"), - SOUTH_KOREA("KR", "South Korea"), - KUWAIT("KW", "Kuwait"), - CAYMAN_ISLANDS("KY", "Cayman Islands"), - KAZAKHSTAN("KZ", "Kazakhstan"), - LAOS("LA", "Laos"), - LEBANON("LB", "Lebanon"), - SAINT_LUCIA("LC", "Saint Lucia"), - LIECHTENSTEIN("LI", "Liechtenstein"), - SRI_LANKA("LK", "Sri Lanka"), - LIBERIA("LR", "Liberia"), - LESOTHO("LS", "Lesotho"), - LITHUANIA("LT", "Lithuania"), - LUXEMBOURG("LU", "Luxembourg"), - LATVIA("LV", "Latvia"), - LIBYA("LY", "Libya"), - MOROCCO("MA", "Morocco"), - MONACO("MC", "Monaco"), - MOLDOVA("MD", "Moldova"), - MONTENEGRO("ME", "Montenegro"), - SAINT_MARTIN("MF", "Saint Martin"), - MADAGASCAR("MG", "Madagascar"), - MARSHALL_ISLANDS("MH", "Marshall Islands"), - MACEDONIA("MK", "Macedonia"), - MALI("ML", "Mali"), - MYANMAR("MM", "Myanmar"), - MONGOLIA("MN", "Mongolia"), - MACAO("MO", "Macao"), - NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"), - MARTINIQUE("MQ", "Martinique"), - MAURITANIA("MR", "Mauritania"), - MONTSERRAT("MS", "Montserrat"), - MALTA("MT", "Malta"), - MAURITIUS("MU", "Mauritius"), - MALDIVES("MV", "Maldives"), - MALAWI("MW", "Malawi"), - MEXICO("MX", "Mexico"), - MALAYSIA("MY", "Malaysia"), - MOZAMBIQUE("MZ", "Mozambique"), - NAMIBIA("NA", "Namibia"), - NEW_CALEDONIA("NC", "New Caledonia"), - NIGER("NE", "Niger"), - NORFOLK_ISLAND("NF", "Norfolk Island"), - NIGERIA("NG", "Nigeria"), - NICARAGUA("NI", "Nicaragua"), - NETHERLANDS("NL", "Netherlands"), - NORWAY("NO", "Norway"), - NEPAL("NP", "Nepal"), - NAURU("NR", "Nauru"), - NIUE("NU", "Niue"), - NEW_ZEALAND("NZ", "New Zealand"), - OMAN("OM", "Oman"), - PANAMA("PA", "Panama"), - PERU("PE", "Peru"), - FRENCH_POLYNESIA("PF", "French Polynesia"), - PAPUA_NEW_GUINEA("PG", "Papua New Guinea"), - PHILIPPINES("PH", "Philippines"), - PAKISTAN("PK", "Pakistan"), - POLAND("PL", "Poland"), - SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"), - PITCAIRN("PN", "Pitcairn"), - PUERTO_RICO("PR", "Puerto Rico"), - PALESTINE("PS", "Palestine"), - PORTUGAL("PT", "Portugal"), - PALAU("PW", "Palau"), - PARAGUAY("PY", "Paraguay"), - QATAR("QA", "Qatar"), - REUNION("RE", "Reunion"), - ROMANIA("RO", "Romania"), - SERBIA("RS", "Serbia"), - RUSSIA("RU", "Russia"), - RWANDA("RW", "Rwanda"), - SAUDI_ARABIA("SA", "Saudi Arabia"), - SOLOMON_ISLANDS("SB", "Solomon Islands"), - SEYCHELLES("SC", "Seychelles"), - SUDAN("SD", "Sudan"), - SWEDEN("SE", "Sweden"), - SINGAPORE("SG", "Singapore"), - SAINT_HELENA("SH", "Saint Helena"), - SLOVENIA("SI", "Slovenia"), - SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"), - SLOVAKIA("SK", "Slovakia"), - SIERRA_LEONE("SL", "Sierra Leone"), - SAN_MARINO("SM", "San Marino"), - SENEGAL("SN", "Senegal"), - SOMALIA("SO", "Somalia"), - SURINAME("SR", "Suriname"), - SOUTH_SUDAN("SS", "South Sudan"), - SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"), - EL_SALVADOR("SV", "El Salvador"), - SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"), - SYRIA("SY", "Syria"), - SWAZILAND("SZ", "Swaziland"), - TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"), - CHAD("TD", "Chad"), - FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"), - TOGO("TG", "Togo"), - THAILAND("TH", "Thailand"), - TAJIKISTAN("TJ", "Tajikistan"), - TOKELAU("TK", "Tokelau"), - TIMOR_LESTE("TL", "Timor-Leste"), - TURKMENISTAN("TM", "Turkmenistan"), - TUNISIA("TN", "Tunisia"), - TONGA("TO", "Tonga"), - TURKEY("TR", "Turkey"), - TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"), - TUVALU("TV", "Tuvalu"), - TAIWAN("TW", "Taiwan"), - TANZANIA("TZ", "Tanzania"), - UKRAINE("UA", "Ukraine"), - UGANDA("UG", "Uganda"), - UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"), - UNITED_STATES("US", "United States"), - URUGUAY("UY", "Uruguay"), - UZBEKISTAN("UZ", "Uzbekistan"), - VATICAN("VA", "Vatican"), - SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"), - VENEZUELA("VE", "Venezuela"), - BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"), - U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"), - VIETNAM("VN", "Vietnam"), - VANUATU("VU", "Vanuatu"), - WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"), - SAMOA("WS", "Samoa"), - YEMEN("YE", "Yemen"), - MAYOTTE("YT", "Mayotte"), - SOUTH_AFRICA("ZA", "South Africa"), - ZAMBIA("ZM", "Zambia"), - ZIMBABWE("ZW", "Zimbabwe"); - - private String isoTag; - private String name; - - Country(String isoTag, String name) { - this.isoTag = isoTag; - this.name = name; - } - - /** - * Gets the name of the country. - * - * @return The name of the country. - */ - public String getCountryName() { - return name; - } - - /** - * Gets the iso tag of the country. - * - * @return The iso tag of the country. - */ - public String getCountryIsoTag() { - return isoTag; - } - - /** - * Gets a country by it's iso tag. - * - * @param isoTag The iso tag of the county. - * @return The country with the given iso tag or null if unknown. - */ - public static Country byIsoTag(String isoTag) { - for (Country country : Country.values()) { - if (country.getCountryIsoTag().equals(isoTag)) { - return country; - } - } - return null; - } - - /** - * Gets a country by a locale. - * - * @param locale The locale. - * @return The country from the giben locale or null if unknown country or - * if the locale does not contain a country. - */ - public static Country byLocale(Locale locale) { - return byIsoTag(locale.getCountry()); - } - - } - -} \ No newline at end of file + static { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick". + final String defaultPackage = new String(new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's' }); + final String examplePackage = new String(new byte[] { 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e' }); + // We want to make sure nobody just copy & pastes the example and use the wrong package names. + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + + // The version of this bStats class. + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent. + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // The uuid of the server. + private static String serverUUID; + + // The plugin. + private final JavaPlugin plugin; + + // A list with all custom charts. + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(final JavaPlugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file. + final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + final File configFile = new File(bStatsFolder, "config.yml"); + final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists. + if (!config.isSet("serverUuid")) { + + // Add default values. + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + + // Inform the server owners about bStats. + config.options().header("bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); + try { + config.save(configFile); + } + catch (final IOException ignored) { + } + } + + // Load the data. + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + if (config.getBoolean("enabled", true)) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one. + for (final Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first. + break; + } + catch (final NoSuchFieldException ignored) { + } + } + // Register our service. + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + this.startSubmitting(); + } + } + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(final CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + this.charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags. + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!Metrics.this.plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler. + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync. + Bukkit.getScheduler().runTask(Metrics.this.plugin, new Runnable() { + @Override + public void run() { + Metrics.this.submitData(); + } + }); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start. + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + final JSONObject data = new JSONObject(); + + final String pluginName = this.plugin.getDescription().getName(); + final String pluginVersion = this.plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin. + data.put("pluginVersion", pluginVersion); // Append the version of the plugin. + final JSONArray customCharts = new JSONArray(); + for (final CustomChart customChart : this.charts) { + // Add the data of the custom charts. + final JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it. + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data. + final int playerAmount = Bukkit.getOnlinePlayers().size(); + final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = org.bukkit.Bukkit.getVersion(); + bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); + + // OS/Java specific data. + final String javaVersion = System.getProperty("java.version"); + final String osName = System.getProperty("os.name"); + final String osArch = System.getProperty("os.arch"); + final String osVersion = System.getProperty("os.version"); + final int coreCount = Runtime.getRuntime().availableProcessors(); + + final JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = this.getServerData(); + + final JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data. + for (final Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier. + } + catch (final NoSuchFieldException ignored) { + continue; // Continue "searching". + } + // Found one! + try { + pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service))); + } + catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server. + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data. + sendData(data); + } + catch (final Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + Metrics.this.plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + Metrics.this.plugin.getName(), e); + } + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(final JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth. + final byte[] compressedData = compress(data.toString()); + + // Add headers. + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request. + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format. + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data. + connection.setDoOutput(true); + final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + connection.getInputStream().close(); // We don't care about the response - Just send our data :) + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + final GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes("UTF-8")); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart. + protected final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public CustomChart(final String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + protected JSONObject getRequestJsonObject() { + final JSONObject chart = new JSONObject(); + chart.put("chartId", this.chartId); + try { + final JSONObject data = this.getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } + catch (final Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + this.chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData(); + + } + + /** + * Represents a custom simple pie. + */ + public static abstract class SimplePie extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimplePie(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the pie. + * + * @return The value of the pie. + */ + public abstract String getValue(); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final String value = this.getValue(); + if (value == null || value.isEmpty()) { + // Null = skip the chart. + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static abstract class AdvancedPie extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedPie(final String chartId) { + super(chartId); + } + + /** + * Gets the values of the pie. + * + * @param valueMap Just an empty map. The only reason it exists is to + * make your life easier. You don't have to create a map + * yourself! + * @return The values of the pie. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final JSONObject values = new JSONObject(); + final HashMap map = this.getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart. + return null; + } + boolean allSkipped = true; + for (final Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid. + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart. + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static abstract class SingleLineChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SingleLineChart(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @return The value of the chart. + */ + public abstract int getValue(); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final int value = this.getValue(); + if (value == 0) { + // Null = skip the chart. + return null; + } + data.put("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static abstract class MultiLineChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public MultiLineChart(final String chartId) { + super(chartId); + } + + /** + * Gets the values of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to + * make your life easier. You don't have to create a map + * yourself! + * @return The values of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final JSONObject values = new JSONObject(); + final HashMap map = this.getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart. + return null; + } + boolean allSkipped = true; + for (final Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid. + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart. + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static abstract class SimpleBarChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimpleBarChart(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to + * make your life easier. You don't have to create a map + * yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final JSONObject values = new JSONObject(); + final HashMap map = this.getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart. + return null; + } + for (final Map.Entry entry : map.entrySet()) { + final JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static abstract class AdvancedBarChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedBarChart(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to + * make your life easier. You don't have to create a map + * yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final JSONObject values = new JSONObject(); + final HashMap map = this.getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart. + return null; + } + boolean allSkipped = true; + for (final Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid. + } + allSkipped = false; + final JSONArray categoryValues = new JSONArray(); + for (final int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart. + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple map chart. + */ + public static abstract class SimpleMapChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public SimpleMapChart(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @return The value of the chart. + */ + public abstract Country getValue(); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final Country value = this.getValue(); + + if (value == null) { + // Null = skip the chart. + return null; + } + data.put("value", value.getCountryIsoTag()); + return data; + } + + } + + /** + * Represents a custom advanced map chart. + */ + public static abstract class AdvancedMapChart extends CustomChart { + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + public AdvancedMapChart(final String chartId) { + super(chartId); + } + + /** + * Gets the value of the chart. + * + * @param valueMap Just an empty map. The only reason it exists is to + * make your life easier. You don't have to create a map + * yourself! + * @return The value of the chart. + */ + public abstract HashMap getValues(HashMap valueMap); + + @Override + protected JSONObject getChartData() { + final JSONObject data = new JSONObject(); + final JSONObject values = new JSONObject(); + final HashMap map = this.getValues(new HashMap()); + if (map == null || map.isEmpty()) { + // Null = skip the chart. + return null; + } + boolean allSkipped = true; + for (final Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid. + } + allSkipped = false; + values.put(entry.getKey().getCountryIsoTag(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart. + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * A enum which is used for custom maps. + */ + public enum Country { + + /** + * bStats will use the country of the server. + */ + AUTO_DETECT("AUTO", "Auto Detected"), + + ANDORRA("AD", "Andorra"), UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"), AFGHANISTAN("AF", "Afghanistan"), ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"), ANGUILLA("AI", "Anguilla"), ALBANIA("AL", "Albania"), ARMENIA("AM", "Armenia"), NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"), ANGOLA("AO", "Angola"), ANTARCTICA("AQ", "Antarctica"), ARGENTINA("AR", "Argentina"), AMERICAN_SAMOA("AS", "American Samoa"), AUSTRIA("AT", "Austria"), AUSTRALIA("AU", "Australia"), ARUBA("AW", "Aruba"), ALAND_ISLANDS("AX", "Åland Islands"), AZERBAIJAN("AZ", "Azerbaijan"), BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and Herzegovina"), BARBADOS("BB", "Barbados"), BANGLADESH("BD", "Bangladesh"), BELGIUM("BE", "Belgium"), BURKINA_FASO("BF", "Burkina Faso"), BULGARIA("BG", "Bulgaria"), BAHRAIN("BH", "Bahrain"), BURUNDI("BI", "Burundi"), BENIN("BJ", "Benin"), SAINT_BARTHELEMY("BL", "Saint Barthélemy"), BERMUDA("BM", "Bermuda"), BRUNEI("BN", "Brunei"), BOLIVIA("BO", "Bolivia"), BONAIRE_SINT_EUSTATIUS_AND_SABA("BQ", "Bonaire, Sint Eustatius and Saba"), BRAZIL("BR", "Brazil"), BAHAMAS("BS", "Bahamas"), BHUTAN("BT", "Bhutan"), BOUVET_ISLAND("BV", "Bouvet Island"), BOTSWANA("BW", "Botswana"), BELARUS("BY", "Belarus"), BELIZE("BZ", "Belize"), CANADA("CA", "Canada"), COCOS_ISLANDS("CC", "Cocos Islands"), THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"), CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"), CONGO("CG", "Congo"), SWITZERLAND("CH", "Switzerland"), COTE_D_IVOIRE("CI", "Côte d'Ivoire"), COOK_ISLANDS("CK", "Cook Islands"), CHILE("CL", "Chile"), CAMEROON("CM", "Cameroon"), CHINA("CN", "China"), COLOMBIA("CO", "Colombia"), COSTA_RICA("CR", "Costa Rica"), CUBA("CU", "Cuba"), CAPE_VERDE("CV", "Cape Verde"), CURACAO("CW", "Curaçao"), CHRISTMAS_ISLAND("CX", "Christmas Island"), CYPRUS("CY", "Cyprus"), CZECH_REPUBLIC("CZ", "Czech Republic"), GERMANY("DE", "Germany"), DJIBOUTI("DJ", "Djibouti"), DENMARK("DK", "Denmark"), DOMINICA("DM", "Dominica"), DOMINICAN_REPUBLIC("DO", "Dominican Republic"), ALGERIA("DZ", "Algeria"), ECUADOR("EC", "Ecuador"), ESTONIA("EE", "Estonia"), EGYPT("EG", "Egypt"), WESTERN_SAHARA("EH", "Western Sahara"), ERITREA("ER", "Eritrea"), SPAIN("ES", "Spain"), ETHIOPIA("ET", "Ethiopia"), FINLAND("FI", "Finland"), FIJI("FJ", "Fiji"), FALKLAND_ISLANDS("FK", "Falkland Islands"), MICRONESIA("FM", "Micronesia"), FAROE_ISLANDS("FO", "Faroe Islands"), FRANCE("FR", "France"), GABON("GA", "Gabon"), UNITED_KINGDOM("GB", "United Kingdom"), GRENADA("GD", "Grenada"), GEORGIA("GE", "Georgia"), FRENCH_GUIANA("GF", "French Guiana"), GUERNSEY("GG", "Guernsey"), GHANA("GH", "Ghana"), GIBRALTAR("GI", "Gibraltar"), GREENLAND("GL", "Greenland"), GAMBIA("GM", "Gambia"), GUINEA("GN", "Guinea"), GUADELOUPE("GP", "Guadeloupe"), EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"), GREECE("GR", "Greece"), SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS("GS", "South Georgia And The South Sandwich Islands"), GUATEMALA("GT", "Guatemala"), GUAM("GU", "Guam"), GUINEA_BISSAU("GW", "Guinea-Bissau"), GUYANA("GY", "Guyana"), HONG_KONG("HK", "Hong Kong"), HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island And McDonald Islands"), HONDURAS("HN", "Honduras"), CROATIA("HR", "Croatia"), HAITI("HT", "Haiti"), HUNGARY("HU", "Hungary"), INDONESIA("ID", "Indonesia"), IRELAND("IE", "Ireland"), ISRAEL("IL", "Israel"), ISLE_OF_MAN("IM", "Isle Of Man"), INDIA("IN", "India"), BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"), IRAQ("IQ", "Iraq"), IRAN("IR", "Iran"), ICELAND("IS", "Iceland"), ITALY("IT", "Italy"), JERSEY("JE", "Jersey"), JAMAICA("JM", "Jamaica"), JORDAN("JO", "Jordan"), JAPAN("JP", "Japan"), KENYA("KE", "Kenya"), KYRGYZSTAN("KG", "Kyrgyzstan"), CAMBODIA("KH", "Cambodia"), KIRIBATI("KI", "Kiribati"), COMOROS("KM", "Comoros"), SAINT_KITTS_AND_NEVIS("KN", "Saint Kitts And Nevis"), NORTH_KOREA("KP", "North Korea"), SOUTH_KOREA("KR", "South Korea"), KUWAIT("KW", "Kuwait"), CAYMAN_ISLANDS("KY", "Cayman Islands"), KAZAKHSTAN("KZ", "Kazakhstan"), LAOS("LA", "Laos"), LEBANON("LB", "Lebanon"), SAINT_LUCIA("LC", "Saint Lucia"), LIECHTENSTEIN("LI", "Liechtenstein"), SRI_LANKA("LK", "Sri Lanka"), LIBERIA("LR", "Liberia"), LESOTHO("LS", "Lesotho"), LITHUANIA("LT", "Lithuania"), LUXEMBOURG("LU", "Luxembourg"), LATVIA("LV", "Latvia"), LIBYA("LY", "Libya"), MOROCCO("MA", "Morocco"), MONACO("MC", "Monaco"), MOLDOVA("MD", "Moldova"), MONTENEGRO("ME", "Montenegro"), SAINT_MARTIN("MF", "Saint Martin"), MADAGASCAR("MG", "Madagascar"), MARSHALL_ISLANDS("MH", "Marshall Islands"), MACEDONIA("MK", "Macedonia"), MALI("ML", "Mali"), MYANMAR("MM", "Myanmar"), MONGOLIA("MN", "Mongolia"), MACAO("MO", "Macao"), NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"), MARTINIQUE("MQ", "Martinique"), MAURITANIA("MR", "Mauritania"), MONTSERRAT("MS", "Montserrat"), MALTA("MT", "Malta"), MAURITIUS("MU", "Mauritius"), MALDIVES("MV", "Maldives"), MALAWI("MW", "Malawi"), MEXICO("MX", "Mexico"), MALAYSIA("MY", "Malaysia"), MOZAMBIQUE("MZ", "Mozambique"), NAMIBIA("NA", "Namibia"), NEW_CALEDONIA("NC", "New Caledonia"), NIGER("NE", "Niger"), NORFOLK_ISLAND("NF", "Norfolk Island"), NIGERIA("NG", "Nigeria"), NICARAGUA("NI", "Nicaragua"), NETHERLANDS("NL", "Netherlands"), NORWAY("NO", "Norway"), NEPAL("NP", "Nepal"), NAURU("NR", "Nauru"), NIUE("NU", "Niue"), NEW_ZEALAND("NZ", "New Zealand"), OMAN("OM", "Oman"), PANAMA("PA", "Panama"), PERU("PE", "Peru"), FRENCH_POLYNESIA("PF", "French Polynesia"), PAPUA_NEW_GUINEA("PG", "Papua New Guinea"), PHILIPPINES("PH", "Philippines"), PAKISTAN("PK", "Pakistan"), POLAND("PL", "Poland"), SAINT_PIERRE_AND_MIQUELON("PM", "Saint Pierre And Miquelon"), PITCAIRN("PN", "Pitcairn"), PUERTO_RICO("PR", "Puerto Rico"), PALESTINE("PS", "Palestine"), PORTUGAL("PT", "Portugal"), PALAU("PW", "Palau"), PARAGUAY("PY", "Paraguay"), QATAR("QA", "Qatar"), REUNION("RE", "Reunion"), ROMANIA("RO", "Romania"), SERBIA("RS", "Serbia"), RUSSIA("RU", "Russia"), RWANDA("RW", "Rwanda"), SAUDI_ARABIA("SA", "Saudi Arabia"), SOLOMON_ISLANDS("SB", "Solomon Islands"), SEYCHELLES("SC", "Seychelles"), SUDAN("SD", "Sudan"), SWEDEN("SE", "Sweden"), SINGAPORE("SG", "Singapore"), SAINT_HELENA("SH", "Saint Helena"), SLOVENIA("SI", "Slovenia"), SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard And Jan Mayen"), SLOVAKIA("SK", "Slovakia"), SIERRA_LEONE("SL", "Sierra Leone"), SAN_MARINO("SM", "San Marino"), SENEGAL("SN", "Senegal"), SOMALIA("SO", "Somalia"), SURINAME("SR", "Suriname"), SOUTH_SUDAN("SS", "South Sudan"), SAO_TOME_AND_PRINCIPE("ST", "Sao Tome And Principe"), EL_SALVADOR("SV", "El Salvador"), SINT_MAARTEN_DUTCH_PART("SX", "Sint Maarten (Dutch part)"), SYRIA("SY", "Syria"), SWAZILAND("SZ", "Swaziland"), TURKS_AND_CAICOS_ISLANDS("TC", "Turks And Caicos Islands"), CHAD("TD", "Chad"), FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"), TOGO("TG", "Togo"), THAILAND("TH", "Thailand"), TAJIKISTAN("TJ", "Tajikistan"), TOKELAU("TK", "Tokelau"), TIMOR_LESTE("TL", "Timor-Leste"), TURKMENISTAN("TM", "Turkmenistan"), TUNISIA("TN", "Tunisia"), TONGA("TO", "Tonga"), TURKEY("TR", "Turkey"), TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"), TUVALU("TV", "Tuvalu"), TAIWAN("TW", "Taiwan"), TANZANIA("TZ", "Tanzania"), UKRAINE("UA", "Ukraine"), UGANDA("UG", "Uganda"), UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"), UNITED_STATES("US", "United States"), URUGUAY("UY", "Uruguay"), UZBEKISTAN("UZ", "Uzbekistan"), VATICAN("VA", "Vatican"), SAINT_VINCENT_AND_THE_GRENADINES("VC", "Saint Vincent And The Grenadines"), VENEZUELA("VE", "Venezuela"), BRITISH_VIRGIN_ISLANDS("VG", "British Virgin Islands"), U_S__VIRGIN_ISLANDS("VI", "U.S. Virgin Islands"), VIETNAM("VN", "Vietnam"), VANUATU("VU", "Vanuatu"), WALLIS_AND_FUTUNA("WF", "Wallis And Futuna"), SAMOA("WS", "Samoa"), YEMEN("YE", "Yemen"), MAYOTTE("YT", "Mayotte"), SOUTH_AFRICA("ZA", "South Africa"), ZAMBIA("ZM", "Zambia"), ZIMBABWE("ZW", "Zimbabwe"); + + private String isoTag; + private String name; + + Country(final String isoTag, final String name) { + this.isoTag = isoTag; + this.name = name; + } + + /** + * Gets the name of the country. + * + * @return The name of the country. + */ + public String getCountryName() { + return this.name; + } + + /** + * Gets the iso tag of the country. + * + * @return The iso tag of the country. + */ + public String getCountryIsoTag() { + return this.isoTag; + } + + /** + * Gets a country by it's iso tag. + * + * @param isoTag The iso tag of the county. + * @return The country with the given iso tag or null if + * unknown. + */ + public static Country byIsoTag(final String isoTag) { + for (final Country country : Country.values()) { + if (country.getCountryIsoTag().equals(isoTag)) { + return country; + } + } + return null; + } + + /** + * Gets a country by a locale. + * + * @param locale The locale. + * @return The country from the giben locale or null if + * unknown country or if the locale does not contain a country. + */ + public static Country byLocale(final Locale locale) { + return byIsoTag(locale.getCountry()); + } + + } + +} diff --git a/src/com/projectkorra/projectkorra/util/MovementHandler.java b/src/com/projectkorra/projectkorra/util/MovementHandler.java index 3c3cfd8ab..6aa27227a 100644 --- a/src/com/projectkorra/projectkorra/util/MovementHandler.java +++ b/src/com/projectkorra/projectkorra/util/MovementHandler.java @@ -1,5 +1,8 @@ package com.projectkorra.projectkorra.util; +import java.util.HashSet; +import java.util.Set; + import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -7,106 +10,198 @@ import org.bukkit.scheduler.BukkitRunnable; import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; /** - * An object to control how an entity moves. - *
Current functions include stopping. + * An object to control how an entity moves.
+ * Current functions include stopping. + * * @author Simplicitee * */ public class MovementHandler { - - private LivingEntity entity; - private BukkitRunnable runnable; + + public static Set handlers = new HashSet<>(); + + private final LivingEntity entity; + private BukkitRunnable runnable, msg; private ResetTask reset = null; + private final CoreAbility ability; - public MovementHandler(LivingEntity entity) { + public MovementHandler(final LivingEntity entity, final CoreAbility ability) { this.entity = entity; + this.ability = ability; + handlers.add(this); } - + /** - * This stops the movement of the entity once - * they land on the ground, acting as a "paralyze" - * @param duration how long the entity should be stopped for (in ticks) + * This stops the movement of the entity once they land on the ground, + * acting as a "paralyze" with a duration for how long they should be + * stopped + * + * @param duration how long the entity should be stopped for (in + * ticks). + * @param message the message to send to the stopped entity if they are a + * player + * @param ability ability which is stopping the player */ - public void stop(long duration, String message) { - if (entity instanceof Player) { - long start = System.currentTimeMillis(); - Player player = (Player) entity; - player.setMetadata("movement:stop", new FixedMetadataValue(ProjectKorra.plugin, 0)); - runnable = new BukkitRunnable() { + public void stopWithDuration(final long duration, final String message) { + this.entity.setMetadata("movement:stop", new FixedMetadataValue(ProjectKorra.plugin, this.ability)); + if (this.entity instanceof Player) { + final long start = System.currentTimeMillis(); + final Player player = (Player) this.entity; + this.runnable = new BukkitRunnable() { @Override public void run() { ActionBar.sendActionBar(message, player); - if (System.currentTimeMillis() >= start + duration/20*1000) { - player.removeMetadata("movement:stop", ProjectKorra.plugin); - reset(); + if (System.currentTimeMillis() >= start + duration / 20 * 1000) { + MovementHandler.this.reset(); } } - + }; - runnable.runTaskTimer(ProjectKorra.plugin, 0, 1); + this.runnable.runTaskTimer(ProjectKorra.plugin, 0, 1); } else { - runnable = new BukkitRunnable() { - + this.runnable = new BukkitRunnable() { + @Override public void run() { - allowMove(); + MovementHandler.this.reset(); } - + }; new BukkitRunnable() { - + @Override public void run() { - if (entity.isOnGround()) { - entity.setAI(false); - cancel(); - runnable.runTaskLater(ProjectKorra.plugin, duration); + if (MovementHandler.this.entity.isOnGround()) { + MovementHandler.this.entity.setAI(false); + this.cancel(); + MovementHandler.this.runnable.runTaskLater(ProjectKorra.plugin, duration); } } - + }.runTaskTimer(ProjectKorra.plugin, 0, 1); } } - - private void allowMove() { - if (!(entity instanceof Player)) { - entity.setAI(true); - } - if (reset != null) { - reset.run(); + + /** + * This stops the movement of the entity once they land on the ground, + * acting as a "paralyze" + * + * @param message the message to send to the stopped entity if they are a + * player + * @param ability ability which is stopping the player + */ + public void stop(final String message) { + this.entity.setMetadata("movement:stop", new FixedMetadataValue(ProjectKorra.plugin, this.ability)); + if (this.entity instanceof Player) { + final Player player = (Player) this.entity; + this.msg = new BukkitRunnable() { + + @Override + public void run() { + ActionBar.sendActionBar(message, player); + } + + }; + this.msg.runTaskTimer(ProjectKorra.plugin, 0, 1); + } else { + new BukkitRunnable() { + + @Override + public void run() { + if (MovementHandler.this.entity.isOnGround()) { + MovementHandler.this.entity.setAI(false); + this.cancel(); + } + } + + }.runTaskTimer(ProjectKorra.plugin, 0, 1); } + this.runnable = null; } - + /** - * Cancels the current task and allows the entity to move freely + * Resets any stopped movements and runs the {@link ResetTask} if able. */ public void reset() { - runnable.cancel(); - allowMove(); + if (this.runnable != null) { + this.runnable.cancel(); + } + if (this.msg != null) { + this.msg.cancel(); + } + if (!(this.entity instanceof Player)) { + this.entity.setAI(true); + } + if (this.reset != null) { + this.reset.run(); + } + if (this.entity.hasMetadata("movement:stop")) { + this.entity.removeMetadata("movement:stop", ProjectKorra.plugin); + } } - + + public CoreAbility getAbility() { + return this.ability; + } + public LivingEntity getEntity() { - return entity; + return this.entity; } - - public void setResetTask(ResetTask reset) { + + public void setResetTask(final ResetTask reset) { this.reset = reset; } - + /** - * Functional interface, called when the entity is allowed to - * move again, therefore "reseting" it's AI + * Functional interface, called when the entity is allowed to move again, + * therefore "reseting" it's AI + * * @author Simplicitee * */ public interface ResetTask { public void run(); } - - public static boolean isStopped(Entity entity) { + + /** + * Checks if the entity is stopped by an instance of MovementHandler + * + * @param entity the entity in question of being stopped + * @return false if not stopped by an instance of MovementHandler + */ + public static boolean isStopped(final Entity entity) { return entity.hasMetadata("movement:stop"); } + + /** + * Resets all instances of MovementHandler + */ + public static void resetAll() { + for (final MovementHandler handler : handlers) { + handler.reset(); + } + } + + /** + * Using an entity and ability, the MovementHandler associated with both + * will be found. + * + * @param entity the entity in question of being stopped + * @param ability the ability in question of doing the stopping + * @return null if no MovementHandler instance with entity and ability + * found. + */ + public static MovementHandler getFromEntityAndAbility(final Entity entity, final CoreAbility ability) { + for (final MovementHandler handler : handlers) { + if (handler.getEntity().getEntityId() == entity.getEntityId() && handler.getAbility().equals(ability)) { + return handler; + } + } + + return null; + } } diff --git a/src/com/projectkorra/projectkorra/util/ParticleEffect.java b/src/com/projectkorra/projectkorra/util/ParticleEffect.java index 66965b9c7..6239a8c11 100644 --- a/src/com/projectkorra/projectkorra/util/ParticleEffect.java +++ b/src/com/projectkorra/projectkorra/util/ParticleEffect.java @@ -1,13 +1,5 @@ package com.projectkorra.projectkorra.util; -import com.projectkorra.projectkorra.util.ReflectionHandler.PackageType; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -16,6 +8,14 @@ import java.util.Map; import java.util.Map.Entry; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import com.projectkorra.projectkorra.util.ReflectionHandler.PackageType; + /** * ParticleEffect Library *

@@ -38,7 +38,7 @@ *

* It would be nice if you provide credit to me if you use this class in a * published project - * + * * @author DarkBlade12 * @version 1.6 */ @@ -464,7 +464,6 @@ public enum ParticleEffect { * */ SPIT("spit", 48, 11); - private static final Map NAME_MAP = new HashMap(); private static final Map ID_MAP = new HashMap(); @@ -476,9 +475,9 @@ public enum ParticleEffect { private final boolean requiresData; private final boolean requiresWater; - // Initialize map for quick name and id lookup + // Initialize map for quick name and id lookup. static { - for (ParticleEffect effect : values()) { + for (final ParticleEffect effect : values()) { NAME_MAP.put(effect.name, effect); ID_MAP.put(effect.id, effect); } @@ -487,7 +486,7 @@ public enum ParticleEffect { /** * Construct a new particle effect - * + * * @param name Name of this particle effect * @param id Id of this particle effect * @param requiredVersion Version which is required (1.x) @@ -496,7 +495,7 @@ public enum ParticleEffect { * @param requiresWater Indicates whether water is required for this * particle effect to display properly */ - private ParticleEffect(String name, int id, int requiredVersion, boolean requiresData, boolean requiresWater) { + private ParticleEffect(final String name, final int id, final int requiredVersion, final boolean requiresData, final boolean requiresWater) { this.name = name; this.id = id; this.requiredVersion = requiredVersion; @@ -507,7 +506,7 @@ private ParticleEffect(String name, int id, int requiredVersion, boolean require /** * Construct a new particle effect with {@link #requiresWater} set to * false - * + * * @param name Name of this particle effect * @param id Id of this particle effect * @param requiredVersion Version which is required (1.x) @@ -515,14 +514,14 @@ private ParticleEffect(String name, int id, int requiredVersion, boolean require * this particle effect * @see #ParticleEffect(String, int, boolean, boolean) */ - private ParticleEffect(String name, int id, int requiredVersion, boolean requiresData) { + private ParticleEffect(final String name, final int id, final int requiredVersion, final boolean requiresData) { this(name, id, requiredVersion, requiresData, false); } /** * Construct a new particle effect with {@link #requiresData} and * {@link #requiresWater} set to false - * + * * @param name Name of this particle effect * @param id Id of this particle effect * @param requiredVersion Version which is required (1.x) @@ -530,77 +529,77 @@ private ParticleEffect(String name, int id, int requiredVersion, boolean require * this particle effect * @see #ParticleEffect(String, int, boolean) */ - private ParticleEffect(String name, int id, int requiredVersion) { + private ParticleEffect(final String name, final int id, final int requiredVersion) { this(name, id, requiredVersion, false); } /** * Returns the name of this particle effect - * + * * @return The name */ public String getName() { - return name; + return this.name; } /** * Returns the id of this particle effect - * + * * @return The id */ public int getId() { - return id; + return this.id; } /** * Returns the required version for this particle effect (1.x) - * + * * @return The required version */ public int getRequiredVersion() { - return requiredVersion; + return this.requiredVersion; } /** * Determine if additional data is required for this particle effect - * + * * @return Whether additional data is required or not */ public boolean getRequiresData() { - return requiresData; + return this.requiresData; } /** * Determine if water is required for this particle effect to display * properly - * + * * @return Whether water is required or not */ public boolean getRequiresWater() { - return requiresWater; + return this.requiresWater; } /** * Determine if this particle effect is supported by your current server * version - * + * * @return Whether the particle effect is supported or not */ public boolean isSupported() { - if (requiredVersion == -1) { + if (this.requiredVersion == -1) { return true; } - return ParticlePacket.getVersion() >= requiredVersion; + return ParticlePacket.getVersion() >= this.requiredVersion; } /** * Returns the particle effect with the given name - * + * * @param name Name of the particle effect * @return The particle effect */ - public static ParticleEffect fromName(String name) { - for (Entry entry : NAME_MAP.entrySet()) { + public static ParticleEffect fromName(final String name) { + for (final Entry entry : NAME_MAP.entrySet()) { if (!entry.getKey().equalsIgnoreCase(name)) { continue; } @@ -611,12 +610,12 @@ public static ParticleEffect fromName(String name) { /** * Returns the particle effect with the given id - * + * * @param id Id of the particle effect * @return The particle effect */ - public static ParticleEffect fromId(int id) { - for (Entry entry : ID_MAP.entrySet()) { + public static ParticleEffect fromId(final int id) { + for (final Entry entry : ID_MAP.entrySet()) { if (entry.getKey() != id) { continue; } @@ -627,24 +626,24 @@ public static ParticleEffect fromId(int id) { /** * Determine if water is at a certain location - * + * * @param location Location to check * @return Whether water is at this location or not */ - private static boolean isWater(Location location) { - Material material = location.getBlock().getType(); + private static boolean isWater(final Location location) { + final Material material = location.getBlock().getType(); return material == Material.WATER || material == Material.STATIONARY_WATER; } /** * Determine if the distance between @param location and one of the players * exceeds 256 - * + * * @param location Location to check * @return Whether the distance exceeds 256 or not */ - private static boolean isLongDistance(Location location, List players) { - for (Player player : players) { + private static boolean isLongDistance(final Location location, final List players) { + for (final Player player : players) { if (player.getWorld().equals(location.getWorld()) && player.getLocation().distance(location) < 256) { continue; } @@ -656,7 +655,7 @@ private static boolean isLongDistance(Location location, List players) { /** * Displays a particle effect which is only visible for all players within a * certain range in the world of @param center - * + * * @param offsetX Maximum distance particles can fly away from the center on * the x-axis * @param offsetY Maximum distance particles can fly away from the center on @@ -676,14 +675,14 @@ private static boolean isLongDistance(Location location, List players) { * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { + public void display(final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (requiresData) { + if (this.requiresData) { throw new ParticleDataException("This particle effect requires additional data"); } - if (requiresWater && !isWater(center)) { + if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException("There is no water at the center location"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); @@ -692,7 +691,7 @@ public void display(float offsetX, float offsetY, float offsetZ, float speed, in /** * Displays a particle effect which is only visible for all players within a * certain range in the world of @param center - * + * * @param offsetX Maximum distance particles can fly away from the center on * the x-axis * @param offsetY Maximum distance particles can fly away from the center on @@ -711,14 +710,14 @@ public void display(float offsetX, float offsetY, float offsetZ, float speed, in * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ - public void display(Location center, float offsetX, float offsetY, float offsetZ, float speed, int amount) { - display(offsetX, offsetY, offsetZ, speed, amount, center, RANGE); + public void display(final Location center, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount) { + this.display(offsetX, offsetY, offsetZ, speed, amount, center, RANGE); } /** * Displays a particle effect which is only visible for the specified * players - * + * * @param offsetX Maximum distance particles can fly away from the center on * the x-axis * @param offsetY Maximum distance particles can fly away from the center on @@ -738,14 +737,14 @@ public void display(Location center, float offsetX, float offsetY, float offsetZ * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { + public void display(final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (requiresData) { + if (this.requiresData) { throw new ParticleDataException("This particle effect requires additional data"); } - if (requiresWater && !isWater(center)) { + if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException("There is no water at the center location"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); @@ -755,7 +754,7 @@ public void display(float offsetX, float offsetY, float offsetZ, float speed, in * Displays a single particle which flies into a determined direction and is * only visible for all players within a certain range in the world * of @param center - * + * * @param direction Direction of the particle * @param speed Display speed of the particle * @param center Center location of the effect @@ -769,14 +768,14 @@ public void display(float offsetX, float offsetY, float offsetZ, float speed, in * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ - public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { + public void display(final Vector direction, final float speed, final Location center, final double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (requiresData) { + if (this.requiresData) { throw new ParticleDataException("This particle effect requires additional data"); } - if (requiresWater && !isWater(center)) { + if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException("There is no water at the center location"); } new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); @@ -785,7 +784,7 @@ public void display(Vector direction, float speed, Location center, double range /** * Displays a single particle which flies into a determined direction and is * only visible for the specified players - * + * * @param direction Direction of the particle * @param speed Display speed of the particle * @param center Center location of the effect @@ -799,14 +798,14 @@ public void display(Vector direction, float speed, Location center, double range * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { + public void display(final Vector direction, final float speed, final Location center, final List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (requiresData) { + if (this.requiresData) { throw new ParticleDataException("This particle effect requires additional data"); } - if (requiresWater && !isWater(center)) { + if (this.requiresWater && !isWater(center)) { throw new IllegalArgumentException("There is no water at the center location"); } new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players); @@ -816,7 +815,7 @@ public void display(Vector direction, float speed, Location center, List * Displays a particle effect which requires additional data and is only * visible for all players within a certain range in the world of @param * center - * + * * @param data Data of the effect * @param offsetX Maximum distance particles can fly away from the center on * the x-axis @@ -835,11 +834,11 @@ public void display(Vector direction, float speed, Location center, List * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { + public void display(final ParticleData data, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final double range) throws ParticleVersionException, ParticleDataException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (!requiresData) { + if (!this.requiresData) { throw new ParticleDataException("This particle effect does not require additional data"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); @@ -848,7 +847,7 @@ public void display(ParticleData data, float offsetX, float offsetY, float offse /** * Displays a particle effect which requires additional data and is only * visible for the specified players - * + * * @param data Data of the effect * @param offsetX Maximum distance particles can fly away from the center on * the x-axis @@ -867,11 +866,11 @@ public void display(ParticleData data, float offsetX, float offsetY, float offse * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { + public void display(final ParticleData data, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final Location center, final List players) throws ParticleVersionException, ParticleDataException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (!requiresData) { + if (!this.requiresData) { throw new ParticleDataException("This particle effect does not require additional data"); } new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); @@ -881,7 +880,7 @@ public void display(ParticleData data, float offsetX, float offsetY, float offse * Displays a single particle which requires additional data that flies into * a determined direction and is only visible for all players within a * certain range in the world of @param center - * + * * @param data Data of the effect * @param direction Direction of the particle * @param speed Display speed of the particles @@ -894,11 +893,11 @@ public void display(ParticleData data, float offsetX, float offsetY, float offse * @see ParticlePacket * @see ParticlePacket#sendTo(Location, double) */ - public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { + public void display(final ParticleData data, final Vector direction, final float speed, final Location center, final double range) throws ParticleVersionException, ParticleDataException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (!requiresData) { + if (!this.requiresData) { throw new ParticleDataException("This particle effect does not require additional data"); } new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); @@ -907,7 +906,7 @@ public void display(ParticleData data, Vector direction, float speed, Location c /** * Displays a single particle which requires additional data that flies into * a determined direction and is only visible for the specified players - * + * * @param data Data of the effect * @param direction Direction of the particle * @param speed Display speed of the particles @@ -920,11 +919,11 @@ public void display(ParticleData data, Vector direction, float speed, Location c * @see ParticlePacket * @see ParticlePacket#sendTo(Location, List) */ - public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { + public void display(final ParticleData data, final Vector direction, final float speed, final Location center, final List players) throws ParticleVersionException, ParticleDataException { + if (!this.isSupported()) { throw new ParticleVersionException("This particle effect is not supported by your server version"); } - if (!requiresData) { + if (!this.requiresData) { throw new ParticleDataException("This particle effect does not require additional data"); } new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players); @@ -937,7 +936,7 @@ public void display(ParticleData data, Vector direction, float speed, Location c *

* This class is part of the ParticleEffect Library and follows the * same usage conditions - * + * * @author DarkBlade12 * @since 1.6 */ @@ -948,12 +947,11 @@ public static abstract class ParticleData { /** * Construct a new particle data - * + * * @param material Material of the item/block * @param data Data value of the item/block */ - @SuppressWarnings("deprecation") - public ParticleData(Material material, byte data) { + public ParticleData(final Material material, final byte data) { this.material = material; this.data = data; this.packetData = new int[] { material.getId(), data }; @@ -961,49 +959,49 @@ public ParticleData(Material material, byte data) { /** * Returns the material of this data - * + * * @return The material */ public Material getMaterial() { - return material; + return this.material; } /** * Returns the data value of this data - * + * * @return The data value */ public byte getData() { - return data; + return this.data; } /** * Returns the data as an int array for packet construction - * + * * @return The data for the packet */ public int[] getPacketData() { - return packetData; + return this.packetData; } /** * Returns the data as a string for pre 1.8 versions - * + * * @return The data string for the packet */ public String getPacketDataString() { - return "_" + packetData[0] + "_" + packetData[1]; + return "_" + this.packetData[0] + "_" + this.packetData[1]; } /** * Sets the packet data. Should be an integer array. For ITEM_CRACK and * BLOCK_DUST, it should be [id, meta] but for BLOCK_CRACK it should be * [id + (meta * 4096)] - * + * * @param data The packet data. */ - public void setPacketData(int[] data) { - packetData = data; + public void setPacketData(final int[] data) { + this.packetData = data; } } @@ -1012,19 +1010,19 @@ public void setPacketData(int[] data) { *

* This class is part of the ParticleEffect Library and follows the * same usage conditions. - * + * * @author DarkBlade12 * @since 1.6 */ public static final class ItemData extends ParticleData { /** * Construct a new item data. - * + * * @param material Material of the item * @param data Data value of the item * @see ParticleData#ParticleData(Material, byte) */ - public ItemData(Material material, byte data) { + public ItemData(final Material material, final byte data) { super(material, data); } } @@ -1035,21 +1033,20 @@ public ItemData(Material material, byte data) { *

* This class is part of the ParticleEffect Library and follows the * same usage conditions - * + * * @author DarkBlade12 * @since 1.6 */ public static final class BlockData extends ParticleData { /** * Construct a new block data - * + * * @param material Material of the block * @param data Data value of the block * @throws IllegalArgumentException If the material is not a block * @see ParticleData#ParticleData(Material, byte) */ - @SuppressWarnings("deprecation") - public BlockData(Material material, byte data) throws IllegalArgumentException { + public BlockData(final Material material, final byte data) throws IllegalArgumentException { super(material, data); if (!material.isBlock()) { throw new IllegalArgumentException("The material is not a block"); @@ -1065,7 +1062,7 @@ public BlockData(Material material, byte data) throws IllegalArgumentException { *

* This class is part of the ParticleEffect Library and follows the * same usage conditions - * + * * @author DarkBlade12 * @since 1.6 */ @@ -1074,11 +1071,11 @@ private static final class ParticleDataException extends RuntimeException { /** * Construct a new particle data exception - * + * * @param message Message that will be logged * @param cause Cause of the exception */ - public ParticleDataException(String message) { + public ParticleDataException(final String message) { super(message); } } @@ -1089,7 +1086,7 @@ public ParticleDataException(String message) { *

* This class is part of the ParticleEffect Library and follows the * same usage conditions - * + * * @author DarkBlade12 * @since 1.6 */ @@ -1098,11 +1095,11 @@ private static final class ParticleVersionException extends RuntimeException { /** * Construct a new particle version exception - * + * * @param message Message that will be logged * @param cause Cause of the exception */ - public ParticleVersionException(String message) { + public ParticleVersionException(final String message) { super(message); } } @@ -1113,7 +1110,7 @@ public ParticleVersionException(String message) { *

* This class is part of the ParticleEffect Library and follows the * same usage conditions - * + * * @author DarkBlade12 * @since 1.5 */ @@ -1137,7 +1134,7 @@ public static final class ParticlePacket { /** * Construct a new particle packet - * + * * @param effect Particle effect * @param offsetX Maximum distance particles can fly away from the * center on the x-axis @@ -1154,7 +1151,7 @@ public static final class ParticlePacket { * amount is lower than 1 * @see #initialize() */ - public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException { + public ParticlePacket(final ParticleEffect effect, final float offsetX, final float offsetY, final float offsetZ, final float speed, final int amount, final boolean longDistance, final ParticleData data) throws IllegalArgumentException { initialize(); if (speed < 0) { throw new IllegalArgumentException("The speed is lower than 0"); @@ -1172,7 +1169,7 @@ public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float /** * Construct a new particle packet of a single particle flying into a * determined direction - * + * * @param effect Particle effect * @param direction Direction of the particle * @param speed Display speed of the particle @@ -1182,7 +1179,7 @@ public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float * @throws IllegalArgumentException If the speed is lower than 0 * @see #initialize() */ - public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException { + public ParticlePacket(final ParticleEffect effect, final Vector direction, final float speed, final boolean longDistance, final ParticleData data) throws IllegalArgumentException { initialize(); if (speed < 0) { throw new IllegalArgumentException("The speed is lower than 0"); @@ -1205,7 +1202,7 @@ public ParticlePacket(ParticleEffect effect, Vector direction, float speed, bool * Note: These fields only have to be initialized once, so it * will return if {@link #initialized} is already set to * true - * + * * @throws VersionIncompatibleException if your bukkit version is not * supported by this library */ @@ -1218,13 +1215,13 @@ public static void initialize() throws VersionIncompatibleException { if (version > 7) { enumParticle = PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); } - Class packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); + final Class packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); packetConstructor = ReflectionHandler.getConstructor(packetClass); getHandle = ReflectionHandler.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); playerConnection = ReflectionHandler.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); sendPacket = ReflectionHandler.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); } - catch (Exception exception) { + catch (final Exception exception) { throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception); } initialized = true; @@ -1232,7 +1229,7 @@ public static void initialize() throws VersionIncompatibleException { /** * Returns the version of your server (1.x) - * + * * @return The version number */ public static int getVersion() { @@ -1242,7 +1239,7 @@ public static int getVersion() { /** * Determine if {@link #packetConstructor}, {@link #getHandle}, * {@link #playerConnection} and {@link #sendPacket} are initialized - * + * * @return Whether these fields are initialized or not * @see #initialize() */ @@ -1252,7 +1249,7 @@ public static boolean isInitialized() { /** * Sends the packet to a single player and caches it - * + * * @param center Center location of the effect * @param player Receiver of the packet * @throws PacketInstantiationException if instantion fails due to an @@ -1260,65 +1257,65 @@ public static boolean isInitialized() { * @throws PacketSendingException if sending fails due to an unknown * error */ - public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException { - if (packet == null) { + public void sendTo(final Location center, final Player player) throws PacketInstantiationException, PacketSendingException { + if (this.packet == null) { try { - packet = packetConstructor.newInstance(); + this.packet = packetConstructor.newInstance(); Object id; if (version < 8) { - id = effect.getName(); - if (data != null) { - id += data.getPacketDataString(); + id = this.effect.getName(); + if (this.data != null) { + id += this.data.getPacketDataString(); } } else { - id = enumParticle.getEnumConstants()[effect.getId()]; + id = enumParticle.getEnumConstants()[this.effect.getId()]; } - ReflectionHandler.setValue(packet, true, "a", id); - ReflectionHandler.setValue(packet, true, "b", (float) center.getX()); - ReflectionHandler.setValue(packet, true, "c", (float) center.getY()); - ReflectionHandler.setValue(packet, true, "d", (float) center.getZ()); - ReflectionHandler.setValue(packet, true, "e", offsetX); - ReflectionHandler.setValue(packet, true, "f", offsetY); - ReflectionHandler.setValue(packet, true, "g", offsetZ); - ReflectionHandler.setValue(packet, true, "h", speed); - ReflectionHandler.setValue(packet, true, "i", amount); + ReflectionHandler.setValue(this.packet, true, "a", id); + ReflectionHandler.setValue(this.packet, true, "b", (float) center.getX()); + ReflectionHandler.setValue(this.packet, true, "c", (float) center.getY()); + ReflectionHandler.setValue(this.packet, true, "d", (float) center.getZ()); + ReflectionHandler.setValue(this.packet, true, "e", this.offsetX); + ReflectionHandler.setValue(this.packet, true, "f", this.offsetY); + ReflectionHandler.setValue(this.packet, true, "g", this.offsetZ); + ReflectionHandler.setValue(this.packet, true, "h", this.speed); + ReflectionHandler.setValue(this.packet, true, "i", this.amount); if (version > 7) { - ReflectionHandler.setValue(packet, true, "j", longDistance); - ReflectionHandler.setValue(packet, true, "k", data == null ? new int[0] : data.getPacketData()); + ReflectionHandler.setValue(this.packet, true, "j", this.longDistance); + ReflectionHandler.setValue(this.packet, true, "k", this.data == null ? new int[0] : this.data.getPacketData()); } } - catch (Exception exception) { + catch (final Exception exception) { throw new PacketInstantiationException("Packet instantiation failed", exception); } } try { - sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); + sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), this.packet); } - catch (Exception exception) { + catch (final Exception exception) { throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); } } /** * Sends the packet to all players in the list - * + * * @param center Center location of the effect * @param players Receivers of the packet * @throws IllegalArgumentException If the player list is empty * @see #sendTo(Location center, Player player) */ - public void sendTo(Location center, List players) throws IllegalArgumentException { + public void sendTo(final Location center, final List players) throws IllegalArgumentException { if (players.isEmpty()) { throw new IllegalArgumentException("The player list is empty"); } - for (Player player : players) { - sendTo(center, player); + for (final Player player : players) { + this.sendTo(center, player); } } /** * Sends the packet to all players in a certain range - * + * * @param center Center location of the effect * @param range Range in which players will receive the packet (Maximum * range for particles is usually 16, but it can differ for @@ -1326,17 +1323,17 @@ public void sendTo(Location center, List players) throws IllegalArgument * @throws IllegalArgumentException If the range is lower than 1 * @see #sendTo(Location center, Player player) */ - public void sendTo(Location center, double range) throws IllegalArgumentException { + public void sendTo(final Location center, final double range) throws IllegalArgumentException { if (range < 1) { throw new IllegalArgumentException("The range is lower than 1"); } - - double squared = range * range; - for (Player player : Bukkit.getOnlinePlayers()) { + + final double squared = range * range; + for (final Player player : Bukkit.getOnlinePlayers()) { if (player.getWorld() != center.getWorld() || player.getLocation().distanceSquared(center) > squared) { continue; } - sendTo(center, player); + this.sendTo(center, player); } } @@ -1346,7 +1343,7 @@ public void sendTo(Location center, double range) throws IllegalArgumentExceptio *

* This class is part of the ParticleEffect Library and follows * the same usage conditions - * + * * @author DarkBlade12 * @since 1.5 */ @@ -1355,11 +1352,11 @@ private static final class VersionIncompatibleException extends RuntimeException /** * Construct a new version incompatible exception - * + * * @param message Message that will be logged * @param cause Cause of the exception */ - public VersionIncompatibleException(String message, Throwable cause) { + public VersionIncompatibleException(final String message, final Throwable cause) { super(message, cause); } } @@ -1370,7 +1367,7 @@ public VersionIncompatibleException(String message, Throwable cause) { *

* This class is part of the ParticleEffect Library and follows * the same usage conditions - * + * * @author DarkBlade12 * @since 1.4 */ @@ -1379,11 +1376,11 @@ private static final class PacketInstantiationException extends RuntimeException /** * Construct a new packet instantiation exception - * + * * @param message Message that will be logged * @param cause Cause of the exception */ - public PacketInstantiationException(String message, Throwable cause) { + public PacketInstantiationException(final String message, final Throwable cause) { super(message, cause); } } @@ -1393,7 +1390,7 @@ public PacketInstantiationException(String message, Throwable cause) { *

* This class is part of the ParticleEffect Library and follows * the same usage conditions - * + * * @author DarkBlade12 * @since 1.4 */ @@ -1402,11 +1399,11 @@ private static final class PacketSendingException extends RuntimeException { /** * Construct a new packet sending exception - * + * * @param message Message that will be logged * @param cause Cause of the exception */ - public PacketSendingException(String message, Throwable cause) { + public PacketSendingException(final String message, final Throwable cause) { super(message, cause); } } diff --git a/src/com/projectkorra/projectkorra/util/PassiveHandler.java b/src/com/projectkorra/projectkorra/util/PassiveHandler.java index 5e2677c47..443308a6d 100644 --- a/src/com/projectkorra/projectkorra/util/PassiveHandler.java +++ b/src/com/projectkorra/projectkorra/util/PassiveHandler.java @@ -8,39 +8,38 @@ import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.util.PassiveManager; -import com.projectkorra.projectkorra.airbending.passive.AirPassive; import com.projectkorra.projectkorra.airbending.passive.AirSaturation; -import com.projectkorra.projectkorra.chiblocking.passive.ChiPassive; import com.projectkorra.projectkorra.chiblocking.passive.ChiSaturation; import com.projectkorra.projectkorra.command.Commands; import com.projectkorra.projectkorra.configuration.ConfigManager; public class PassiveHandler { - private static final Map FOOD = new ConcurrentHashMap<>(); - public static float getExhaustion(Player player, float level, double factor) { + public static float getExhaustion(final Player player, float level, final double factor) { if (!FOOD.keySet().contains(player)) { FOOD.put(player, level); return level; } else { - float oldlevel = FOOD.get(player); + final float oldlevel = FOOD.get(player); if (level < oldlevel) { level = 0; } else { level = (float) ((level - oldlevel) * factor + oldlevel); } + FOOD.put(player, level); return level; } } - public static void checkExhaustionPassives(Player player) { + public static void checkExhaustionPassives(final Player player) { if (!CoreAbility.getAbility(AirSaturation.class).isEnabled() && !CoreAbility.getAbility(ChiSaturation.class).isEnabled()) { return; } - double air = AirPassive.getExhaustionFactor(); - double chi = ChiPassive.getExhaustionFactor(); + + double air = AirSaturation.getExhaustionFactor(); + double chi = ChiSaturation.getExhaustionFactor(); if (ConfigManager.defaultConfig.get().getStringList("Properties.DisabledWorlds").contains(player.getWorld().getName())) { return; @@ -50,93 +49,25 @@ public static void checkExhaustionPassives(Player player) { return; } - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (bPlayer == null) + if (bPlayer == null) { return; + } - if (!PassiveManager.hasPassive(player, CoreAbility.getAbility(AirSaturation.class))) + if (!PassiveManager.hasPassive(player, CoreAbility.getAbility(AirSaturation.class))) { air = 0; - if (!PassiveManager.hasPassive(player, CoreAbility.getAbility(ChiSaturation.class))) + } + + if (!PassiveManager.hasPassive(player, CoreAbility.getAbility(ChiSaturation.class))) { chi = 0; + } - double max = Math.max(air, chi); - if (max == 0) + final double max = Math.max(air, chi); + if (max == 0) { return; - else { + } else { player.setExhaustion(getExhaustion(player, player.getExhaustion(), max)); } } - - /* - * public static void checkSpeedPassives(Player player) { if - * (!player.isSprinting()) return; int air = AirPassive.getSpeedPower(); int - * chi = ChiPassive.getSpeedPower(); int earth = - * EarthPassive.getSandRunSpeed(); - * - * if (ConfigManager.defaultConfig.get().getStringList( - * "Properties.DisabledWorlds").contains(player.getWorld().getName())) { - * return; } - * - * if (Commands.isToggledForAll && - * ConfigManager.defaultConfig.get().getBoolean( - * "Properties.TogglePassivesWithAllBending")) { return; } - * - * boolean sandbender = true; BendingPlayer bPlayer = - * BendingPlayer.getBendingPlayer(player); - * - * if (bPlayer == null) return; if (!bPlayer.canBendPassive(Element.EARTH)) - * sandbender = false; if (!bPlayer.hasSubElement(SubElement.SAND)) - * sandbender = false; if (!bPlayer.canBendPassive(Element.AIR)) air = 0; if - * (!bPlayer.canBendPassive(Element.CHI)) chi = 0; - * - * int max = 0; - * - * if (sandbender && - * EarthAbility.isSand(player.getLocation().getBlock().getRelative(BlockFace - * .DOWN))) { if (CoreAbility.hasAbility(player, AcrobatStance.class)) { - * AcrobatStance abil = CoreAbility.getAbility(player, AcrobatStance.class); - * max = Math.max(air, chi); max = Math.max(max, abil.getSpeed()); max = - * Math.max(max, earth); } else { max = Math.max(air, chi); max = - * Math.max(max, earth); } } else { if (CoreAbility.hasAbility(player, - * AcrobatStance.class)) { AcrobatStance abil = - * CoreAbility.getAbility(player, AcrobatStance.class); max = Math.max(air, - * chi); max = Math.max(max, abil.getSpeed()); } else { max = Math.max(air, - * chi); } } - * - * if (max == 0) return; boolean b = true; if - * (player.hasPotionEffect(PotionEffectType.SPEED)) { for (PotionEffect - * potion : player.getActivePotionEffects()) { if (potion.getType() == - * PotionEffectType.SPEED) { if (potion.getAmplifier() > max - 1) b = false; - * } } } if (b) { player.addPotionEffect(new - * PotionEffect(PotionEffectType.SPEED, 15, max-1, true, false), false); } } - * - * public static void checkJumpPassives(Player player) { if - * (!player.isSprinting()) return; int air = AirPassive.getJumpPower(); int - * chi = ChiPassive.getJumpPower(); - * - * if (ConfigManager.defaultConfig.get().getStringList( - * "Properties.DisabledWorlds").contains(player.getWorld().getName())) { - * return; } - * - * if (Commands.isToggledForAll && - * ConfigManager.defaultConfig.get().getBoolean( - * "Properties.TogglePassivesWithAllBending")) { return; } - * - * BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - * - * if (bPlayer == null) return; if (!bPlayer.canBendPassive(Element.AIR)) - * air = 0; if (!bPlayer.canBendPassive(Element.CHI)) chi = 0; int max = 0; - * if (CoreAbility.hasAbility(player, AcrobatStance.class)) { AcrobatStance - * abil = CoreAbility.getAbility(player, AcrobatStance.class); max = - * Math.max(air, chi); max = Math.max(max, abil.getSpeed()); } else { max = - * Math.max(air, chi); } - * - * if (max == 0) return; boolean b = true; if - * (player.hasPotionEffect(PotionEffectType.JUMP)) { for (PotionEffect - * potion : player.getActivePotionEffects()) { if (potion.getType() == - * PotionEffectType.JUMP) { if (potion.getAmplifier() > max - 1) b = false; - * } } } if (b) { player.addPotionEffect(new - * PotionEffect(PotionEffectType.JUMP, 15, max-1, true, false), false); } } - */ } diff --git a/src/com/projectkorra/projectkorra/util/ReflectionHandler.java b/src/com/projectkorra/projectkorra/util/ReflectionHandler.java index 9f31b56d3..04f7d2614 100644 --- a/src/com/projectkorra/projectkorra/util/ReflectionHandler.java +++ b/src/com/projectkorra/projectkorra/util/ReflectionHandler.java @@ -1,7 +1,5 @@ package com.projectkorra.projectkorra.util; -import org.bukkit.Bukkit; - import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -9,6 +7,8 @@ import java.util.HashMap; import java.util.Map; +import org.bukkit.Bukkit; + /** * ReflectionUtils *

@@ -24,18 +24,18 @@ *

* It would be nice if you provide credit to me if you use this class in a * published project - * + * * @author DarkBlade12 * @version 1.1 */ public final class ReflectionHandler { - // Prevent accidental construction + // Prevent accidental construction. private ReflectionHandler() { } /** * Returns the constructor of a given class with the given parameter types - * + * * @param clazz Target class * @param parameterTypes Parameter types of the desired constructor * @return The constructor of the target class with the specified parameter @@ -46,9 +46,9 @@ private ReflectionHandler() { * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ - public static Constructor getConstructor(Class clazz, Class... parameterTypes) throws NoSuchMethodException { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for (Constructor constructor : clazz.getConstructors()) { + public static Constructor getConstructor(final Class clazz, final Class... parameterTypes) throws NoSuchMethodException { + final Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); + for (final Constructor constructor : clazz.getConstructors()) { if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) { continue; } @@ -59,7 +59,7 @@ public static Constructor getConstructor(Class clazz, Class... paramete /** * Returns the constructor of a desired class with the given parameter types - * + * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param parameterTypes Parameter types of the desired constructor @@ -72,13 +72,13 @@ public static Constructor getConstructor(Class clazz, Class... paramete * found * @see #getConstructor(Class, Class...) */ - public static Constructor getConstructor(String className, PackageType packageType, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { + public static Constructor getConstructor(final String className, final PackageType packageType, final Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getConstructor(packageType.getClass(className), parameterTypes); } /** * Returns an instance of a class with the given arguments - * + * * @param clazz Target class * @param arguments Arguments which are used to construct an object of the * target class @@ -96,13 +96,13 @@ public static Constructor getConstructor(String className, PackageType packag * @throws NoSuchMethodException If the desired constructor with the * specified arguments cannot be found */ - public static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + public static Object instantiateObject(final Class clazz, final Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); } /** * Returns an instance of a desired class with the given arguments - * + * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param arguments Arguments which are used to construct an object of the @@ -125,13 +125,13 @@ public static Object instantiateObject(Class clazz, Object... arguments) thro * specified name and package cannot be found * @see #instantiateObject(Class, Object...) */ - public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + public static Object instantiateObject(final String className, final PackageType packageType, final Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return instantiateObject(packageType.getClass(className), arguments); } /** * Returns a method of a class with the given parameter types - * + * * @param clazz Target class * @param methodName Name of the desired method * @param parameterTypes Parameter types of the desired method @@ -142,9 +142,9 @@ public static Object instantiateObject(String className, PackageType packageType * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ - public static Method getMethod(Class clazz, String methodName, Class... parameterTypes) throws NoSuchMethodException { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for (Method method : clazz.getMethods()) { + public static Method getMethod(final Class clazz, final String methodName, final Class... parameterTypes) throws NoSuchMethodException { + final Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); + for (final Method method : clazz.getMethods()) { if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { continue; } @@ -155,7 +155,7 @@ public static Method getMethod(Class clazz, String methodName, Class... pa /** * Returns a method of a desired class with the given parameter types - * + * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param methodName Name of the desired method @@ -169,13 +169,13 @@ public static Method getMethod(Class clazz, String methodName, Class... pa * specified name and package cannot be found * @see #getMethod(Class, String, Class...) */ - public static Method getMethod(String className, PackageType packageType, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { + public static Method getMethod(final String className, final PackageType packageType, final String methodName, final Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getMethod(packageType.getClass(className), methodName, parameterTypes); } /** * Invokes a method on an object with the given arguments - * + * * @param instance Target object * @param methodName Name of the desired method * @param arguments Arguments which are used to invoke the desired method @@ -194,14 +194,14 @@ public static Method getMethod(String className, PackageType packageType, String * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ - public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + public static Object invokeMethod(final Object instance, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** * Invokes a method of the target class on an object with the given * arguments - * + * * @param instance Target object * @param clazz Target class * @param methodName Name of the desired method @@ -220,13 +220,13 @@ public static Object invokeMethod(Object instance, String methodName, Object... * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ - public static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + public static Object invokeMethod(final Object instance, final Class clazz, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** * Invokes a method of a desired class on an object with the given arguments - * + * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located @@ -247,13 +247,13 @@ public static Object invokeMethod(Object instance, Class clazz, String method * specified name and package cannot be found * @see #invokeMethod(Object, Class, String, Object...) */ - public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + public static Object invokeMethod(final Object instance, final String className, final PackageType packageType, final String methodName, final Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return invokeMethod(instance, packageType.getClass(className), methodName, arguments); } /** * Returns a field of the target class with the given name - * + * * @param clazz Target class * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field @@ -262,15 +262,15 @@ public static Object invokeMethod(Object instance, String className, PackageType * cannot be found * @throws SecurityException If the desired field cannot be made accessible */ - public static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { - Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); + public static Field getField(final Class clazz, final boolean declared, final String fieldName) throws NoSuchFieldException, SecurityException { + final Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); field.setAccessible(true); return field; } /** * Returns a field of a desired class with the given name - * + * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param declared Whether the desired field is declared or not @@ -283,13 +283,13 @@ public static Field getField(Class clazz, boolean declared, String fieldName) * specified name and package cannot be found * @see #getField(Class, boolean, String) */ - public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { + public static Field getField(final String className, final PackageType packageType, final boolean declared, final String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { return getField(packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field of the given class of an object - * + * * @param instance Target object * @param clazz Target class * @param declared Whether the desired field is declared or not @@ -303,13 +303,13 @@ public static Field getField(String className, PackageType packageType, boolean * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ - public static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + public static Object getValue(final Object instance, final Class clazz, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getField(clazz, declared, fieldName).get(instance); } /** * Returns the value of a field of a desired class of an object - * + * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located @@ -326,13 +326,13 @@ public static Object getValue(Object instance, Class clazz, boolean declared, * specified name and package cannot be found * @see #getValue(Object, Class, boolean, String) */ - public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { + public static Object getValue(final Object instance, final String className, final PackageType packageType, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { return getValue(instance, packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field with the given name of an object - * + * * @param instance Target object * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field @@ -346,13 +346,13 @@ public static Object getValue(Object instance, String className, PackageType pac * @throws SecurityException If the desired field cannot be made accessible * @see #getValue(Object, Class, boolean, String) */ - public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + public static Object getValue(final Object instance, final boolean declared, final String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getValue(instance, instance.getClass(), declared, fieldName); } /** * Sets the value of a field of the given class of an object - * + * * @param instance Target object * @param clazz Target class * @param declared Whether the desired field is declared or not @@ -366,13 +366,13 @@ public static Object getValue(Object instance, boolean declared, String fieldNam * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ - public static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + public static void setValue(final Object instance, final Class clazz, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { getField(clazz, declared, fieldName).set(instance, value); } /** * Sets the value of a field of a desired class of an object - * + * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located @@ -389,13 +389,13 @@ public static void setValue(Object instance, Class clazz, boolean declared, S * specified name and package cannot be found * @see #setValue(Object, Class, boolean, String, Object) */ - public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { + public static void setValue(final Object instance, final String className, final PackageType packageType, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { setValue(instance, packageType.getClass(className), declared, fieldName, value); } /** * Sets the value of a field with the given name of an object - * + * * @param instance Target object * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field @@ -408,7 +408,7 @@ public static void setValue(Object instance, String className, PackageType packa * @throws SecurityException If the desired field cannot be made accessible * @see #setValue(Object, Class, boolean, String, Object) */ - public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + public static void setValue(final Object instance, final boolean declared, final String fieldName, final Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { setValue(instance, instance.getClass(), declared, fieldName, value); } @@ -417,7 +417,7 @@ public static void setValue(Object instance, boolean declared, String fieldName, *

* This class is part of the ReflectionUtils and follows the same * usage conditions - * + * * @author DarkBlade12 * @since 1.0 */ @@ -428,53 +428,53 @@ public enum PackageType { /** * Construct a new package type - * + * * @param path Path of the package */ - private PackageType(String path) { + private PackageType(final String path) { this.path = path; } /** * Construct a new package type - * + * * @param parent Parent package of the package * @param path Path of the package */ - private PackageType(PackageType parent, String path) { + private PackageType(final PackageType parent, final String path) { this(parent + "." + path); } /** * Returns the path of this package type - * + * * @return The path */ public String getPath() { - return path; + return this.path; } /** * Returns the class with the given name - * + * * @param className Name of the desired class * @return The class with the specified name * @throws ClassNotFoundException If the desired class with the * specified name and package cannot be found */ - public Class getClass(String className) throws ClassNotFoundException { + public Class getClass(final String className) throws ClassNotFoundException { return Class.forName(this + "." + className); } - // Override for convenience + // Override for convenience. @Override public String toString() { - return path; + return this.path; } /** * Returns the version of your server - * + * * @return The server version */ public static String getServerVersion() { @@ -487,7 +487,7 @@ public static String getServerVersion() { *

* This class is part of the ReflectionUtils and follows the same * usage conditions - * + * * @author DarkBlade12 * @since 1.0 */ @@ -498,9 +498,9 @@ public enum DataType { private final Class primitive; private final Class reference; - // Initialize map for quick class lookup + // Initialize map for quick class lookup. static { - for (DataType type : values()) { + for (final DataType type : values()) { CLASS_MAP.put(type.primitive, type); CLASS_MAP.put(type.reference, type); } @@ -508,76 +508,76 @@ public enum DataType { /** * Construct a new data type - * + * * @param primitive Primitive class of this data type * @param reference Reference class of this data type */ - private DataType(Class primitive, Class reference) { + private DataType(final Class primitive, final Class reference) { this.primitive = primitive; this.reference = reference; } /** * Returns the primitive class of this data type - * + * * @return The primitive class */ public Class getPrimitive() { - return primitive; + return this.primitive; } /** * Returns the reference class of this data type - * + * * @return The reference class */ public Class getReference() { - return reference; + return this.reference; } /** * Returns the data type with the given primitive/reference class - * + * * @param clazz Primitive/Reference class of the data type * @return The data type */ - public static DataType fromClass(Class clazz) { + public static DataType fromClass(final Class clazz) { return CLASS_MAP.get(clazz); } /** * Returns the primitive class of the data type with the given reference * class - * + * * @param clazz Reference class of the data type * @return The primitive class */ - public static Class getPrimitive(Class clazz) { - DataType type = fromClass(clazz); + public static Class getPrimitive(final Class clazz) { + final DataType type = fromClass(clazz); return type == null ? clazz : type.getPrimitive(); } /** * Returns the reference class of the data type with the given primitive * class - * + * * @param clazz Primitive class of the data type * @return The reference class */ - public static Class getReference(Class clazz) { - DataType type = fromClass(clazz); + public static Class getReference(final Class clazz) { + final DataType type = fromClass(clazz); return type == null ? clazz : type.getReference(); } /** * Returns the primitive class array of the given class array - * + * * @param classes Given class array * @return The primitive class array */ - public static Class[] getPrimitive(Class[] classes) { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; + public static Class[] getPrimitive(final Class[] classes) { + final int length = classes == null ? 0 : classes.length; + final Class[] types = new Class[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(classes[index]); } @@ -586,13 +586,13 @@ public static Class[] getPrimitive(Class[] classes) { /** * Returns the reference class array of the given class array - * + * * @param classes Given class array * @return The reference class array */ - public static Class[] getReference(Class[] classes) { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; + public static Class[] getReference(final Class[] classes) { + final int length = classes == null ? 0 : classes.length; + final Class[] types = new Class[length]; for (int index = 0; index < length; index++) { types[index] = getReference(classes[index]); } @@ -601,13 +601,13 @@ public static Class[] getReference(Class[] classes) { /** * Returns the primitive class array of the given object array - * + * * @param objects Given object array * @return The primitive class array */ - public static Class[] getPrimitive(Object[] objects) { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; + public static Class[] getPrimitive(final Object[] objects) { + final int length = objects == null ? 0 : objects.length; + final Class[] types = new Class[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(objects[index].getClass()); } @@ -616,13 +616,13 @@ public static Class[] getPrimitive(Object[] objects) { /** * Returns the reference class array of the given object array - * + * * @param objects Given object array * @return The reference class array */ - public static Class[] getReference(Object[] objects) { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; + public static Class[] getReference(final Object[] objects) { + final int length = objects == null ? 0 : objects.length; + final Class[] types = new Class[length]; for (int index = 0; index < length; index++) { types[index] = getReference(objects[index].getClass()); } @@ -631,18 +631,18 @@ public static Class[] getReference(Object[] objects) { /** * Compares two class arrays on equivalence - * + * * @param primary Primary class array * @param secondary Class array which is compared to the primary array * @return Whether these arrays are equal or not */ - public static boolean compare(Class[] primary, Class[] secondary) { + public static boolean compare(final Class[] primary, final Class[] secondary) { if (primary == null || secondary == null || primary.length != secondary.length) { return false; } for (int index = 0; index < primary.length; index++) { - Class primaryClass = primary[index]; - Class secondaryClass = secondary[index]; + final Class primaryClass = primary[index]; + final Class secondaryClass = secondary[index]; if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) { continue; } diff --git a/src/com/projectkorra/projectkorra/util/RevertChecker.java b/src/com/projectkorra/projectkorra/util/RevertChecker.java index 41ae17d60..d238272d9 100644 --- a/src/com/projectkorra/projectkorra/util/RevertChecker.java +++ b/src/com/projectkorra/projectkorra/util/RevertChecker.java @@ -1,8 +1,11 @@ package com.projectkorra.projectkorra.util; -import com.projectkorra.projectkorra.ProjectKorra; -import com.projectkorra.projectkorra.ability.EarthAbility; -import com.projectkorra.projectkorra.configuration.ConfigManager; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Future; import org.bukkit.Chunk; import org.bukkit.Server; @@ -10,39 +13,34 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Future; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.EarthAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; public class RevertChecker implements Runnable { - private ProjectKorra plugin; + private final ProjectKorra plugin; private static final FileConfiguration config = ConfigManager.defaultConfig.get(); private static final boolean safeRevert = config.getBoolean("Properties.Earth.SafeRevert"); public static Map earthRevertQueue = new ConcurrentHashMap<>(); static Map airRevertQueue = new ConcurrentHashMap<>(); - //static ConcurrentHashMap chunks = new ConcurrentHashMap(); - // static ConcurrentHashMap movedEarthQueue = new ConcurrentHashMap(); private long time; - public RevertChecker(ProjectKorra bending) { - plugin = bending; + public RevertChecker(final ProjectKorra bending) { + this.plugin = bending; } public static void revertAirBlocks() { - for (int ID : airRevertQueue.keySet()) { + for (final int ID : airRevertQueue.keySet()) { EarthAbility.revertAirBlock(ID); RevertChecker.airRevertQueue.remove(ID); } } public static void revertEarthBlocks() { - for (Block block : earthRevertQueue.keySet()) { + for (final Block block : earthRevertQueue.keySet()) { EarthAbility.revertBlock(block); earthRevertQueue.remove(block); } @@ -50,90 +48,90 @@ public static void revertEarthBlocks() { private Future> returnFuture; - // void addToMovedEarthQueue(Block block, Material type) { - // if (!movedEarthQueue.containsKey(block)) - // movedEarthQueue.put(block, type); - // - // } - - private void addToAirRevertQueue(int i) { - if (!airRevertQueue.containsKey(i)) + private void addToAirRevertQueue(final int i) { + if (!airRevertQueue.containsKey(i)) { airRevertQueue.put(i, i); + } } - private void addToRevertQueue(Block block) { - if (!earthRevertQueue.containsKey(block)) + private void addToRevertQueue(final Block block) { + if (!earthRevertQueue.containsKey(block)) { earthRevertQueue.put(block, block); + } } + @Override public void run() { - if (!plugin.isEnabled()) { + if (!this.plugin.isEnabled()) { return; } - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); if (config.getBoolean("Properties.Earth.RevertEarthbending")) { try { - returnFuture = plugin.getServer().getScheduler().callSyncMethod(plugin, new getOccupiedChunks(plugin.getServer())); - ArrayList chunks = returnFuture.get(); + this.returnFuture = this.plugin.getServer().getScheduler().callSyncMethod(this.plugin, new getOccupiedChunks(this.plugin.getServer())); + final ArrayList chunks = this.returnFuture.get(); - Map earth = new HashMap(); + final Map earth = new HashMap(); earth.putAll(EarthAbility.getMovedEarth()); - for (Block block : earth.keySet()) { - if (earthRevertQueue.containsKey(block)) + for (final Block block : earth.keySet()) { + if (earthRevertQueue.containsKey(block)) { continue; + } boolean remove = true; - Information info = earth.get(block); - if (time < info.getTime() + config.getLong("Properties.Earth.RevertCheckTime") || (chunks.contains(block.getChunk()) && safeRevert)) { + final Information info = earth.get(block); + if (this.time < info.getTime() + config.getLong("Properties.Earth.RevertCheckTime") || (chunks.contains(block.getChunk()) && safeRevert)) { remove = false; } if (remove) { - addToRevertQueue(block); + this.addToRevertQueue(block); } } - Map air = new HashMap(); + final Map air = new HashMap(); air.putAll(EarthAbility.getTempAirLocations()); - for (Integer i : air.keySet()) { - if (airRevertQueue.containsKey(i)) + for (final Integer i : air.keySet()) { + if (airRevertQueue.containsKey(i)) { continue; + } boolean remove = true; - Information info = air.get(i); - Block block = info.getBlock(); - if (time < info.getTime() + config.getLong("Properties.Earth.RevertCheckTime") || (chunks.contains(block.getChunk()) && safeRevert)) { + final Information info = air.get(i); + final Block block = info.getBlock(); + if (this.time < info.getTime() + config.getLong("Properties.Earth.RevertCheckTime") || (chunks.contains(block.getChunk()) && safeRevert)) { remove = false; } if (remove) { - addToAirRevertQueue(i); + this.addToAirRevertQueue(i); } } } - catch (Exception e) { + catch (final Exception e) { e.printStackTrace(); } } } private class getOccupiedChunks implements Callable> { - private Server server; + private final Server server; - public getOccupiedChunks(Server server) { + public getOccupiedChunks(final Server server) { this.server = server; } @Override public ArrayList call() throws Exception { - ArrayList chunks = new ArrayList(); + final ArrayList chunks = new ArrayList(); - for (Player player : server.getOnlinePlayers()) { - Chunk chunk = player.getLocation().getChunk(); - if (!chunks.contains(chunk)) + for (final Player player : this.server.getOnlinePlayers()) { + final Chunk chunk = player.getLocation().getChunk(); + if (!chunks.contains(chunk)) { chunks.add(chunk); + } } return chunks; diff --git a/src/com/projectkorra/projectkorra/util/Statistic.java b/src/com/projectkorra/projectkorra/util/Statistic.java new file mode 100644 index 000000000..038bbcef8 --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/Statistic.java @@ -0,0 +1,38 @@ +package com.projectkorra.projectkorra.util; + +import com.projectkorra.projectkorra.ability.CoreAbility; + +public enum Statistic { + + PLAYER_KILLS("PlayerKills", "player kills"), PLAYER_DAMAGE("PlayerDamage", "player damage"), TOTAL_KILLS("TotalKills", "total kills"), TOTAL_DAMAGE("TotalDamage", "total damage"); + + private String name; + private String displayName; + + private Statistic(final String name, final String displayName) { + this.name = name; + this.displayName = displayName; + } + + public String getName() { + return this.name; + } + + public String getDisplayName() { + return this.displayName; + } + + public String getStatisticName(final CoreAbility ability) { + return this.getName() + "_" + ability.getName(); + } + + public static Statistic getStatistic(final String name) { + for (final Statistic statistic : Statistic.values()) { + if (statistic.getName().equalsIgnoreCase(name)) { + return statistic; + } + } + return null; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/StatisticsManager.java b/src/com/projectkorra/projectkorra/util/StatisticsManager.java new file mode 100644 index 000000000..b01d5840b --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/StatisticsManager.java @@ -0,0 +1,223 @@ +package com.projectkorra.projectkorra.util; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.entity.Player; + +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.storage.DBConnection; +import com.projectkorra.projectkorra.storage.MySQL; +import com.projectkorra.projectkorra.storage.SQLite; + +public class StatisticsManager implements Runnable { + + /** + * HashMap which contains all current statistic values (Map>) + */ + private final Map> STATISTICS = new HashMap<>(); + /** + * HashMap which contains all statistic delta values (Map>) + */ + private final Map> DELTA = new HashMap<>(); + /** + * HashMap which contains all statistic names by ID. + */ + private final Map KEYS_BY_NAME = new HashMap<>(); + /** + * HashMap which contains all statistic IDs by name. + */ + private final Map KEYS_BY_ID = new HashMap<>(); + /** + * HashMap which contains all UUIDs of players who have recently logged out + * to have their stats saved. + */ + private final Set STORAGE = new HashSet<>(); + private final int INTERVAL = 5; + + public StatisticsManager() { + if (!ProjectKorra.isStatisticsEnabled()) { + ProjectKorra.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(ProjectKorra.plugin, this, 20 * this.INTERVAL, 20 * this.INTERVAL); + } + this.setupStatistics(); + } + + public void setupStatistics() { + // Create pk_statKeys table. + if (!DBConnection.sql.tableExists("pk_statKeys")) { + ProjectKorra.log.info("Creating pk_statKeys table"); + String query = ""; + if (DBConnection.sql instanceof MySQL) { + query = "CREATE TABLE `pk_statKeys` (`id` INTEGER PRIMARY KEY AUTO_INCREMENT, `statName` VARCHAR(64));"; + } else if (DBConnection.sql instanceof SQLite) { + query = "CREATE TABLE `pk_statKeys` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `statName` TEXT(64));"; + } + DBConnection.sql.modifyQuery(query, false); + } + // Create pk_stats table. + if (!DBConnection.sql.tableExists("pk_stats")) { + ProjectKorra.log.info("Creating pk_stats table"); + String query = ""; + if (DBConnection.sql instanceof MySQL) { + query = "CREATE TABLE `pk_stats` (`statId` INTEGER, `uuid` VARCHAR(36), `statValue` BIGINT, PRIMARY KEY (statId, uuid));"; + } else if (DBConnection.sql instanceof SQLite) { + query = "CREATE TABLE `pk_stats` (`statId` INTEGER, `uuid` TEXT(36), `statValue` BIGINT, PRIMARY KEY (statId, uuid));"; + } + DBConnection.sql.modifyQuery(query, false); + } + // Insert all abilities into pk_statKeys for all statistics. + for (final CoreAbility ability : CoreAbility.getAbilitiesByName()) { + if (ability.isHarmlessAbility()) { + continue; + } + for (final Statistic statistic : Statistic.values()) { + final String statName = statistic.getStatisticName(ability); + final ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_statKeys WHERE statName = '" + statName + "'"); + try { + if (!rs.next()) { + DBConnection.sql.modifyQuery("INSERT INTO pk_statKeys (statName) VALUES ('" + statName + "')", false); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + } + // Populate Keys Map with all loaded statName(s) in pk_statKeys. + final ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_statKeys"); + try { + while (rs.next()) { + this.KEYS_BY_NAME.put(rs.getString("statName"), rs.getInt("id")); + this.KEYS_BY_ID.put(rs.getInt("id"), rs.getString("statName")); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + + public void load(final UUID uuid) { + this.STATISTICS.put(uuid, new HashMap<>()); + this.DELTA.put(uuid, new HashMap<>()); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_stats WHERE uuid = '" + uuid.toString() + "'")) { + while (rs.next()) { + this.STATISTICS.get(uuid).put(rs.getInt("statId"), rs.getLong("statValue")); + this.DELTA.get(uuid).put(rs.getInt("statId"), 0L); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + + public void save(final UUID uuid, final boolean async) { + if (!this.DELTA.containsKey(uuid)) { + return; + } + final Map stats = this.DELTA.get(uuid); + for (final Entry entry : stats.entrySet()) { + final int statId = entry.getKey(); + final long statValue = entry.getValue(); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_stats WHERE uuid = '" + uuid.toString() + "' AND statId = " + statId)) { + if (!rs.next()) { + DBConnection.sql.modifyQuery("INSERT INTO pk_stats (statId, uuid, statValue) VALUES (" + statId + ", '" + uuid.toString() + "', " + statValue + ")", async); + } else { + DBConnection.sql.modifyQuery("UPDATE pk_stats SET statValue = statValue + " + statValue + " WHERE uuid = '" + uuid.toString() + "' AND statId = " + statId + ";", async); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + } + + public long getStatisticDelta(final UUID uuid, final int statId) { + // If the player is offline, pull value from database. + if (!this.DELTA.containsKey(uuid)) { + return 0; + } else if (!this.DELTA.get(uuid).containsKey(statId)) { + return 0; + } + return this.DELTA.get(uuid).get(statId); + } + + public long getStatisticCurrent(final UUID uuid, final int statId) { + // If the player is offline, pull value from database. + if (!this.STATISTICS.containsKey(uuid)) { + try (ResultSet rs = DBConnection.sql.readQuery("SELECT statValue FROM pk_stats WHERE uuid = '" + uuid.toString() + "' AND statId = " + statId + ";")) { + if (rs.next()) { + return rs.getLong("statValue"); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + return 0; + } else if (!this.STATISTICS.get(uuid).containsKey(statId)) { + return 0; + } + return this.STATISTICS.get(uuid).get(statId); + } + + public void addStatistic(final UUID uuid, final int statId, final long statDelta) { + if (!this.STATISTICS.containsKey(uuid) || !this.DELTA.containsKey(uuid)) { + return; + } + this.STATISTICS.get(uuid).put(statId, this.getStatisticCurrent(uuid, statId) + statDelta); + this.DELTA.get(uuid).put(statId, this.getStatisticDelta(uuid, statId) + statDelta); + + } + + public Map getStatisticsMap(final UUID uuid) { + final Map map = new HashMap<>(); + // If the player is offline, create a new temporary Map from the database. + if (!this.STATISTICS.containsKey(uuid)) { + try (ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_stats WHERE uuid = '" + uuid.toString() + "'")) { + while (rs.next()) { + final int statId = rs.getInt("statId"); + final long statValue = rs.getLong("statValue"); + map.put(statId, statValue); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + return map; + } + return this.STATISTICS.get(uuid); + } + + public void store(final UUID uuid) { + this.STORAGE.add(uuid); + } + + @Override + public void run() { + for (final UUID uuid : this.STORAGE) { + // Confirm that the player is offline. + final Player player = ProjectKorra.plugin.getServer().getPlayer(uuid); + if (player == null) { + this.save(uuid, true); + } + } + this.STORAGE.clear(); + } + + public Map getKeysByName() { + return this.KEYS_BY_NAME; + } + + public Map getKeysById() { + return this.KEYS_BY_ID; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/StatisticsMethods.java b/src/com/projectkorra/projectkorra/util/StatisticsMethods.java new file mode 100644 index 000000000..cebf7458f --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/StatisticsMethods.java @@ -0,0 +1,210 @@ +package com.projectkorra.projectkorra.util; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.UUID; + +import org.bukkit.entity.Player; + +import com.projectkorra.projectkorra.Element; +import com.projectkorra.projectkorra.ProjectKorra; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.storage.DBConnection; + +public class StatisticsMethods { + + /** + * Get the {@link Statistic} value of the given {@link CoreAbility} for the + * {@link Player} with {@link UUID} uuid. + * + * @param uuid The {@link UUID} of the {@link Player} being looked up. + * @param ability The {@link CoreAbility} for which the given statistic is + * being looked up against. + * @param statistic The {@link Statistic} being searched under. + * + * @return The found value of the given statistic. If the target player is + * not online this value will be pulled from the database. + * Otherwise, their current value will be pulled from + * {@link StatisticsManager#STATISTICS}. + */ + public static long getStatisticAbility(final UUID uuid, final CoreAbility ability, final Statistic statistic) { + if (!ProjectKorra.isStatisticsEnabled()) { + return 0; + } + final int statId = getId(statistic.getStatisticName(ability)); + return ProjectKorra.statistics.getStatisticCurrent(uuid, statId); + } + + /** + * Increment the {@link Player} with {@link UUID} uuid's {@link Statistic} + * for the given {@link CoreAbility} by a constant. + * + * @param uuid The {@link UUID} of the {@link Player} with the + * {@link Statistic} being modified. + * @param ability The {@link CoreAbility} for which the given statistic is + * being added to. + * @param statistic The {@link Statistic} being modified. + * @param statDelta The difference which is to be added onto the user's + * current statistic value. + */ + public static void addStatisticAbility(final UUID uuid, final CoreAbility ability, final Statistic statistic, final long statDelta) { + if (!ProjectKorra.isStatisticsEnabled()) { + return; + } + final int statId = getId(statistic.getStatisticName(ability)); + ProjectKorra.statistics.addStatistic(uuid, statId, statDelta); + } + + /** + * Get the {@link Statistic} value of the given {@link Element} for the + * {@link Player} with {@link UUID} uuid. + * + * @param uuid The {@link UUID} of the {@link Player} being looked up. + * @param element The {@link Element} for which the given statistic is being + * looked up against. + * @param statistic The {@link Statistic} being searched under. + * @return The found value of all statistics under this element. If the + * target player is not online this value will be pulled from the + * database. Otherwise, their current value will be pulled from + * {@link StatisticsManager#STATISTICS}. + */ + public static long getStatisticElement(final UUID uuid, final Element element, final Statistic statistic) { + if (!ProjectKorra.isStatisticsEnabled()) { + return 0; + } + long totalValue = 0; + for (final int statId : ProjectKorra.statistics.getStatisticsMap(uuid).keySet()) { + final String abilName = getAbilityName(statId); + final CoreAbility ability = CoreAbility.getAbility(abilName); + if (ability == null) { + continue; + } else if (!ability.getElement().equals(element)) { + continue; + } + // If the ID for this statistic and ability do not equal statId, then it must be a different statistic type. + else if (getId(statistic.getStatisticName(ability)) != statId) { + continue; + } + final long value = getStatisticAbility(uuid, ability, statistic); + totalValue += value; + } + return totalValue; + } + + /** + * Get the {@link Statistic} value of the given {@link Element} for the + * {@link Player} with {@link UUID} uuid. + * + * @param uuid The {@link UUID} of the {@link Player} being looked up. + * @param statistic The {@link Statistic} being searched under. + * @return The found value of all statistics under this category. If the + * target player is not online this value will be pulled from the + * database. Otherwise, their current value will be pulled from + * {@link StatisticsManager#STATISTICS}. + */ + public static long getStatisticTotal(final UUID uuid, final Statistic statistic) { + if (!ProjectKorra.isStatisticsEnabled()) { + return 0; + } + long totalValue = 0; + for (final int statId : ProjectKorra.statistics.getStatisticsMap(uuid).keySet()) { + final String abilName = getAbilityName(statId); + final CoreAbility ability = CoreAbility.getAbility(abilName); + if (ability == null) { + continue; + } + // If the ID for this statistic and ability do not equal statId, then it must be a different statistic type. + else if (getId(statistic.getStatisticName(ability)) != statId) { + continue; + } + final long value = getStatisticAbility(uuid, ability, statistic); + totalValue += value; + } + return totalValue; + } + + /** + * Get the {@link Statistic} value of the given {@link Object} for the + * {@link Player} with {@link UUID} uuid. This method will interpret as to + * whether the developer is trying to pull a statistic lookup on an ability + * or element. + * + * @param uuid The {@link UUID} of the {@link Player} being looked up. + * @param object This {@link Object} is used to input either a + * {@link CoreAbility} or {@link Element} when using statistics + * in a more general way. + * @param statistic The {@link Statistic} being searched under. + * + * @return The found value of the given statistic. If the target player is + * not online this value will be pulled from the database. + * Otherwise, their current value will be pulled from + * {@link StatisticsManager#STATISTICS}. + * + * @throws IllegalArgumentException if the given object argument is not of + * type {@link CoreAbility} or {@link Element}. + */ + public static long getStatistic(final UUID uuid, final Object object, final Statistic statistic) throws IllegalArgumentException { + if (!ProjectKorra.isStatisticsEnabled()) { + return 0; + } + if (object instanceof CoreAbility) { + return getStatisticAbility(uuid, (CoreAbility) object, statistic); + } else if (object instanceof Element) { + return getStatisticElement(uuid, (Element) object, statistic); + } else { + throw new IllegalArgumentException("Variable object is not a valid input type. Required: CoreAbility or Element."); + } + } + + /** + * Get the statistic ID generated by the pk_statKeys table for the statName + * {@link String}. + * + * @param statName The {@link String} identified used in the pk_statKeys + * table. + * @return The ID associated with the provided key. If invalid statName, + * return -1. + */ + public static int getId(final String statName) { + if (!ProjectKorra.isStatisticsEnabled()) { + return 0; + } + if (!ProjectKorra.statistics.getKeysByName().containsKey(statName)) { + DBConnection.sql.modifyQuery("INSERT INTO pk_statKeys (statName) VALUES ('" + statName + "')", false); + try (ResultSet rs = DBConnection.sql.readQuery("SELECT * FROM pk_statKeys WHERE statName = '" + statName + "'")) { + if (rs.next()) { + ProjectKorra.statistics.getKeysByName().put(rs.getString("statName"), rs.getInt("id")); + ProjectKorra.statistics.getKeysById().put(rs.getInt("id"), rs.getString("statName")); + } + } + catch (final SQLException e) { + e.printStackTrace(); + } + } + return ProjectKorra.statistics.getKeysByName().containsKey(statName) ? ProjectKorra.statistics.getKeysByName().get(statName) : -1; + } + + /** + * Get the unique {@link String} used by the pk_statKeys to register new + * {@link Statistic} options. + * + * @param id The statistic ID associated with this statistic name. + * @return The unique statistic name. If invalid id, return an empty + * {@link String}. + */ + public static String getAbilityName(final int id) { + if (!ProjectKorra.isStatisticsEnabled()) { + return ""; + } + if (!ProjectKorra.statistics.getKeysById().containsKey(id)) { + return ""; + } + final String statName = ProjectKorra.statistics.getKeysById().get(id); + final String[] split = statName.split("_"); + if (split.length < 2) { + return ""; + } + return split[1]; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/TempArmor.java b/src/com/projectkorra/projectkorra/util/TempArmor.java index 4b0f4b7d2..c192e0642 100644 --- a/src/com/projectkorra/projectkorra/util/TempArmor.java +++ b/src/com/projectkorra/projectkorra/util/TempArmor.java @@ -1,28 +1,29 @@ package com.projectkorra.projectkorra.util; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.PriorityQueue; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; -import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.CoreAbility; public class TempArmor { - private static Map INSTANCES = new ConcurrentHashMap(); + private static Map> INSTANCES = new ConcurrentHashMap<>(); + private static Map ORIGINAL = new HashMap<>(); private static long defaultDuration = 30000L; private LivingEntity entity; private long startTime; private long duration; - private BukkitTask endTimer; private ItemStack[] oldArmor; private ItemStack[] newArmor; private CoreAbility ability; @@ -32,12 +33,12 @@ public class TempArmor { * Creates a set of temporary armor on the player. This armor cannot be * tinkered with, dropped, and will restore the player's old armor when the * duration expires or when {@link #revert()} is called. - * + * * @param entity The player * @param armorItems The armor that should be set onto the player. Optional * - can be set later. */ - public TempArmor(LivingEntity entity, ItemStack[] armorItems) { + public TempArmor(final LivingEntity entity, final ItemStack[] armorItems) { this(entity, defaultDuration, null, armorItems); } @@ -45,13 +46,13 @@ public TempArmor(LivingEntity entity, ItemStack[] armorItems) { * Creates a set of temporary armor on the player. This armor cannot be * tinkered with, dropped, and will restore the player's old armor when the * duration expires or when {@link #revert()} is called. - * + * * @param entity The player * @param ability The ability that is creating the armor * @param armorItems The armor that should be set onto the player. Optional * - can be set later. */ - public TempArmor(LivingEntity entity, CoreAbility ability, ItemStack[] armorItems) { + public TempArmor(final LivingEntity entity, final CoreAbility ability, final ItemStack[] armorItems) { this(entity, defaultDuration, ability, armorItems); } @@ -59,22 +60,22 @@ public TempArmor(LivingEntity entity, CoreAbility ability, ItemStack[] armorItem * Creates a set of temporary armor on the player. This armor cannot be * tinkered with, dropped, and will restore the player's old armor when the * duration expires or when {@link #revert()} is called. - * + * * @param entity The player * @param duration How long the armor is to last. In milliseconds. * @param ability The ability that is creating the armor * @param armorItems The armor that should be set onto the player. Optional * - can be set later. */ - public TempArmor(LivingEntity entity, long duration, CoreAbility ability, ItemStack[] armorItems) { - if (duration <= 0) + public TempArmor(final LivingEntity entity, long duration, final CoreAbility ability, final ItemStack[] armorItems) { + if (duration <= 0) { duration = defaultDuration; + } this.entity = entity; this.startTime = System.currentTimeMillis(); this.duration = duration; this.ability = ability; - this.oldArmor = new ItemStack[] { new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR) }; for (int i = 0; i < 4; i++) { @@ -83,46 +84,40 @@ public TempArmor(LivingEntity entity, long duration, CoreAbility ability, ItemSt } } - this.newArmor = armorItems.clone(); + if (!INSTANCES.containsKey(entity)) { + ORIGINAL.put(entity, this.oldArmor); + final PriorityQueue queue = new PriorityQueue<>(10, new Comparator() { - ItemStack[] actualArmor = new ItemStack[4]; - for (int i = 0; i < 4; i++) { - if (armorItems[i] == null) { - actualArmor[i] = this.oldArmor[i]; - } else { - actualArmor[i] = armorItems[i]; - } - } - - this.entity.getEquipment().setArmorContents(actualArmor); + @Override + public int compare(final TempArmor a, final TempArmor b) { + final long current = System.currentTimeMillis(); + final long remainingA = a.getStartTime() + a.getDuration() - current; + final long remainingB = b.getStartTime() + b.getDuration() - current; + return (int) (remainingA - remainingB); + } - //This auto reverts the armor after a certain amount of time. We're doing it - //this way instead of checking if it should be reverted every tick in a runnable - this.endTimer = new BukkitRunnable() { + }); - @Override - public void run() { - endTimer = null; - revert(); - } - }.runTaskLater(ProjectKorra.plugin, duration / 50); + INSTANCES.put(entity, queue); + } + this.setArmor(armorItems); - INSTANCES.put(entity, this); + INSTANCES.get(entity).add(this); } /** * Filters out any TempArmor from the drop list and replaces it with the * original armor. Used when the player/mob dies. - * + * * @param drops The original item drop list * @return The drop list with the old armor added in place of the temp armor */ - public List filterArmor(List drops) { - List newDrops = new ArrayList(); + public List filterArmor(final List drops) { + final List newDrops = new ArrayList(); - for (ItemStack drop : drops) { + for (final ItemStack drop : drops) { boolean match = false; - for (ItemStack armorPiece : newArmor) { + for (final ItemStack armorPiece : this.newArmor) { if (armorPiece.isSimilar(drop)) { match = true; break; @@ -133,7 +128,7 @@ public List filterArmor(List drops) { } } - for (ItemStack armorPiece : oldArmor) { + for (final ItemStack armorPiece : this.oldArmor) { if (armorPiece != null && armorPiece.getType() != Material.AIR) { newDrops.add(armorPiece); } @@ -142,33 +137,33 @@ public List filterArmor(List drops) { } public CoreAbility getAbility() { - return ability; + return this.ability; } public LivingEntity getEntity() { - return entity; + return this.entity; } public long getDuration() { - return duration; + return this.duration; } public ItemStack[] getNewArmor() { - return newArmor; + return this.newArmor; } public ItemStack[] getOldArmor() { - return oldArmor; + return this.oldArmor; } public long getStartTime() { - return startTime; + return this.startTime; } - public void setArmor(ItemStack[] armor) { + public void setArmor(final ItemStack[] armor) { this.newArmor = armor; - ItemStack[] actualArmor = new ItemStack[4]; + final ItemStack[] actualArmor = new ItemStack[4]; for (int i = 0; i < 4; i++) { if (armor[i] == null) { actualArmor[i] = this.oldArmor[i]; @@ -180,30 +175,76 @@ public void setArmor(ItemStack[] armor) { this.entity.getEquipment().setArmorContents(actualArmor); } + private void updateArmor(final TempArmor next) { + final ItemStack[] armor = next.newArmor; + final ItemStack[] actualArmor = new ItemStack[4]; + for (int i = 0; i < 4; i++) { + if (armor[i] == null) { + actualArmor[i] = next.oldArmor[i]; + } else { + actualArmor[i] = armor[i]; + } + } + + this.entity.getEquipment().setArmorContents(actualArmor); + } + /** * Sets whether the ability that created the TempArmor should be forcefully * removed if the armor is forced to be reverted. Such cases are things like * on player death, etc. - * + * * @param bool */ - public void setRemovesAbilityOnForceRevert(boolean bool) { + public void setRemovesAbilityOnForceRevert(final boolean bool) { this.removeAbilOnForceRevert = bool; } - /** Destroys the TempArmor instance and restores the player's old armor. */ + /** + * Destroys the TempArmor instance and removes it from the display queue. + *
+ *
+ * Will also restore the player's armor to the state it was before any + * TempArmor instance was started, if the display queue is empty. + */ public void revert() { - if (this.endTimer != null) { - this.endTimer.cancel(); + if (this.removeAbilOnForceRevert && this.ability != null && !this.ability.isRemoved()) { + this.ability.remove(); } - this.entity.getEquipment().setArmorContents(this.oldArmor); + final PriorityQueue queue = INSTANCES.get(this.entity); - if (this.removeAbilOnForceRevert && this.ability != null && !this.ability.isRemoved()) { - this.ability.remove(); + if (queue.contains(this)) { + final TempArmor head = queue.peek(); + if (head.equals(this)) { + queue.poll(); + if (!queue.isEmpty()) { + this.updateArmor(queue.peek()); + } + } else { + queue.remove(this); + } } - INSTANCES.remove(this.entity); + if (queue.isEmpty()) { + this.entity.getEquipment().setArmorContents(ORIGINAL.get(this.entity)); + INSTANCES.remove(this.entity); + ORIGINAL.remove(this.entity); + } + } + + public static void cleanup() { + for (final LivingEntity entity : INSTANCES.keySet()) { + final PriorityQueue queue = INSTANCES.get(entity); + while (!queue.isEmpty()) { + final TempArmor tarmor = queue.peek(); + if (System.currentTimeMillis() >= tarmor.getStartTime() + tarmor.getDuration()) { + tarmor.revert(); + } else { + break; + } + } + } } /** @@ -211,29 +252,42 @@ public void revert() { * shutdown! */ public static void revertAll() { - for (TempArmor armor : INSTANCES.values()) { - armor.revert(); + for (final LivingEntity entity : INSTANCES.keySet()) { + while (!INSTANCES.get(entity).isEmpty()) { + final TempArmor armor = INSTANCES.get(entity).poll(); + armor.revert(); + } } } /** * Whether the player is currently wearing temporary armor - * - * @param player The player - * @return If the player has temporary armor on + * + * @param entity The entity + * @return If the entity has temporary armor on */ - public static boolean hasTempArmor(LivingEntity player) { - return INSTANCES.containsKey(player); + public static boolean hasTempArmor(final LivingEntity entity) { + return INSTANCES.containsKey(entity) && !INSTANCES.get(entity).isEmpty(); } /** * Returns the temporary armor the player is currently wearing - * - * @param player The player - * @return The TempArmor the player is wearing, or null if they + * + * @param entity The entity + * @return The TempArmor the entity is wearing, or null if they * aren't wearing any. */ - public static TempArmor getTempArmor(LivingEntity player) { - return INSTANCES.get(player); + public static TempArmor getVisibleTempArmor(final LivingEntity entity) { + if (!TempArmor.hasTempArmor(entity)) { + return null; + } + return INSTANCES.get(entity).peek(); + } + + public static List getTempArmorList(final LivingEntity entity) { + if (!TempArmor.hasTempArmor(entity)) { + return Collections.emptyList(); + } + return new ArrayList<>(INSTANCES.get(entity)); } } diff --git a/src/com/projectkorra/projectkorra/util/TempArmorStand.java b/src/com/projectkorra/projectkorra/util/TempArmorStand.java new file mode 100644 index 000000000..8b433725f --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/TempArmorStand.java @@ -0,0 +1,42 @@ +package com.projectkorra.projectkorra.util; + +import java.util.HashSet; +import java.util.Set; + +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.metadata.FixedMetadataValue; + +import com.projectkorra.projectkorra.ProjectKorra; + +/** + * Object to represent an ArmorStand that is not used for normal functionality + * + * @author Simplicitee + * + */ +public class TempArmorStand { + + public static Set tempStands = new HashSet<>(); + + public ArmorStand stand; + + public TempArmorStand(final Location loc) { + this.stand = loc.getWorld().spawn(loc, ArmorStand.class); + this.stand.setMetadata("temparmorstand", new FixedMetadataValue(ProjectKorra.plugin, 0)); + } + + public ArmorStand getArmorStand() { + return this.stand; + } + + /** + * Removes all instances of TempArmorStands and the associated ArmorStands + */ + public static void removeAll() { + for (final TempArmorStand temp : tempStands) { + temp.getArmorStand().remove(); + } + tempStands.clear(); + } +} diff --git a/src/com/projectkorra/projectkorra/util/TempBlock.java b/src/com/projectkorra/projectkorra/util/TempBlock.java index a734bad49..2b838e616 100644 --- a/src/com/projectkorra/projectkorra/util/TempBlock.java +++ b/src/com/projectkorra/projectkorra/util/TempBlock.java @@ -20,80 +20,78 @@ public class TempBlock { public static Map instances = new ConcurrentHashMap(); public static final PriorityQueue REVERT_QUEUE = new PriorityQueue<>(100, new Comparator() { @Override - public int compare(TempBlock t1, TempBlock t2) { + public int compare(final TempBlock t1, final TempBlock t2) { return (int) (t1.revertTime - t2.revertTime); } }); - private Block block; - private Material newtype; + private final Block block; private byte newdata; private BlockState state; private long revertTime; private boolean inRevertQueue; private RevertTask revertTask = null; - @SuppressWarnings("deprecation") - public TempBlock(Block block, Material newtype, byte newdata) { + public TempBlock(final Block block, final Material newtype, final byte newdata) { this.block = block; this.newdata = newdata; - this.newtype = newtype; if (instances.containsKey(block)) { - TempBlock temp = instances.get(block); - if (newtype != temp.newtype) { + final TempBlock temp = instances.get(block); + if (newtype != temp.block.getType()) { temp.block.setType(newtype); - temp.newtype = newtype; } - if (newdata != temp.newdata) { + if (newdata != temp.block.getData()) { temp.block.setData(newdata); temp.newdata = newdata; } - state = temp.state; + this.state = temp.state; instances.put(block, temp); } else { - state = block.getState(); + this.state = block.getState(); instances.put(block, this); block.setType(newtype); block.setData(newdata); } - if (state.getType() == Material.FIRE) - state.setType(Material.AIR); + if (this.state.getType() == Material.FIRE) { + this.state.setType(Material.AIR); + } } - public static TempBlock get(Block block) { - if (isTempBlock(block)) + public static TempBlock get(final Block block) { + if (isTempBlock(block)) { return instances.get(block); + } return null; } - public static boolean isTempBlock(Block block) { + public static boolean isTempBlock(final Block block) { return block != null ? instances.containsKey(block) : false; } - public static boolean isTouchingTempBlock(Block block) { - BlockFace[] faces = { BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; - for (BlockFace face : faces) { - if (instances.containsKey(block.getRelative(face))) + public static boolean isTouchingTempBlock(final Block block) { + final BlockFace[] faces = { BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; + for (final BlockFace face : faces) { + if (instances.containsKey(block.getRelative(face))) { return true; + } } return false; } public static void removeAll() { - for (Block block : instances.keySet()) { + for (final Block block : instances.keySet()) { revertBlock(block, Material.AIR); } - for (TempBlock tempblock : REVERT_QUEUE) { + for (final TempBlock tempblock : REVERT_QUEUE) { tempblock.revertBlock(); } } - public static void removeBlock(Block block) { + public static void removeBlock(final Block block) { instances.remove(block); } - @SuppressWarnings("deprecation") - public static void revertBlock(Block block, Material defaulttype) { + public static void revertBlock(final Block block, final Material defaulttype) { if (instances.containsKey(block)) { instances.get(block).revertBlock(); } else { @@ -107,35 +105,34 @@ public static void revertBlock(Block block, Material defaulttype) { block.setType(defaulttype); } } - // block.setType(defaulttype); } public Block getBlock() { - return block; + return this.block; } public Location getLocation() { - return block.getLocation(); + return this.block.getLocation(); } public BlockState getState() { - return state; + return this.state; } - + public RevertTask getRevertTask() { - return revertTask; + return this.revertTask; } - - public void setRevertTask(RevertTask task) { + + public void setRevertTask(final RevertTask task) { this.revertTask = task; } public long getRevertTime() { - return revertTime; + return this.revertTime; } - public void setRevertTime(long revertTime) { - if (inRevertQueue) { + public void setRevertTime(final long revertTime) { + if (this.inRevertQueue) { REVERT_QUEUE.remove(this); } this.inRevertQueue = true; @@ -144,44 +141,40 @@ public void setRevertTime(long revertTime) { } public void revertBlock() { - state.update(true); - instances.remove(block); + this.state.update(true); + instances.remove(this.block); if (REVERT_QUEUE.contains(this)) { REVERT_QUEUE.remove(this); } - if (revertTask != null) { - revertTask.run(); + if (this.revertTask != null) { + this.revertTask.run(); } } - public void setState(BlockState newstate) { - state = newstate; + public void setState(final BlockState newstate) { + this.state = newstate; } - public void setType(Material material) { - setType(material, newdata); + public void setType(final Material material) { + this.setType(material, this.newdata); } - @SuppressWarnings("deprecation") - public void setType(Material material, byte data) { - newtype = material; - newdata = data; - block.setType(material); - block.setData(data); + public void setType(final Material material, final byte data) { + this.newdata = data; + this.block.setType(material); + this.block.setData(data); } public static void startReversion() { new BukkitRunnable() { @Override public void run() { - long currentTime = System.currentTimeMillis(); + final long currentTime = System.currentTimeMillis(); while (!REVERT_QUEUE.isEmpty()) { - TempBlock tempBlock = REVERT_QUEUE.peek(); + final TempBlock tempBlock = REVERT_QUEUE.peek(); if (currentTime >= tempBlock.revertTime) { REVERT_QUEUE.poll(); tempBlock.revertBlock(); - //long finish = System.currentTimeMillis(); - //Bukkit.broadcastMessage(String.valueOf(finish - currentTime)); } else { break; } @@ -189,8 +182,8 @@ public void run() { } }.runTaskTimer(ProjectKorra.plugin, 0, 1); } - + public interface RevertTask { public void run(); } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/util/TempPotionEffect.java b/src/com/projectkorra/projectkorra/util/TempPotionEffect.java index a7b080711..2fcff3ec0 100644 --- a/src/com/projectkorra/projectkorra/util/TempPotionEffect.java +++ b/src/com/projectkorra/projectkorra/util/TempPotionEffect.java @@ -1,103 +1,102 @@ package com.projectkorra.projectkorra.util; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; + public class TempPotionEffect { private static Map instances = new ConcurrentHashMap(); private static final long tick = 21; private int ID = Integer.MIN_VALUE; - private Map infos = new ConcurrentHashMap(); - private LivingEntity entity; + private final Map infos = new ConcurrentHashMap(); + private final LivingEntity entity; - public TempPotionEffect(LivingEntity entity, PotionEffect effect) { + public TempPotionEffect(final LivingEntity entity, final PotionEffect effect) { this(entity, effect, System.currentTimeMillis()); } - public TempPotionEffect(LivingEntity entity, PotionEffect effect, long starttime) { + public TempPotionEffect(final LivingEntity entity, final PotionEffect effect, final long starttime) { this.entity = entity; if (instances.containsKey(entity)) { - TempPotionEffect instance = instances.get(entity); + final TempPotionEffect instance = instances.get(entity); instance.infos.put(instance.ID++, new PotionInfo(starttime, effect)); - // instance.effects.put(starttime, effect); instances.put(entity, instance); } else { - // effects.put(starttime, effect); - infos.put(ID++, new PotionInfo(starttime, effect)); + this.infos.put(this.ID++, new PotionInfo(starttime, effect)); instances.put(entity, this); } } public static void progressAll() { - for (LivingEntity entity : instances.keySet()) { + for (final LivingEntity entity : instances.keySet()) { instances.get(entity).progress(); } } - private void addEffect(PotionEffect effect) { - for (PotionEffect peffect : entity.getActivePotionEffects()) { + private void addEffect(final PotionEffect effect) { + for (final PotionEffect peffect : this.entity.getActivePotionEffects()) { if (peffect.getType().equals(effect.getType())) { if (peffect.getAmplifier() > effect.getAmplifier()) { if (peffect.getDuration() > effect.getDuration()) { return; } else { - int dt = effect.getDuration() - peffect.getDuration(); - PotionEffect neweffect = new PotionEffect(effect.getType(), dt, effect.getAmplifier()); - new TempPotionEffect(entity, neweffect, System.currentTimeMillis() + peffect.getDuration() * tick); + final int dt = effect.getDuration() - peffect.getDuration(); + final PotionEffect neweffect = new PotionEffect(effect.getType(), dt, effect.getAmplifier()); + new TempPotionEffect(this.entity, neweffect, System.currentTimeMillis() + peffect.getDuration() * tick); return; } } else { if (peffect.getDuration() > effect.getDuration()) { - entity.removePotionEffect(peffect.getType()); - entity.addPotionEffect(effect); - int dt = peffect.getDuration() - effect.getDuration(); - PotionEffect neweffect = new PotionEffect(peffect.getType(), dt, peffect.getAmplifier()); - new TempPotionEffect(entity, neweffect, System.currentTimeMillis() + effect.getDuration() * tick); + this.entity.removePotionEffect(peffect.getType()); + this.entity.addPotionEffect(effect); + final int dt = peffect.getDuration() - effect.getDuration(); + final PotionEffect neweffect = new PotionEffect(peffect.getType(), dt, peffect.getAmplifier()); + new TempPotionEffect(this.entity, neweffect, System.currentTimeMillis() + effect.getDuration() * tick); return; } else { - entity.removePotionEffect(peffect.getType()); - entity.addPotionEffect(effect); + this.entity.removePotionEffect(peffect.getType()); + this.entity.addPotionEffect(effect); return; } } } } - entity.addPotionEffect(effect); + this.entity.addPotionEffect(effect); } private void progress() { - for (int id : infos.keySet()) { - PotionInfo info = infos.get(id); + for (final int id : this.infos.keySet()) { + final PotionInfo info = this.infos.get(id); if (info.getTime() < System.currentTimeMillis()) { - addEffect(info.getEffect()); - infos.remove(id); + this.addEffect(info.getEffect()); + this.infos.remove(id); } } - if (infos.isEmpty() && instances.containsKey(entity)) - instances.remove(entity); + if (this.infos.isEmpty() && instances.containsKey(this.entity)) { + instances.remove(this.entity); + } } private class PotionInfo { - private long starttime; - private PotionEffect effect; + private final long starttime; + private final PotionEffect effect; - public PotionInfo(long starttime, PotionEffect effect) { + public PotionInfo(final long starttime, final PotionEffect effect) { this.starttime = starttime; this.effect = effect; } public long getTime() { - return starttime; + return this.starttime; } public PotionEffect getEffect() { - return effect; + return this.effect; } } diff --git a/src/com/projectkorra/projectkorra/util/TimeUtil.java b/src/com/projectkorra/projectkorra/util/TimeUtil.java new file mode 100644 index 000000000..88a392b44 --- /dev/null +++ b/src/com/projectkorra/projectkorra/util/TimeUtil.java @@ -0,0 +1,39 @@ +package com.projectkorra.projectkorra.util; + +import java.util.concurrent.TimeUnit; + +public class TimeUtil { + + /** + * Get the given time in a formatted String. + * + * @param time Time to be formatting (milliseconds) + * @return Formatted time + */ + public static String formatTime(long time) { + String sign = ""; + if (time < 0) { + sign = "-"; + time = Math.abs(time); + } + final long days = time / TimeUnit.DAYS.toMillis(1); + final long hours = time % TimeUnit.DAYS.toMillis(1) / TimeUnit.HOURS.toMillis(1); + final long minutes = time % TimeUnit.HOURS.toMillis(1) / TimeUnit.MINUTES.toMillis(1); + final long seconds = time % TimeUnit.MINUTES.toMillis(1) / TimeUnit.SECONDS.toMillis(1); + String formatted = sign; + if (days > 0) { + formatted += String.valueOf(days) + "d "; + } + if (hours > 0) { + formatted += String.valueOf(hours) + "h "; + } + if (minutes > 0) { + formatted += String.valueOf(minutes) + "m "; + } + if (seconds >= 0) { + formatted += String.valueOf(seconds) + "s"; + } + return formatted; + } + +} diff --git a/src/com/projectkorra/projectkorra/util/Updater.java b/src/com/projectkorra/projectkorra/util/Updater.java index 2ebcc32df..73a6e4b02 100644 --- a/src/com/projectkorra/projectkorra/util/Updater.java +++ b/src/com/projectkorra/projectkorra/util/Updater.java @@ -1,21 +1,17 @@ package com.projectkorra.projectkorra.util; -import org.bukkit.plugin.Plugin; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import org.bukkit.plugin.Plugin; /** * Updater class that takes an rss feed and checks for updates there
- * Will only work on xenforo rss feeds + * Will only work on xenforo rss feeds Outdated: RSS feeds no longer + * available. Gets the version from the page itself and parse it. *

* Methods to look for in this class: *

    @@ -26,18 +22,18 @@ *
  • {@link #updateAvailable()} to check if theres an update
  • *
*

- * - * @author Jacklin213 * + * @author Jacklin213, updated by StrangeOne101 */ public class Updater { private URL url; private URLConnection urlc; - private Document document; - private String currentVersion; - private Plugin plugin; - private String pluginName; + private String updateVersion; + private final String currentVersion; + private final Plugin plugin; + private final boolean checkUpdate; + private final String pluginName; /** * Creates a new instance of Updater. This constructor should only be called @@ -46,106 +42,129 @@ public class Updater { *
* This constructor should NEVER be called to initiate a field. If called to * initiate a field, Updater will throw NullPointerExceptions - * + * * @param plugin Plugin to check updates for * @param URL RSS feed URL link to check for updates on. + * @param checkForUpdate Whether the plugin should check for updates when + * the server starts or not. Defined in the config */ - public Updater(Plugin plugin, String URL) { + public Updater(final Plugin plugin, final String URL, final boolean checkForUpdate) { this.plugin = plugin; - try { - url = new URL(URL); - urlc = url.openConnection(); - urlc.setRequestProperty("User-Agent", ""); // Must be used or face 403 - urlc.setConnectTimeout(30000); // 30 second time out, throws SocketTimeoutException - document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(urlc.getInputStream()); - } - catch (IOException e) { - plugin.getLogger().info("Could not connect to ProjectKorra.com to check for updates"); - } - catch (SAXException | ParserConfigurationException e) { - e.printStackTrace(); + this.checkUpdate = checkForUpdate; + if (this.checkUpdate) { + this.runAsync(plugin, () -> { + try { + plugin.getLogger().info("Checking for updates...!"); + this.url = new URL(URL); + this.urlc = this.url.openConnection(); + this.urlc.setRequestProperty("User-Agent", "Mozilla/5.0"); // Must be used or face 403. + this.urlc.setConnectTimeout(30000); // 30 second time out, throws SocketTimeoutException. + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(this.urlc.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + // The characters allowed in the version are any digit, full stops, spaces, or "for MC x.x.x+". + // Then we are just parsing it from the line that states the version. + if (line.toLowerCase().matches(".*[0-9\\. formcr+]{1,23}<\\/span>.*")) { + line = line.trim(); + this.updateVersion = line.split("")[1].split("<\\/span>")[0]; + break; + } + } + } + catch (final IOException e) { + e.printStackTrace(); + } + } + catch (final IOException e) { + plugin.getLogger().info("Could not connect to projectkorra.com"); + } + this.checkUpdate(); + }); } this.currentVersion = plugin.getDescription().getVersion(); this.pluginName = plugin.getDescription().getName(); } + private void runAsync(final Plugin plugin, final Runnable run) { + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, run); + } + /** * Logs and update message in console. Displays different messages dependent * on {@link #updateAvailable()} - * */ public void checkUpdate() { - if (getUpdateVersion() == null) { + if (!this.isEnabled()) { + return; + } + if (this.getUpdateVersion() == null) { + this.plugin.getLogger().info("Something went wrong while trying to retrieve the latest version."); return; - } else if (updateAvailable()) { - plugin.getLogger().info("===================[Update Available]==================="); - plugin.getLogger().info("You are running version " + getCurrentVersion()); - plugin.getLogger().info("The latest version avaliable is " + getUpdateVersion()); + } + if (this.updateAvailable()) { + this.plugin.getLogger().info("===================[Update Available]==================="); + this.plugin.getLogger().info("You are running version " + this.getCurrentVersion()); + this.plugin.getLogger().info("The latest version available is " + this.getUpdateVersion()); } else { - plugin.getLogger().info("You are running the latest version of " + pluginName); + this.plugin.getLogger().info("You are running the latest version of " + this.pluginName); } } /** * Gets latest plugin version. - * + * * @return Latest plugin version, or null if it cannot connect */ public String getUpdateVersion() { - if (document != null) { - Node latestFile = document.getElementsByTagName("item").item(0); - NodeList children = latestFile.getChildNodes(); - - String version = children.item(1).getTextContent(); - return version.toUpperCase(); - } - return null; + return this.updateVersion; } /** - * Checks to see if an update is available. - * + * Checks to see if an update is available. Note: This method does + * not check the newest version in real time. It checks using the + * latest version number retrieved upon startup. + * * @return true If there is an update */ public boolean updateAvailable() { - String updateVersion = getUpdateVersion(); + final String updateVersion = this.getUpdateVersion(); if (updateVersion == null) { return false; } - int currentNumber = Integer.parseInt(currentVersion.substring(0, 5).replaceAll("\\.", "")); - int updateNumber = Integer.parseInt(updateVersion.substring(0, 5).replaceAll("\\.", "")); - if (updateNumber == currentNumber) { - if (currentVersion.contains("BETA") && updateVersion.contains("BETA")) { - int currentBeta = Integer.parseInt(currentVersion.substring(currentVersion.lastIndexOf(" ") + 1)); - int updateBeta = Integer.parseInt(updateVersion.substring(updateVersion.lastIndexOf(" ") + 1)); - if (currentBeta == updateBeta || currentBeta > updateBeta) { - return false; - } - } else if (!currentVersion.contains("BETA") && updateVersion.contains("BETA")) { - return false; - } - } else if (currentVersion.equalsIgnoreCase(updateVersion) || currentNumber > updateNumber) { - return false; - } - return true; + final String numericUpdateVersion = updateVersion.split(" ")[0]; // Only take the left half if there is words in it too. + final String numericCurrentVersion = this.currentVersion.split(" ")[0]; + final int currentNumber = Integer.parseInt(numericCurrentVersion.replaceAll("[^\\d]", "")); // Replace points So version is just 186 instead of 1.8.6, etc. + final int updateNumber = Integer.parseInt(numericUpdateVersion.replaceAll("[^\\d]", "")); + + return currentNumber < updateNumber || this.currentVersion.hashCode() != updateVersion.hashCode(); // If the numeric versions are the same, check if the version string is different. } /** * Gets the connected URL object. - * + * * @return The URL object */ public URL getUrl() { - return url; + return this.url; } /** * Gets the current plugin version from the plugin.yml. - * + * * @return The current plugin version */ public String getCurrentVersion() { - return currentVersion; + return this.currentVersion; + } + + /** + * Returns whether the update checker has been enabled or not. + * + * @return True if enabled, otherwise false + */ + public boolean isEnabled() { + return this.checkUpdate; } } diff --git a/src/com/projectkorra/projectkorra/util/logging/LogFilter.java b/src/com/projectkorra/projectkorra/util/logging/LogFilter.java index 62116d41f..2192e04ef 100644 --- a/src/com/projectkorra/projectkorra/util/logging/LogFilter.java +++ b/src/com/projectkorra/projectkorra/util/logging/LogFilter.java @@ -1,9 +1,5 @@ package com.projectkorra.projectkorra.util.logging; -import com.projectkorra.projectkorra.ProjectKorra; - -import org.bukkit.Bukkit; - import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; @@ -11,18 +7,22 @@ import java.util.logging.Filter; import java.util.logging.LogRecord; +import org.bukkit.Bukkit; + +import com.projectkorra.projectkorra.ProjectKorra; + /** * This class should only be used to set {@link PKLogHandler}'s filter. - * + * * @author Jacklin213 * @version 2.1.0 */ public class LogFilter implements Filter { - private List loggedRecords = new ArrayList<>(); + private final List loggedRecords = new ArrayList<>(); @Override - public boolean isLoggable(LogRecord record) { + public boolean isLoggable(final LogRecord record) { if (record.getMessage() == null && record.getThrown() == null) { return false; } @@ -38,9 +38,9 @@ public boolean isLoggable(LogRecord record) { if (!record.getThrown().getMessage().contains("ProjectKorra")) { return false; } - // record message doesnt have ProjectKorra but throwable does + // record message doesnt have ProjectKorra but throwable does. } - recordString = buildString(record); + recordString = this.buildString(record); } else { if (record.getThrown() != null) { if (record.getThrown().getMessage() == null) { @@ -49,13 +49,13 @@ public boolean isLoggable(LogRecord record) { if (!record.getThrown().getMessage().contains("ProjectKorra")) { return false; } - // record message null but throwable has ProjectKorra - recordString = buildString(record); + // record message null but throwable has ProjectKorra. + recordString = this.buildString(record); } } - if (loggedRecords.contains(recordString)) { - // Logged records contains record + if (this.loggedRecords.contains(recordString)) { + // Logged records contains record return false; } @@ -65,20 +65,21 @@ public boolean isLoggable(LogRecord record) { final String toRecord = recordString; Bukkit.getScheduler().runTaskLater(ProjectKorra.plugin, new Runnable() { + @Override public void run() { - loggedRecords.add(toRecord); + LogFilter.this.loggedRecords.add(toRecord); } }, 10); return true; } - private String buildString(LogRecord record) { - StringBuilder builder = new StringBuilder(); + private String buildString(final LogRecord record) { + final StringBuilder builder = new StringBuilder(); if (record.getMessage() != null) { builder.append(record.getMessage()); } if (record.getThrown() != null) { - StringWriter writer = new StringWriter(); + final StringWriter writer = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(writer)); builder.append(writer); } diff --git a/src/com/projectkorra/projectkorra/util/logging/LogFormatter.java b/src/com/projectkorra/projectkorra/util/logging/LogFormatter.java index 7863c85f7..e89a4f4b2 100644 --- a/src/com/projectkorra/projectkorra/util/logging/LogFormatter.java +++ b/src/com/projectkorra/projectkorra/util/logging/LogFormatter.java @@ -8,7 +8,7 @@ /** * Logger formatter class based on bukkit's formatter. - * + * * @author Jacklin213 * @version 2.1.0 */ @@ -17,21 +17,21 @@ public class LogFormatter extends Formatter { private final SimpleDateFormat date = new SimpleDateFormat("MMM-dd|HH:mm:ss"); @Override - public String format(LogRecord record) { - StringBuilder builder = new StringBuilder(); - Throwable ex = record.getThrown(); + public String format(final LogRecord record) { + final StringBuilder builder = new StringBuilder(); + final Throwable ex = record.getThrown(); builder.append("("); - builder.append(date.format(record.getMillis())); + builder.append(this.date.format(record.getMillis())); builder.append(")"); builder.append(" ["); builder.append(record.getLevel().getLocalizedName().toUpperCase()); builder.append("] "); - builder.append(formatMessage(record)); + builder.append(this.formatMessage(record)); builder.append('\n'); if (ex != null) { - StringWriter writer = new StringWriter(); + final StringWriter writer = new StringWriter(); ex.printStackTrace(new PrintWriter(writer)); builder.append(writer); } diff --git a/src/com/projectkorra/projectkorra/util/logging/PKLogHandler.java b/src/com/projectkorra/projectkorra/util/logging/PKLogHandler.java index 85aac346d..1a840124c 100644 --- a/src/com/projectkorra/projectkorra/util/logging/PKLogHandler.java +++ b/src/com/projectkorra/projectkorra/util/logging/PKLogHandler.java @@ -17,13 +17,13 @@ * errors} *
  • Formatter - {@link LogFormatter}
  • * - * + * * @author Jacklin213 * @version 2.1.0 */ public class PKLogHandler extends FileHandler { - public PKLogHandler(String filename) throws IOException { + public PKLogHandler(final String filename) throws IOException { super(filename, 500 * 1024, 20, true); this.setLevel(Level.WARNING); this.setFilter(new LogFilter()); @@ -31,9 +31,9 @@ public PKLogHandler(String filename) throws IOException { } @Override - public synchronized void publish(LogRecord record) { + public synchronized void publish(final LogRecord record) { super.publish(record); - flush(); + this.flush(); } } diff --git a/src/com/projectkorra/projectkorra/waterbending/OctopusForm.java b/src/com/projectkorra/projectkorra/waterbending/OctopusForm.java index f330cd8b6..d3a5f271e 100644 --- a/src/com/projectkorra/projectkorra/waterbending/OctopusForm.java +++ b/src/com/projectkorra/projectkorra/waterbending/OctopusForm.java @@ -42,9 +42,12 @@ public class OctopusForm extends WaterAbility { private int stepCounter; private int totalStepCount; private long time; + private long startTime; private long interval; private long cooldown; + private long duration; private double attackRange; + private long usageCooldown; private double knockback; private double radius; private double startAngle; @@ -58,10 +61,10 @@ public class OctopusForm extends WaterAbility { private ArrayList newBlocks; private PhaseChange pc; - public OctopusForm(Player player) { + public OctopusForm(final Player player) { super(player); - OctopusForm oldOctopus = getAbility(player, OctopusForm.class); + final OctopusForm oldOctopus = getAbility(player, OctopusForm.class); if (oldOctopus != null) { if (oldOctopus.formed) { oldOctopus.attack(); @@ -71,7 +74,7 @@ public OctopusForm(Player player) { } } - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { if (oldOctopus != null) { oldOctopus.remove(); } @@ -89,9 +92,11 @@ public OctopusForm(Player player) { this.damage = getConfig().getInt("Abilities.Water.OctopusForm.Damage"); this.interval = getConfig().getLong("Abilities.Water.OctopusForm.FormDelay"); this.attackRange = getConfig().getInt("Abilities.Water.OctopusForm.AttackRange"); + this.usageCooldown = getConfig().getInt("Abilities.Water.OctopusForm.UsageCooldown"); this.knockback = getConfig().getDouble("Abilities.Water.OctopusForm.Knockback"); this.radius = getConfig().getDouble("Abilities.Water.OctopusForm.Radius"); this.cooldown = getConfig().getLong("Abilities.Water.OctopusForm.Cooldown"); + this.duration = getConfig().getLong("Abilities.Water.OctopusForm.Duration"); this.angleIncrement = getConfig().getDouble("Abilities.Water.OctopusForm.AngleIncrement"); this.currentFormHeight = 0; this.blocks = new ArrayList(); @@ -101,54 +106,53 @@ public OctopusForm(Player player) { } else { this.pc = new PhaseChange(player, PhaseChangeType.CUSTOM); } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.damage = getConfig().getInt("Abilities.Avatar.AvatarState.Water.OctopusForm.Damage"); this.attackRange = getConfig().getInt("Abilities.Avatar.AvatarState.Water.OctopusForm.AttackRange"); this.knockback = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.OctopusForm.Knockback"); this.radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.OctopusForm.Radius"); } this.time = System.currentTimeMillis(); + this.startTime = System.currentTimeMillis(); if (!player.isSneaking()) { - this.sourceBlock = BlockSource.getWaterSourceBlock(player, range, ClickType.LEFT_CLICK, true, true, bPlayer.canPlantbend()); + this.sourceBlock = BlockSource.getWaterSourceBlock(player, this.range, ClickType.LEFT_CLICK, true, true, this.bPlayer.canPlantbend()); } - if (sourceBlock != null) { - sourceLocation = sourceBlock.getLocation(); - sourceSelected = true; - start(); + if (this.sourceBlock != null) { + this.sourceLocation = this.sourceBlock.getLocation(); + this.sourceSelected = true; + this.start(); } } private void incrementStep() { - if (sourceSelected) { - sourceSelected = false; - settingUp = true; - bPlayer.addCooldown(this); - } else if (settingUp) { - settingUp = false; - forming = true; - } else if (forming) { - forming = false; - formed = true; - bPlayer.addCooldown(this); + if (this.sourceSelected) { + this.sourceSelected = false; + this.settingUp = true; + } else if (this.settingUp) { + this.settingUp = false; + this.forming = true; + } else if (this.forming) { + this.forming = false; + this.formed = true; } } - @SuppressWarnings("deprecation") - public static void form(Player player) { - OctopusForm oldForm = getAbility(player, OctopusForm.class); + public static void form(final Player player) { + final OctopusForm oldForm = getAbility(player, OctopusForm.class); if (oldForm != null) { oldForm.form(); } else if (WaterReturn.hasWaterBottle(player)) { - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { block.setType(Material.WATER); block.setData(FULL); - OctopusForm form = new OctopusForm(player); + final OctopusForm form = new OctopusForm(player); + form.setSourceBlock(block); form.form(); if (form.formed || form.forming || form.settingUp) { @@ -161,31 +165,32 @@ public static void form(Player player) { } private void form() { - incrementStep(); - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); - } else if (!GeneralMethods.isAdjacentToThreeOrMoreSources(sourceBlock) && sourceBlock != null) { - sourceBlock.setType(Material.AIR); + this.incrementStep(); + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); + } else if (!GeneralMethods.isAdjacentToThreeOrMoreSources(this.sourceBlock) && this.sourceBlock != null) { + this.sourceBlock.setType(Material.AIR); } - source = new TempBlock(sourceBlock, Material.STATIONARY_WATER, (byte) 8); + this.source = new TempBlock(this.sourceBlock, Material.STATIONARY_WATER, (byte) 8); } private void attack() { - if (!formed) { + if (!this.formed || this.bPlayer.isOnCooldown("OctopusAttack")) { return; } - double tentacleAngle = (new Vector(1, 0, 0)).angle(player.getEyeLocation().getDirection()) + angleIncrement / 2; + this.bPlayer.addCooldown("OctopusAttack", this.usageCooldown); + final double tentacleAngle = (new Vector(1, 0, 0)).angle(this.player.getEyeLocation().getDirection()) + this.angleIncrement / 2; - for (double tangle = tentacleAngle; tangle < tentacleAngle + 360; tangle += angleIncrement) { - double phi = Math.toRadians(tangle); - affect(player.getLocation().clone().add(new Vector(radius * Math.cos(phi), 1, radius * Math.sin(phi)))); + for (double tangle = tentacleAngle; tangle < tentacleAngle + 360; tangle += this.angleIncrement) { + final double phi = Math.toRadians(tangle); + this.affect(this.player.getLocation().clone().add(new Vector(this.radius * Math.cos(phi), 1, this.radius * Math.sin(phi)))); } } - private void affect(Location location) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, attackRange)) { - if (entity.getEntityId() == player.getEntityId()) { + private void affect(final Location location) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(location, this.attackRange)) { + if (entity.getEntityId() == this.player.getEntityId()) { continue; } else if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; @@ -193,16 +198,16 @@ private void affect(Location location) { continue; } - double knock = bPlayer.isAvatarState() ? AvatarState.getValue(knockback) : knockback; - entity.setVelocity(GeneralMethods.getDirection(player.getLocation(), location).normalize().multiply(knock)); + final double knock = this.bPlayer.isAvatarState() ? AvatarState.getValue(this.knockback) : this.knockback; + entity.setVelocity(GeneralMethods.getDirection(this.player.getLocation(), location).normalize().multiply(knock)); if (entity instanceof LivingEntity) { - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } AirAbility.breakBreathbendingHold(entity); } } - + @Override public boolean allowBreakPlants() { return false; @@ -210,162 +215,166 @@ public boolean allowBreakPlants() { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; - } else if (!player.isSneaking() && !sourceSelected) { - remove(); + } else if (!this.player.isSneaking() && !this.sourceSelected) { + this.remove(); return; - } else if (sourceBlock.getLocation().distanceSquared(player.getLocation()) > range * range && sourceSelected) { - remove(); + } else if (this.sourceBlock.getLocation().distanceSquared(this.player.getLocation()) > this.range * this.range && this.sourceSelected) { + this.remove(); + return; + } else if (this.duration != 0 && System.currentTimeMillis() > this.startTime + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - Random random = new Random(); + final Random random = new Random(); - if (System.currentTimeMillis() > time + interval) { - time = System.currentTimeMillis(); - Location location = player.getLocation(); + if (System.currentTimeMillis() > this.time + this.interval) { + this.time = System.currentTimeMillis(); + final Location location = this.player.getLocation(); - if (sourceSelected) { - playFocusWaterEffect(sourceBlock); - } else if (settingUp) { - if (sourceBlock.getY() < location.getBlockY()) { - source.revertBlock(); - source = null; - Block newBlock = sourceBlock.getRelative(BlockFace.UP); - sourceLocation = newBlock.getLocation(); + if (this.sourceSelected) { + playFocusWaterEffect(this.sourceBlock); + } else if (this.settingUp) { + if (this.sourceBlock.getY() < location.getBlockY()) { + this.source.revertBlock(); + this.source = null; + final Block newBlock = this.sourceBlock.getRelative(BlockFace.UP); + this.sourceLocation = newBlock.getLocation(); if (!GeneralMethods.isSolid(newBlock)) { - source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); - sourceBlock = newBlock; + this.source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); + this.sourceBlock = newBlock; } else { - remove(); + this.remove(); return; } - } else if (sourceBlock.getY() > location.getBlockY()) { - source.revertBlock(); - source = null; - Block newBlock = sourceBlock.getRelative(BlockFace.DOWN); - sourceLocation = newBlock.getLocation(); + } else if (this.sourceBlock.getY() > location.getBlockY()) { + this.source.revertBlock(); + this.source = null; + final Block newBlock = this.sourceBlock.getRelative(BlockFace.DOWN); + this.sourceLocation = newBlock.getLocation(); if (!GeneralMethods.isSolid(newBlock)) { - source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); - sourceBlock = newBlock; + this.source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); + this.sourceBlock = newBlock; } else { - remove(); + this.remove(); return; } - } else if (sourceLocation.distanceSquared(location) > radius * radius) { - Vector vector = GeneralMethods.getDirection(sourceLocation, location.getBlock().getLocation()).normalize(); - sourceLocation.add(vector); - Block newBlock = sourceLocation.getBlock(); - - if (!newBlock.equals(sourceBlock)) { - if (source != null) { - source.revertBlock(); + } else if (this.sourceLocation.distanceSquared(location) > this.radius * this.radius) { + final Vector vector = GeneralMethods.getDirection(this.sourceLocation, location.getBlock().getLocation()).normalize(); + this.sourceLocation.add(vector); + final Block newBlock = this.sourceLocation.getBlock(); + + if (!newBlock.equals(this.sourceBlock)) { + if (this.source != null) { + this.source.revertBlock(); } if (!GeneralMethods.isSolid(newBlock)) { - source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); - sourceBlock = newBlock; + this.source = new TempBlock(newBlock, Material.STATIONARY_WATER, (byte) 8); + this.sourceBlock = newBlock; } } } else { - incrementStep(); - if (source != null) { - source.revertBlock(); + this.incrementStep(); + if (this.source != null) { + this.source.revertBlock(); } - source = null; - Vector vector = new Vector(1, 0, 0); - startAngle = vector.angle(GeneralMethods.getDirection(sourceBlock.getLocation(), location)); - angle = startAngle; + this.source = null; + final Vector vector = new Vector(1, 0, 0); + this.startAngle = vector.angle(GeneralMethods.getDirection(this.sourceBlock.getLocation(), location)); + this.angle = this.startAngle; } - } else if (forming) { - if (angle - startAngle >= 360) { - currentFormHeight += 1; + } else if (this.forming) { + if (this.angle - this.startAngle >= 360) { + this.currentFormHeight += 1; } else { - angle += 20; + this.angle += 20; } if (random.nextInt(4) == 0) { - playWaterbendingSound(player.getLocation()); + playWaterbendingSound(this.player.getLocation()); } - formOctopus(); - if (currentFormHeight == 2) { - incrementStep(); + this.formOctopus(); + if (this.currentFormHeight == 2) { + this.incrementStep(); } - } else if (formed) { + } else if (this.formed) { if (random.nextInt(7) == 0) { - playWaterbendingSound(player.getLocation()); + playWaterbendingSound(this.player.getLocation()); } - stepCounter += 1; - if (stepCounter % totalStepCount == 0) { - currentAnimationStep += 1; + this.stepCounter += 1; + if (this.stepCounter % this.totalStepCount == 0) { + this.currentAnimationStep += 1; } - if (currentAnimationStep > 8) { - currentAnimationStep = 1; + if (this.currentAnimationStep > 8) { + this.currentAnimationStep = 1; } - formOctopus(); + this.formOctopus(); } else { - remove(); + this.remove(); return; } } } private void formOctopus() { - Location location = player.getLocation(); - newBlocks.clear(); - ArrayList doneBlocks = new ArrayList(); + final Location location = this.player.getLocation(); + this.newBlocks.clear(); + final ArrayList doneBlocks = new ArrayList(); - for (double theta = startAngle; theta < startAngle + angle; theta += 10) { - double rtheta = Math.toRadians(theta); - Block block = location.clone().add(new Vector(radius * Math.cos(rtheta), 0, radius * Math.sin(rtheta))).getBlock(); + for (double theta = this.startAngle; theta < this.startAngle + this.angle; theta += 10) { + final double rtheta = Math.toRadians(theta); + final Block block = location.clone().add(new Vector(this.radius * Math.cos(rtheta), 0, this.radius * Math.sin(rtheta))).getBlock(); if (!doneBlocks.contains(block)) { - addBaseWater(block); + this.addBaseWater(block); doneBlocks.add(block); } } for (int i = 0; i < 9; i++) { - freezeBelow(player.getLocation().add(i / 3 - 1, 0, i / 3 - 1).getBlock()); + this.freezeBelow(this.player.getLocation().add(i / 3 - 1, 0, i / 3 - 1).getBlock()); } - Vector eyeDir = player.getEyeLocation().getDirection(); + final Vector eyeDir = this.player.getEyeLocation().getDirection(); eyeDir.setY(0); - double tentacleAngle = Math.toDegrees((new Vector(1, 0, 0)).angle(eyeDir)) + angleIncrement / 2; - int astep = currentAnimationStep; - for (double tangle = tentacleAngle; tangle < tentacleAngle + 360; tangle += angleIncrement) { + final double tentacleAngle = Math.toDegrees((new Vector(1, 0, 0)).angle(eyeDir)) + this.angleIncrement / 2; + int astep = this.currentAnimationStep; + for (double tangle = tentacleAngle; tangle < tentacleAngle + 360; tangle += this.angleIncrement) { astep += 1; - double phi = Math.toRadians(tangle); - tentacle(location.clone().add(new Vector(radius * Math.cos(phi), 0, radius * Math.sin(phi))), astep); + final double phi = Math.toRadians(tangle); + this.tentacle(location.clone().add(new Vector(this.radius * Math.cos(phi), 0, this.radius * Math.sin(phi))), astep); } - for (TempBlock block : blocks) { - if (!newBlocks.contains(block)) { + for (final TempBlock block : this.blocks) { + if (!this.newBlocks.contains(block)) { block.revertBlock(); } } - blocks.clear(); - blocks.addAll(newBlocks); + this.blocks.clear(); + this.blocks.addAll(this.newBlocks); - if (blocks.isEmpty()) { - remove(); + if (this.blocks.isEmpty()) { + this.remove(); } } - private void tentacle(Location base, int animationstep) { + private void tentacle(final Location base, int animationstep) { if (!TempBlock.isTempBlock(base.getBlock())) { return; - } else if (!blocks.contains(TempBlock.get(base.getBlock()))) { + } else if (!this.blocks.contains(TempBlock.get(base.getBlock()))) { return; } - Vector direction = GeneralMethods.getDirection(player.getLocation(), base); + final Vector direction = GeneralMethods.getDirection(this.player.getLocation(), base); direction.setY(0); direction.normalize(); @@ -373,70 +382,70 @@ private void tentacle(Location base, int animationstep) { animationstep = animationstep % 8; } - if (currentFormHeight >= 1) { - Block baseBlock = base.clone().add(0, 1, 0).getBlock(); + if (this.currentFormHeight >= 1) { + final Block baseBlock = base.clone().add(0, 1, 0).getBlock(); if (animationstep == 1) { - addWater(baseBlock); + this.addWater(baseBlock); } else if (animationstep == 2 || animationstep == 8) { - addWater(baseBlock); + this.addWater(baseBlock); } else { - addWater(base.clone().add(direction.getX(), 1, direction.getZ()).getBlock()); + this.addWater(base.clone().add(direction.getX(), 1, direction.getZ()).getBlock()); } } - if (currentFormHeight == 2) { - Block baseBlock = base.clone().add(0, 2, 0).getBlock(); + if (this.currentFormHeight == 2) { + final Block baseBlock = base.clone().add(0, 2, 0).getBlock(); if (animationstep == 1) { - addWater(base.clone().add(-direction.getX(), 2, -direction.getZ()).getBlock()); + this.addWater(base.clone().add(-direction.getX(), 2, -direction.getZ()).getBlock()); } else if (animationstep == 3 || animationstep == 7 || animationstep == 2 || animationstep == 8) { - addWater(baseBlock); + this.addWater(baseBlock); } else if (animationstep == 4 || animationstep == 6) { - addWater(base.clone().add(direction.getX(), 2, direction.getZ()).getBlock()); + this.addWater(base.clone().add(direction.getX(), 2, direction.getZ()).getBlock()); } else { - addWater(base.clone().add(2 * direction.getX(), 2, 2 * direction.getZ()).getBlock()); + this.addWater(base.clone().add(2 * direction.getX(), 2, 2 * direction.getZ()).getBlock()); } } } - private void addWater(Block block) { + private void addWater(final Block block) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return; } if (TempBlock.isTempBlock(block)) { - TempBlock tblock = TempBlock.get(block); - if (!newBlocks.contains(tblock) && !blocks.contains(tblock) && isBendableWaterTempBlock(tblock)) { + final TempBlock tblock = TempBlock.get(block); + if (!this.newBlocks.contains(tblock) && !this.blocks.contains(tblock) && isBendableWaterTempBlock(tblock)) { if (!SurgeWave.canThaw(block)) { SurgeWave.thaw(block); } - tblock.setType(Material.STATIONARY_WATER, (byte)8); - newBlocks.add(tblock); - } else if (blocks.contains(tblock)) { - newBlocks.add(tblock); + tblock.setType(Material.STATIONARY_WATER, (byte) 8); + this.newBlocks.add(tblock); + } else if (this.blocks.contains(tblock)) { + this.newBlocks.add(tblock); } - } else if (isWaterbendable(player, block) || block.getType() == Material.FIRE || block.getType() == Material.AIR) { + } else if (this.isWaterbendable(this.player, block) || block.getType() == Material.FIRE || block.getType() == Material.AIR) { if (isWater(block) && !TempBlock.isTempBlock(block)) { ParticleEffect.WATER_BUBBLE.display((float) Math.random(), (float) Math.random(), (float) Math.random(), 0f, 5, block.getLocation().clone().add(0.5, 0.5, 0.5), 255.0); } - newBlocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); + this.newBlocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); } } - private void addBaseWater(Block block) { - freezeBelow(block); - addWater(block); + private void addBaseWater(final Block block) { + this.freezeBelow(block); + this.addWater(block); } - private void freezeBelow(Block block) { - Block toFreeze = block.getRelative(BlockFace.DOWN); + private void freezeBelow(final Block block) { + final Block toFreeze = block.getRelative(BlockFace.DOWN); if (isWater(toFreeze) && !TempBlock.isTempBlock(toFreeze)) { - pc.freeze(toFreeze); + this.pc.freeze(toFreeze); } } - public static boolean wasBrokenFor(Player player, Block block) { - OctopusForm form = getAbility(player, OctopusForm.class); + public static boolean wasBrokenFor(final Player player, final Block block) { + final OctopusForm form = getAbility(player, OctopusForm.class); if (form != null) { if (form.sourceBlock == null) { return false; @@ -450,45 +459,45 @@ public static boolean wasBrokenFor(Player player, Block block) { @Override public void remove() { super.remove(); - returnWater(); + this.returnWater(); - if (source != null) { - source.revertBlock(); + if (this.source != null) { + this.source.revertBlock(); } - for (TempBlock block : blocks) { + for (final TempBlock block : this.blocks) { block.revertBlock(); } new BukkitRunnable() { @Override public void run() { - pc.remove(); + OctopusForm.this.pc.remove(); } - + }.runTaskLater(ProjectKorra.plugin, 1000); } private void returnWater() { - if (source != null) { - source.revertBlock(); - new WaterReturn(player, source.getLocation().getBlock()); - source = null; + if (this.source != null) { + this.source.revertBlock(); + new WaterReturn(this.player, this.source.getLocation().getBlock()); + this.source = null; } else { - Location location = player.getLocation(); - double rtheta = Math.toRadians(startAngle); - Block block = location.clone().add(new Vector(radius * Math.cos(rtheta), 0, radius * Math.sin(rtheta))).getBlock(); - new WaterReturn(player, block); + final Location location = this.player.getLocation(); + final double rtheta = Math.toRadians(this.startAngle); + final Block block = location.clone().add(new Vector(this.radius * Math.cos(rtheta), 0, this.radius * Math.sin(rtheta))).getBlock(); + new WaterReturn(this.player, block); } } @Override public Location getLocation() { - if (sourceBlock != null) { - return sourceBlock.getLocation(); - } else if (sourceLocation != null) { - return sourceLocation; + if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); + } else if (this.sourceLocation != null) { + return this.sourceLocation; } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override @@ -498,7 +507,7 @@ public String getName() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -513,187 +522,187 @@ public boolean isHarmlessAbility() { @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public boolean isSourceSelected() { - return sourceSelected; + return this.sourceSelected; } - public void setSourceSelected(boolean sourceSelected) { + public void setSourceSelected(final boolean sourceSelected) { this.sourceSelected = sourceSelected; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isForming() { - return forming; + return this.forming; } - public void setForming(boolean forming) { + public void setForming(final boolean forming) { this.forming = forming; } public boolean isFormed() { - return formed; + return this.formed; } - public void setFormed(boolean formed) { + public void setFormed(final boolean formed) { this.formed = formed; } public int getRange() { - return range; + return this.range; } - public void setRange(int range) { + public void setRange(final int range) { this.range = range; } public int getDamage() { - return damage; + return this.damage; } - public void setDamage(int damage) { + public void setDamage(final int damage) { this.damage = damage; } public int getCurrentAnimationStep() { - return currentAnimationStep; + return this.currentAnimationStep; } - public void setCurrentAnimationStep(int currentAnimationStep) { + public void setCurrentAnimationStep(final int currentAnimationStep) { this.currentAnimationStep = currentAnimationStep; } public int getStepCounter() { - return stepCounter; + return this.stepCounter; } - public void setStepCounter(int stepCounter) { + public void setStepCounter(final int stepCounter) { this.stepCounter = stepCounter; } public int getTotalStepCount() { - return totalStepCount; + return this.totalStepCount; } - public void setTotalStepCount(int totalStepCount) { + public void setTotalStepCount(final int totalStepCount) { this.totalStepCount = totalStepCount; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getAttackRange() { - return attackRange; + return this.attackRange; } - public void setAttackRange(double attackRange) { + public void setAttackRange(final double attackRange) { this.attackRange = attackRange; } public double getKnockback() { - return knockback; + return this.knockback; } - public void setKnockback(double knockback) { + public void setKnockback(final double knockback) { this.knockback = knockback; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getStartAngle() { - return startAngle; + return this.startAngle; } - public void setStartAngle(double startAngle) { + public void setStartAngle(final double startAngle) { this.startAngle = startAngle; } public double getAngle() { - return angle; + return this.angle; } - public void setAngle(double angle) { + public void setAngle(final double angle) { this.angle = angle; } public double getCurrentFormHeight() { - return currentFormHeight; + return this.currentFormHeight; } - public void setCurrentFormHeight(double currentFormHeight) { + public void setCurrentFormHeight(final double currentFormHeight) { this.currentFormHeight = currentFormHeight; } public double getAngleIncrement() { - return angleIncrement; + return this.angleIncrement; } - public void setAngleIncrement(double angleIncrement) { + public void setAngleIncrement(final double angleIncrement) { this.angleIncrement = angleIncrement; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public TempBlock getSource() { - return source; + return this.source; } - public void setSource(TempBlock source) { + public void setSource(final TempBlock source) { this.source = source; } public Location getSourceLocation() { - return sourceLocation; + return this.sourceLocation; } - public void setSourceLocation(Location sourceLocation) { + public void setSourceLocation(final Location sourceLocation) { this.sourceLocation = sourceLocation; } public ArrayList getBlocks() { - return blocks; + return this.blocks; } public ArrayList getNewBlocks() { - return newBlocks; + return this.newBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java b/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java index 17590d416..63531cee6 100644 --- a/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java +++ b/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java @@ -1,6 +1,7 @@ package com.projectkorra.projectkorra.waterbending; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -26,10 +27,10 @@ public class SurgeWall extends WaterAbility { - // private static final byte FULL = 0x0; private static final String RANGE_CONFIG = "Abilities.Water.Surge.Wall.Range"; private static final Map AFFECTED_BLOCKS = new ConcurrentHashMap<>(); private static final Map WALL_BLOCKS = new ConcurrentHashMap<>(); + public static final List SOURCE_BLOCKS = new ArrayList<>(); private boolean progressing; private boolean settingUp; @@ -38,6 +39,7 @@ public class SurgeWall extends WaterAbility { private long time; private long interval; private long cooldown; + private long duration; private double radius; private double range; private Block sourceBlock; @@ -47,49 +49,54 @@ public class SurgeWall extends WaterAbility { private ArrayList locations; private Vector firstDirection; private Vector targetDirection; + private Map oldTemps; - public SurgeWall(Player player) { + public SurgeWall(final Player player) { super(player); this.interval = getConfig().getLong("Abilities.Water.Surge.Wall.Interval"); this.cooldown = getConfig().getLong("Abilities.Water.Surge.Wall.Cooldown"); + this.duration = getConfig().getLong("Abilities.Water.Surge.Wall.Duration"); this.range = getConfig().getDouble(RANGE_CONFIG); this.radius = getConfig().getDouble("Abilities.Water.Surge.Wall.Radius"); this.locations = new ArrayList<>(); + this.oldTemps = new HashMap<>(); SurgeWave wave = getAbility(player, SurgeWave.class); - if (wave != null && !wave.isProgressing()) { + if (wave != null && !wave.isProgressing() && !this.bPlayer.isOnCooldown("SurgeWave")) { wave.moveWater(); return; } - if (bPlayer.isAvatarState()) { - radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Surge.Wall.Radius"); + if (this.bPlayer.isAvatarState()) { + this.radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Surge.Wall.Radius"); } - SurgeWall wall = getAbility(player, SurgeWall.class); + final SurgeWall wall = getAbility(player, SurgeWall.class); if (wall != null) { if (wall.progressing) { wall.freezeThaw(); return; - } else if (prepare()) { + } else if (this.prepare()) { wall.remove(); - start(); - time = System.currentTimeMillis(); + this.start(); + this.time = System.currentTimeMillis(); } - } else if (prepare()) { - start(); - time = System.currentTimeMillis(); + } else if (!this.bPlayer.isOnCooldown("SurgeWall") && this.prepare()) { + this.start(); + this.time = System.currentTimeMillis(); + return; } - if (bPlayer.isOnCooldown("SurgeWall")) { + if (this.bPlayer.isOnCooldown("SurgeWave") || player.isSneaking()) { return; } else if (wall == null && WaterReturn.hasWaterBottle(player)) { - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { - TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 0); + final TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 0); + SOURCE_BLOCKS.add(tempBlock); wave = new SurgeWave(player); wave.setCanHitSelf(false); @@ -100,25 +107,27 @@ public SurgeWall(Player player) { } else { WaterReturn.emptyWaterBottle(player); } + + SOURCE_BLOCKS.remove(tempBlock); tempBlock.revertBlock(); } } } private void freezeThaw() { - if (!bPlayer.canIcebend()) { + if (!this.bPlayer.canIcebend()) { return; - } else if (frozen) { - thaw(); + } else if (this.frozen) { + this.thaw(); } else { - freeze(); + this.freeze(); } } private void freeze() { - frozen = true; - for (Block block : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(block) == player) { + this.frozen = true; + for (final Block block : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(block) == this.player) { new TempBlock(block, Material.ICE, (byte) 0); playIcebendingSound(block.getLocation()); } @@ -126,28 +135,28 @@ private void freeze() { } private void thaw() { - frozen = false; - for (Block block : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(block) == player) { + this.frozen = false; + for (final Block block : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(block) == this.player) { new TempBlock(block, Material.STATIONARY_WATER, (byte) 8); } } } public boolean prepare() { - cancelPrevious(); - Block block = BlockSource.getWaterSourceBlock(player, range, ClickType.LEFT_CLICK, true, true, bPlayer.canPlantbend()); + this.cancelPrevious(); + final Block block = BlockSource.getWaterSourceBlock(this.player, this.range, ClickType.LEFT_CLICK, true, true, this.bPlayer.canPlantbend()); if (block != null && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - sourceBlock = block; - focusBlock(); + this.sourceBlock = block; + this.focusBlock(); return true; } return false; } private void cancelPrevious() { - SurgeWall oldWave = getAbility(player, SurgeWall.class); + final SurgeWall oldWave = getAbility(this.player, SurgeWall.class); if (oldWave != null) { if (oldWave.progressing) { oldWave.removeWater(oldWave.sourceBlock); @@ -158,42 +167,41 @@ private void cancelPrevious() { } private void focusBlock() { - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } - @SuppressWarnings("deprecation") public void moveWater() { - if (sourceBlock != null) { - targetDestination = player.getTargetBlock(getTransparentMaterialSet(), (int) range).getLocation(); + if (this.sourceBlock != null) { + this.targetDestination = this.player.getTargetBlock(getTransparentMaterialSet(), (int) this.range).getLocation(); - if (targetDestination.distanceSquared(location) <= 1) { - progressing = false; - targetDestination = null; + if (this.targetDestination.distanceSquared(this.location) <= 1) { + this.progressing = false; + this.targetDestination = null; } else { - bPlayer.addCooldown("SurgeWall", cooldown); - progressing = true; - settingUp = true; - firstDestination = getToEyeLevel(); - firstDirection = getDirection(sourceBlock.getLocation(), firstDestination); - targetDirection = getDirection(firstDestination, targetDestination); - - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); + this.bPlayer.addCooldown("SurgeWall", this.cooldown); + this.progressing = true; + this.settingUp = true; + this.firstDestination = this.getToEyeLevel(); + this.firstDirection = this.getDirection(this.sourceBlock.getLocation(), this.firstDestination); + this.targetDirection = this.getDirection(this.firstDestination, this.targetDestination); + + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); } - addWater(sourceBlock); + this.addWater(this.sourceBlock); } } } private Location getToEyeLevel() { - Location loc = sourceBlock.getLocation().clone(); - loc.setY(targetDestination.getY()); + final Location loc = this.sourceBlock.getLocation().clone(); + loc.setY(this.targetDestination.getY()); return loc; } - private Vector getDirection(Location location, Location destination) { + private Vector getDirection(final Location location, final Location destination) { double x1, y1, z1; double x0, y0, z0; @@ -210,40 +218,44 @@ private Vector getDirection(Location location, Location destination) { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); + return; + } else if (this.duration != 0 && System.currentTimeMillis() > this.getStartTime() + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - locations.clear(); + this.locations.clear(); - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - boolean matchesName = bPlayer.getBoundAbilityName().equals(getName()); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + final boolean matchesName = this.bPlayer.getBoundAbilityName().equals(this.getName()); - if (!progressing && !matchesName) { - remove(); + if (!this.progressing && !matchesName) { + this.remove(); return; - } else if (progressing && (!player.isSneaking() || !matchesName)) { - remove(); + } else if (this.progressing && (!this.player.isSneaking() || !matchesName)) { + this.remove(); return; - } else if (!progressing) { - sourceBlock.getWorld().playEffect(location, Effect.SMOKE, 4, (int) range); + } else if (!this.progressing) { + this.sourceBlock.getWorld().playEffect(this.location, Effect.SMOKE, 4, (int) this.range); return; } - if (forming) { + if (this.forming) { if ((new Random()).nextInt(7) == 0) { - playWaterbendingSound(location); + playWaterbendingSound(this.location); } - ArrayList blocks = new ArrayList(); - Location targetLoc = GeneralMethods.getTargetedLocation(player, (int) range, Material.WATER, Material.STATIONARY_WATER, Material.ICE); - location = targetLoc.clone(); - Vector eyeDir = player.getEyeLocation().getDirection(); + final ArrayList blocks = new ArrayList(); + final Location targetLoc = GeneralMethods.getTargetedLocation(this.player, (int) this.range, Material.WATER, Material.STATIONARY_WATER, Material.ICE); + this.location = targetLoc.clone(); + final Vector eyeDir = this.player.getEyeLocation().getDirection(); Vector vector; Block block; - for (double i = 0; i <= getNightFactor(radius); i += 0.5) { + for (double i = 0; i <= this.getNightFactor(this.radius); i += 0.5) { for (double angle = 0; angle < 360; angle += 10) { vector = GeneralMethods.getOrthogonalVector(eyeDir.clone(), angle, i); block = targetLoc.clone().add(vector).getBlock(); @@ -252,64 +264,68 @@ public void progress() { continue; } else if (WALL_BLOCKS.containsKey(block)) { blocks.add(block); - } else if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE || isWaterbendable(block)) && isTransparent(block)) { - WALL_BLOCKS.put(block, player); - addWallBlock(block); + } else if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE || this.isWaterbendable(block)) && this.isTransparent(block)) { + WALL_BLOCKS.put(block, this.player); + this.addWallBlock(block); blocks.add(block); - locations.add(block.getLocation()); + this.locations.add(block.getLocation()); FireBlast.removeFireBlastsAroundPoint(block.getLocation(), 2); } } } - for (Block blocki : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(blocki) == player && !blocks.contains(blocki)) { - finalRemoveWater(blocki); + for (final Block blocki : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(blocki) == this.player && !blocks.contains(blocki)) { + this.finalRemoveWater(blocki); } } return; } - if (sourceBlock.getLocation().distanceSquared(firstDestination) < 0.5 * 0.5 && settingUp) { - settingUp = false; + if (this.sourceBlock.getLocation().distanceSquared(this.firstDestination) < 0.5 * 0.5 && this.settingUp) { + this.settingUp = false; } Vector direction; - if (settingUp) { - direction = firstDirection; + if (this.settingUp) { + direction = this.firstDirection; } else { - direction = targetDirection; + direction = this.targetDirection; } - location = location.clone().add(direction); + this.location = this.location.clone().add(direction); - Block block = location.getBlock(); - if (block.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block = location.getBlock(); + Block block = this.location.getBlock(); + if (block.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); } if (block.getType() != Material.AIR) { - remove(); + this.remove(); return; - } else if (!progressing) { - remove(); + } else if (!this.progressing) { + this.remove(); return; } - addWater(block); - removeWater(sourceBlock); - sourceBlock = block; + this.addWater(block); + this.removeWater(this.sourceBlock); + this.sourceBlock = block; - if (location.distanceSquared(targetDestination) < 1) { - removeWater(sourceBlock); - forming = true; + if (this.location.distanceSquared(this.targetDestination) < 1) { + this.removeWater(this.sourceBlock); + this.forming = true; } } } - private void addWallBlock(Block block) { - if (frozen) { + private void addWallBlock(final Block block) { + if (TempBlock.isTempBlock(block)) { + this.oldTemps.put(block, block.getType()); + } + + if (this.frozen) { new TempBlock(block, Material.ICE, (byte) 0); } else { new TempBlock(block, Material.STATIONARY_WATER, (byte) 8); @@ -319,42 +335,57 @@ private void addWallBlock(Block block) { @Override public void remove() { super.remove(); - returnWater(); - finalRemoveWater(sourceBlock); + this.returnWater(); + this.finalRemoveWater(this.sourceBlock); - for (Block block : WALL_BLOCKS.keySet()) { - if (WALL_BLOCKS.get(block) == player) { - finalRemoveWater(block); + for (final Block block : WALL_BLOCKS.keySet()) { + if (WALL_BLOCKS.get(block) == this.player) { + this.finalRemoveWater(block); } } } - private void removeWater(Block block) { + private void removeWater(final Block block) { if (block != null) { if (AFFECTED_BLOCKS.containsKey(block)) { if (!GeneralMethods.isAdjacentToThreeOrMoreSources(block)) { - TempBlock.revertBlock(block, Material.AIR); + if (this.oldTemps.containsKey(block)) { + final TempBlock tb = TempBlock.get(block); + tb.setType(this.oldTemps.get(block)); + } else { + TempBlock.revertBlock(block, Material.AIR); + } } AFFECTED_BLOCKS.remove(block); } } } - private static void finalRemoveWater(Block block) { + private void finalRemoveWater(final Block block) { if (block != null) { if (AFFECTED_BLOCKS.containsKey(block)) { - TempBlock.revertBlock(block, Material.AIR); + if (this.oldTemps.containsKey(block)) { + final TempBlock tb = TempBlock.get(block); + tb.setType(this.oldTemps.get(block)); + } else { + TempBlock.revertBlock(block, Material.AIR); + } AFFECTED_BLOCKS.remove(block); } if (WALL_BLOCKS.containsKey(block)) { - TempBlock.revertBlock(block, Material.AIR); + if (this.oldTemps.containsKey(block)) { + final TempBlock tb = TempBlock.get(block); + tb.setType(this.oldTemps.get(block)); + } else { + TempBlock.revertBlock(block, Material.AIR); + } WALL_BLOCKS.remove(block); } } } - private void addWater(Block block) { + private void addWater(final Block block) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return; } else if (!TempBlock.isTempBlock(block)) { @@ -362,47 +393,68 @@ private void addWater(Block block) { AFFECTED_BLOCKS.put(block, block); } } - + @Override public boolean allowBreakPlants() { return false; } - public static void form(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void form(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } - int range = getConfig().getInt(RANGE_CONFIG); + final int range = getConfig().getInt(RANGE_CONFIG); SurgeWall wall = getAbility(player, SurgeWall.class); SurgeWave wave = getAbility(player, SurgeWave.class); + if (wave != null) { + if (wave.isProgressing() && !wave.isFreezing()) { + // Freeze the wave. + new SurgeWave(player); + } else if (wave.isActivateFreeze()) { + wave.remove(); + return; + } + } + if (wall == null) { - if (wave == null && BlockSource.getWaterSourceBlock(player, range, ClickType.LEFT_CLICK, true, true, bPlayer.canPlantbend()) == null && WaterReturn.hasWaterBottle(player)) { + final Block source = BlockSource.getWaterSourceBlock(player, range, ClickType.SHIFT_DOWN, true, true, bPlayer.canPlantbend()); + + if (wave == null && source == null && WaterReturn.hasWaterBottle(player)) { if (bPlayer.isOnCooldown("SurgeWall")) { return; } - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { - TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 0); + final TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 0); + SOURCE_BLOCKS.add(tempBlock); wall = new SurgeWall(player); wall.moveWater(); + if (!wall.progressing) { + SOURCE_BLOCKS.remove(tempBlock); tempBlock.revertBlock(); wall.remove(); } else { WaterReturn.emptyWaterBottle(player); } + + SOURCE_BLOCKS.remove(tempBlock); tempBlock.revertBlock(); return; } } - wave = new SurgeWave(player); + // If SurgeWall isn't being created, then try to source SurgeWave. + if (!bPlayer.isOnCooldown("SurgeWave")) { + wave = new SurgeWave(player); + } return; } else { if (isWaterbendable(player, null, player.getTargetBlock((HashSet) null, range))) { @@ -417,24 +469,20 @@ public static void form(Player player) { } public static void removeAllCleanup() { - for (Block block : AFFECTED_BLOCKS.keySet()) { + for (final Block block : AFFECTED_BLOCKS.keySet()) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); WALL_BLOCKS.remove(block); } - for (Block block : WALL_BLOCKS.keySet()) { + for (final Block block : WALL_BLOCKS.keySet()) { TempBlock.revertBlock(block, Material.AIR); AFFECTED_BLOCKS.remove(block); WALL_BLOCKS.remove(block); } } - public static void thaw(Block block) { - finalRemoveWater(block); - } - - public static boolean wasBrokenFor(Player player, Block block) { - SurgeWall wall = getAbility(player, SurgeWall.class); + public static boolean wasBrokenFor(final Player player, final Block block) { + final SurgeWall wall = getAbility(player, SurgeWall.class); if (wall != null) { if (wall.sourceBlock == null) { return false; @@ -446,11 +494,11 @@ public static boolean wasBrokenFor(Player player, Block block) { } private void returnWater() { - if (location != null) { - if (frozen) { - location.getBlock().setType(Material.WATER); + if (this.location != null) { + if (this.frozen) { + this.location.getBlock().setType(Material.WATER); } - new WaterReturn(player, location.getBlock()); + new WaterReturn(this.player, this.location.getBlock()); } } @@ -461,17 +509,17 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; - } else if (sourceBlock != null) { - return sourceBlock.getLocation(); + if (this.location != null) { + return this.location; + } else if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -486,110 +534,110 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - return locations; + return this.locations; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isForming() { - return forming; + return this.forming; } - public void setForming(boolean forming) { + public void setForming(final boolean forming) { this.forming = forming; } public boolean isFrozen() { - return frozen; + return this.frozen; } - public void setFrozen(boolean frozen) { + public void setFrozen(final boolean frozen) { this.frozen = frozen; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Location getTargetDestination() { - return targetDestination; + return this.targetDestination; } - public void setTargetDestination(Location targetDestination) { + public void setTargetDestination(final Location targetDestination) { this.targetDestination = targetDestination; } public Vector getFirstDirection() { - return firstDirection; + return this.firstDirection; } - public void setFirstDirection(Vector firstDirection) { + public void setFirstDirection(final Vector firstDirection) { this.firstDirection = firstDirection; } public Vector getTargetDirection() { - return targetDirection; + return this.targetDirection; } - public void setTargetDirection(Vector targetDirection) { + public void setTargetDirection(final Vector targetDirection) { this.targetDirection = targetDirection; } @@ -601,11 +649,11 @@ public static Map getWallBlocks() { return WALL_BLOCKS; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/SurgeWave.java b/src/com/projectkorra/projectkorra/waterbending/SurgeWave.java index c21dd9d70..f5de04c5d 100644 --- a/src/com/projectkorra/projectkorra/waterbending/SurgeWave.java +++ b/src/com/projectkorra/projectkorra/waterbending/SurgeWave.java @@ -52,7 +52,7 @@ public class SurgeWave extends WaterAbility { private Map waveBlocks; private Map frozenBlocks; - public SurgeWave(Player player) { + public SurgeWave(final Player player) { super(player); SurgeWave wave = getAbility(player, SurgeWave.class); @@ -77,75 +77,75 @@ public SurgeWave(Player player) { this.waveBlocks = new ConcurrentHashMap<>(); this.frozenBlocks = new ConcurrentHashMap<>(); - if (bPlayer.isAvatarState()) { - maxRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Surge.Wave.Radius"); + if (this.bPlayer.isAvatarState()) { + this.maxRadius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Surge.Wave.Radius"); } - maxRadius = getNightFactor(maxRadius); + this.maxRadius = this.getNightFactor(this.maxRadius); - if (prepare()) { + if (this.prepare()) { wave = getAbility(player, SurgeWave.class); if (wave != null) { wave.remove(); } - start(); - time = System.currentTimeMillis(); + this.start(); + this.time = System.currentTimeMillis(); } } - private void addWater(Block block) { + private void addWater(final Block block) { if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return; } else if (!TempBlock.isTempBlock(block)) { new TempBlock(block, Material.STATIONARY_WATER, (byte) 8); - waveBlocks.put(block, block); + this.waveBlocks.put(block, block); } } private void cancelPrevious() { - SurgeWave oldWave = getAbility(player, SurgeWave.class); + final SurgeWave oldWave = getAbility(this.player, SurgeWave.class); if (oldWave != null) { oldWave.remove(); } } private void clearWave() { - for (Block block : waveBlocks.keySet()) { + for (final Block block : this.waveBlocks.keySet()) { TempBlock.revertBlock(block, Material.AIR); } - waveBlocks.clear(); + this.waveBlocks.clear(); } - private void finalRemoveWater(Block block) { - if (waveBlocks.containsKey(block)) { + private void finalRemoveWater(final Block block) { + if (this.waveBlocks.containsKey(block)) { TempBlock.revertBlock(block, Material.AIR); - waveBlocks.remove(block); + this.waveBlocks.remove(block); } } private void focusBlock() { - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } private void freeze() { - clearWave(); - if (!bPlayer.canIcebend()) { + this.clearWave(); + if (!this.bPlayer.canIcebend()) { return; } - double freezeradius = currentRadius; - if (freezeradius > maxFreezeRadius) { - freezeradius = maxFreezeRadius; + double freezeradius = this.currentRadius; + if (freezeradius > this.maxFreezeRadius) { + freezeradius = this.maxFreezeRadius; } - for (final Block block : GeneralMethods.getBlocksAroundPoint(frozenLocation, freezeradius)) { - if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation()) || GeneralMethods.isRegionProtectedFromBuild(player, "PhaseChange", block.getLocation())) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.frozenLocation, freezeradius)) { + if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation()) || GeneralMethods.isRegionProtectedFromBuild(this.player, "PhaseChange", block.getLocation())) { continue; } else if (TempBlock.isTempBlock(block)) { continue; } - Block oldBlock = block; - TempBlock tblock = new TempBlock(block, block.getType(), (byte) 0); + final Block oldBlock = block; + final TempBlock tblock = new TempBlock(block, block.getType(), (byte) 0); if (block.getType() == Material.AIR || block.getType() == Material.SNOW || isWater(block)) { tblock.setType(Material.ICE); } else if (isPlant(block) && block.getType() != Material.LEAVES) { @@ -159,13 +159,13 @@ private void freeze() { @Override public void run() { - frozenBlocks.remove(block); + SurgeWave.this.frozenBlocks.remove(block); } - + }); - tblock.setRevertTime(iceRevertTime + (new Random().nextInt(1000))); - frozenBlocks.put(block, oldBlock.getType()); - for (Block sound : frozenBlocks.keySet()) { + tblock.setRevertTime(this.iceRevertTime + (new Random().nextInt(1000))); + this.frozenBlocks.put(block, oldBlock.getType()); + for (final Block sound : this.frozenBlocks.keySet()) { if ((new Random()).nextInt(4) == 0) { playWaterbendingSound(sound.getLocation()); } @@ -173,7 +173,7 @@ public void run() { } } - private Vector getDirection(Location location, Location destination) { + private Vector getDirection(final Location location, final Location destination) { double x1, y1, z1; double x0, y0, z0; @@ -188,53 +188,52 @@ private Vector getDirection(Location location, Location destination) { return new Vector(x1 - x0, y1 - y0, z1 - z0); } - @SuppressWarnings("deprecation") public void moveWater() { - if (bPlayer.isOnCooldown("SurgeWave")) { + if (this.bPlayer.isOnCooldown("SurgeWave")) { return; } - bPlayer.addCooldown("SurgeWave", cooldown); + this.bPlayer.addCooldown("SurgeWave", this.cooldown); - if (sourceBlock != null) { - if (!sourceBlock.getWorld().equals(player.getWorld())) { + if (this.sourceBlock != null) { + if (!this.sourceBlock.getWorld().equals(this.player.getWorld())) { return; } - range = getNightFactor(range); - if (bPlayer.isAvatarState()) { - pushFactor = AvatarState.getValue(pushFactor); + this.range = this.getNightFactor(this.range); + if (this.bPlayer.isAvatarState()) { + this.pushFactor = AvatarState.getValue(this.pushFactor); } - Entity target = GeneralMethods.getTargetedEntity(player, range); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range); if (target == null) { - targetDestination = player.getTargetBlock(getTransparentMaterialSet(), (int) range).getLocation(); + this.targetDestination = this.player.getTargetBlock(getTransparentMaterialSet(), (int) this.range).getLocation(); } else { - targetDestination = ((LivingEntity) target).getEyeLocation(); + this.targetDestination = ((LivingEntity) target).getEyeLocation(); } - if (targetDestination.distanceSquared(location) <= 1) { - progressing = false; - targetDestination = null; + if (this.targetDestination.distanceSquared(this.location) <= 1) { + this.progressing = false; + this.targetDestination = null; } else { - progressing = true; - targetDirection = getDirection(sourceBlock.getLocation(), targetDestination).normalize(); - targetDestination = location.clone().add(targetDirection.clone().multiply(range)); + this.progressing = true; + this.targetDirection = this.getDirection(this.sourceBlock.getLocation(), this.targetDestination).normalize(); + this.targetDestination = this.location.clone().add(this.targetDirection.clone().multiply(this.range)); - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); } - addWater(sourceBlock); + this.addWater(this.sourceBlock); } } } public boolean prepare() { - cancelPrevious(); - Block block = BlockSource.getWaterSourceBlock(player, selectRange, ClickType.SHIFT_DOWN, true, true, bPlayer.canPlantbend()); + this.cancelPrevious(); + final Block block = BlockSource.getWaterSourceBlock(this.player, this.selectRange, ClickType.SHIFT_DOWN, true, true, this.bPlayer.canPlantbend()); if (block != null && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - sourceBlock = block; - focusBlock(); + this.sourceBlock = block; + this.focusBlock(); return true; } return false; @@ -242,88 +241,88 @@ public boolean prepare() { @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - if (!progressing && !bPlayer.getBoundAbilityName().equals(getName())) { - remove(); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + if (!this.progressing && !this.bPlayer.getBoundAbilityName().equals(this.getName())) { + this.remove(); return; - } else if (!progressing) { - sourceBlock.getWorld().playEffect(location, Effect.SMOKE, 4, (int) range); + } else if (!this.progressing) { + this.sourceBlock.getWorld().playEffect(this.location, Effect.SMOKE, 4, (int) this.range); return; } - if (activateFreeze) { - if (location.distanceSquared(player.getLocation()) > range * range) { - progressing = false; - remove(); + if (this.activateFreeze) { + if (this.location.distanceSquared(this.player.getLocation()) > this.range * this.range) { + this.progressing = false; + this.remove(); return; } } else { - Vector direction = targetDirection; - location = location.clone().add(direction); - Block blockl = location.getBlock(); - ArrayList blocks = new ArrayList(); + final Vector direction = this.targetDirection; + this.location = this.location.clone().add(direction); + final Block blockl = this.location.getBlock(); + final ArrayList blocks = new ArrayList(); - if (!GeneralMethods.isRegionProtectedFromBuild(this, location) && (((blockl.getType() == Material.AIR || blockl.getType() == Material.FIRE || isPlant(blockl) || isWater(blockl) || isWaterbendable(player, blockl))) && blockl.getType() != Material.LEAVES)) { - for (double i = 0; i <= currentRadius; i += .5) { + if (!GeneralMethods.isRegionProtectedFromBuild(this, this.location) && (((blockl.getType() == Material.AIR || blockl.getType() == Material.FIRE || isPlant(blockl) || isWater(blockl) || this.isWaterbendable(this.player, blockl))) && blockl.getType() != Material.LEAVES)) { + for (double i = 0; i <= this.currentRadius; i += .5) { for (double angle = 0; angle < 360; angle += 10) { - Vector vec = GeneralMethods.getOrthogonalVector(targetDirection, angle, i); - Block block = location.clone().add(vec).getBlock(); + final Vector vec = GeneralMethods.getOrthogonalVector(this.targetDirection, angle, i); + final Block block = this.location.clone().add(vec).getBlock(); - if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE) || isWaterbendable(block)) { + if (!blocks.contains(block) && (block.getType() == Material.AIR || block.getType() == Material.FIRE) || this.isWaterbendable(block)) { blocks.add(block); FireBlast.removeFireBlastsAroundPoint(block.getLocation(), 2); } if ((new Random()).nextInt(15) == 0) { - playWaterbendingSound(location); + playWaterbendingSound(this.location); } } } } - for (Block block : waveBlocks.keySet()) { + for (final Block block : this.waveBlocks.keySet()) { if (!blocks.contains(block)) { - finalRemoveWater(block); + this.finalRemoveWater(block); } } - for (Block block : blocks) { - if (!waveBlocks.containsKey(block)) { - addWater(block); + for (final Block block : blocks) { + if (!this.waveBlocks.containsKey(block)) { + this.addWater(block); } } - if (waveBlocks.isEmpty()) { - location = location.subtract(direction); - remove(); - progressing = false; + if (this.waveBlocks.isEmpty()) { + this.location = this.location.subtract(direction); + this.remove(); + this.progressing = false; return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2 * currentRadius)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2 * this.currentRadius)) { boolean knockback = false; - for (Block block : waveBlocks.keySet()) { + for (final Block block : this.waveBlocks.keySet()) { if (entity.getLocation().distanceSquared(block.getLocation()) <= 4) { - if (entity instanceof LivingEntity && freezing && entity.getEntityId() != player.getEntityId()) { - activateFreeze = true; - frozenLocation = entity.getLocation(); - freeze(); + if (entity instanceof LivingEntity && this.freezing && entity.getEntityId() != this.player.getEntityId()) { + this.activateFreeze = true; + this.frozenLocation = entity.getLocation(); + this.freeze(); break; } - if (entity.getEntityId() != player.getEntityId() || canHitSelf) { + if (entity.getEntityId() != this.player.getEntityId() || this.canHitSelf) { knockback = true; } } } if (knockback) { - Vector dir = direction.clone(); - dir.setY(dir.getY() * verticalFactor); - GeneralMethods.setVelocity(entity, entity.getVelocity().clone().add(dir.clone().multiply(getNightFactor(pushFactor)))); + final Vector dir = direction.clone(); + dir.setY(dir.getY() * this.verticalFactor); + GeneralMethods.setVelocity(entity, entity.getVelocity().clone().add(dir.clone().multiply(this.getNightFactor(this.pushFactor)))); entity.setFallDistance(0); if (entity.getFireTicks() > 0) { @@ -334,19 +333,19 @@ public void progress() { } } - if (!progressing) { - remove(); + if (!this.progressing) { + this.remove(); return; } - if (location.distanceSquared(targetDestination) < 1) { - progressing = false; - remove(); - returnWater(); + if (this.location.distanceSquared(this.targetDestination) < 1) { + this.progressing = false; + this.remove(); + this.returnWater(); return; } - if (currentRadius < maxRadius) { - currentRadius += 0.5; + if (this.currentRadius < this.maxRadius) { + this.currentRadius += 0.5; } } } @@ -355,24 +354,24 @@ public void progress() { @Override public void remove() { super.remove(); - thaw(); - returnWater(); - if (waveBlocks != null) { - for (Block block : waveBlocks.keySet()) { - finalRemoveWater(block); + this.thaw(); + this.returnWater(); + if (this.waveBlocks != null) { + for (final Block block : this.waveBlocks.keySet()) { + this.finalRemoveWater(block); } } } public void returnWater() { - if (location != null && player.isOnline()) { - new WaterReturn(player, location.getBlock()); + if (this.location != null && this.player.isOnline()) { + new WaterReturn(this.player, this.location.getBlock()); } } private void thaw() { - if (frozenBlocks != null) { - for (Block block : frozenBlocks.keySet()) { + if (this.frozenBlocks != null) { + for (final Block block : this.frozenBlocks.keySet()) { if (TempBlock.isTempBlock(block)) { TempBlock.get(block).revertBlock(); } @@ -380,8 +379,8 @@ private void thaw() { } } - public static boolean canThaw(Block block) { - for (SurgeWave surgeWave : getAbilities(SurgeWave.class)) { + public static boolean canThaw(final Block block) { + for (final SurgeWave surgeWave : getAbilities(SurgeWave.class)) { if (surgeWave.frozenBlocks.containsKey(block)) { return false; } @@ -390,12 +389,12 @@ public static boolean canThaw(Block block) { } public static void removeAllCleanup() { - for (SurgeWave surgeWave : getAbilities(SurgeWave.class)) { - for (Block block : surgeWave.waveBlocks.keySet()) { + for (final SurgeWave surgeWave : getAbilities(SurgeWave.class)) { + for (final Block block : surgeWave.waveBlocks.keySet()) { block.setType(Material.AIR); surgeWave.waveBlocks.remove(block); } - for (Block block : surgeWave.frozenBlocks.keySet()) { + for (final Block block : surgeWave.frozenBlocks.keySet()) { if (TempBlock.isTempBlock(block)) { TempBlock.get(block).revertBlock(); } @@ -403,8 +402,8 @@ public static void removeAllCleanup() { } } - public static boolean isBlockWave(Block block) { - for (SurgeWave surgeWave : getAbilities(SurgeWave.class)) { + public static boolean isBlockWave(final Block block) { + for (final SurgeWave surgeWave : getAbilities(SurgeWave.class)) { if (surgeWave.waveBlocks.containsKey(block)) { return true; } @@ -412,11 +411,11 @@ public static boolean isBlockWave(Block block) { return false; } - public static void thaw(Block block) { - for (SurgeWave surgeWave : getAbilities(SurgeWave.class)) { + public static void thaw(final Block block) { + for (final SurgeWave surgeWave : getAbilities(SurgeWave.class)) { if (surgeWave.frozenBlocks.containsKey(block)) { if (TempBlock.isTempBlock(block)) { - TempBlock tb = TempBlock.get(block); + final TempBlock tb = TempBlock.get(block); tb.revertBlock(); } } @@ -430,17 +429,17 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; - } else if (sourceBlock != null) { - return sourceBlock.getLocation(); + if (this.location != null) { + return this.location; + } else if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -455,162 +454,162 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return progressing || activateFreeze; + return this.progressing || this.activateFreeze; } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (Block block : waveBlocks.keySet()) { + final ArrayList locations = new ArrayList<>(); + for (final Block block : this.waveBlocks.keySet()) { locations.add(block.getLocation()); } - for (Block block : frozenBlocks.keySet()) { + for (final Block block : this.frozenBlocks.keySet()) { locations.add(block.getLocation()); } return locations; } public boolean isFreezing() { - return freezing; + return this.freezing; } - public void setFreezing(boolean freezing) { + public void setFreezing(final boolean freezing) { this.freezing = freezing; } public boolean isActivateFreeze() { - return activateFreeze; + return this.activateFreeze; } - public void setActivateFreeze(boolean activateFreeze) { + public void setActivateFreeze(final boolean activateFreeze) { this.activateFreeze = activateFreeze; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public boolean isCanHitSelf() { - return canHitSelf; + return this.canHitSelf; } - public void setCanHitSelf(boolean canHitSelf) { + public void setCanHitSelf(final boolean canHitSelf) { this.canHitSelf = canHitSelf; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getCurrentRadius() { - return currentRadius; + return this.currentRadius; } - public void setCurrentRadius(double currentRadius) { + public void setCurrentRadius(final double currentRadius) { this.currentRadius = currentRadius; } public double getMaxRadius() { - return maxRadius; + return this.maxRadius; } - public void setMaxRadius(double maxRadius) { + public void setMaxRadius(final double maxRadius) { this.maxRadius = maxRadius; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getVerticalFactor() { - return verticalFactor; + return this.verticalFactor; } - public void setVerticalFactor(double verticalFactor) { + public void setVerticalFactor(final double verticalFactor) { this.verticalFactor = verticalFactor; } public double getMaxFreezeRadius() { - return maxFreezeRadius; + return this.maxFreezeRadius; } - public void setMaxFreezeRadius(double maxFreezeRadius) { + public void setMaxFreezeRadius(final double maxFreezeRadius) { this.maxFreezeRadius = maxFreezeRadius; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getTargetDestination() { - return targetDestination; + return this.targetDestination; } - public void setTargetDestination(Location targetDestination) { + public void setTargetDestination(final Location targetDestination) { this.targetDestination = targetDestination; } public Location getFrozenLocation() { - return frozenLocation; + return this.frozenLocation; } - public void setFrozenLocation(Location frozenLocation) { + public void setFrozenLocation(final Location frozenLocation) { this.frozenLocation = frozenLocation; } public Vector getTargetDirection() { - return targetDirection; + return this.targetDirection; } - public void setTargetDirection(Vector targetDirection) { + public void setTargetDirection(final Vector targetDirection) { this.targetDirection = targetDirection; } public Map getWaveBlocks() { - return waveBlocks; + return this.waveBlocks; } public Map getFrozenBlocks() { - return frozenBlocks; + return this.frozenBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/Torrent.java b/src/com/projectkorra/projectkorra/waterbending/Torrent.java index cdedbc467..99ce31a08 100644 --- a/src/com/projectkorra/projectkorra/waterbending/Torrent.java +++ b/src/com/projectkorra/projectkorra/waterbending/Torrent.java @@ -1,5 +1,19 @@ package com.projectkorra.projectkorra.waterbending; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + import com.projectkorra.projectkorra.BendingPlayer; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.AirAbility; @@ -13,20 +27,6 @@ import com.projectkorra.projectkorra.waterbending.plant.PlantRegrowth; import com.projectkorra.projectkorra.waterbending.util.WaterReturn; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; - public class Torrent extends WaterAbility { private static final double CLEANUP_RANGE = 50; @@ -65,7 +65,7 @@ public class Torrent extends WaterAbility { private ArrayList launchedBlocks; private ArrayList hurtEntities; - public Torrent(Player player) { + public Torrent(final Player player) { super(player); this.layer = 0; @@ -89,50 +89,50 @@ public Torrent(Player player) { this.launchedBlocks = new ArrayList<>(); this.hurtEntities = new ArrayList<>(); - Torrent oldTorrent = getAbility(player, Torrent.class); + final Torrent oldTorrent = getAbility(player, Torrent.class); if (oldTorrent != null) { if (!oldTorrent.sourceSelected) { oldTorrent.use(); - bPlayer.addCooldown("Torrent", oldTorrent.cooldown); + this.bPlayer.addCooldown("Torrent", oldTorrent.cooldown); return; } else { oldTorrent.remove(); } } - if (bPlayer.isOnCooldown("Torrent")) { + if (this.bPlayer.isOnCooldown("Torrent")) { return; } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.push = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Torrent.Push"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Torrent.InitialDamage"); this.successiveDamage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.Torrent.SuccessiveDamage"); this.maxHits = getConfig().getInt("Abilities.Avatar.AvatarState.Water.Torrent.MaxHits"); } - time = System.currentTimeMillis(); - sourceBlock = BlockSource.getWaterSourceBlock(player, selectRange, ClickType.LEFT_CLICK, true, true, bPlayer.canPlantbend()); - if (sourceBlock != null && !GeneralMethods.isRegionProtectedFromBuild(this, sourceBlock.getLocation())) { - sourceSelected = true; - start(); + this.time = System.currentTimeMillis(); + this.sourceBlock = BlockSource.getWaterSourceBlock(player, this.selectRange, ClickType.LEFT_CLICK, true, true, this.bPlayer.canPlantbend()); + if (this.sourceBlock != null && !GeneralMethods.isRegionProtectedFromBuild(this, this.sourceBlock.getLocation())) { + this.sourceSelected = true; + this.start(); } } private void freeze() { - if (layer == 0) { + if (this.layer == 0) { return; - } else if (!bPlayer.canBendIgnoreBindsCooldowns(getAbility("PhaseChange"))) { + } else if (!this.bPlayer.canBendIgnoreBindsCooldowns(getAbility("PhaseChange"))) { return; } - List ice = GeneralMethods.getBlocksAroundPoint(location, layer); - for (Block block : ice) { - if (isTransparent(player, block) && block.getType() != Material.ICE) { - TempBlock tblock = new TempBlock(block, Material.ICE, (byte) 0); - FROZEN_BLOCKS.put(tblock, player); - if (revert) { - tblock.setRevertTime(revertTime + (new Random().nextInt((500 + 500) + 1) - 500)); + final List ice = GeneralMethods.getBlocksAroundPoint(this.location, this.layer); + for (final Block block : ice) { + if (isTransparent(this.player, block) && block.getType() != Material.ICE) { + final TempBlock tblock = new TempBlock(block, Material.ICE, (byte) 0); + FROZEN_BLOCKS.put(tblock, this.player); + if (this.revert) { + tblock.setRevertTime(this.revertTime + (new Random().nextInt((500 + 500) + 1) - 500)); } playIcebendingSound(block.getLocation()); } @@ -141,244 +141,243 @@ private void freeze() { @Override public void progress() { - if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() > time + interval) { - time = System.currentTimeMillis(); + if (System.currentTimeMillis() > this.time + this.interval) { + this.time = System.currentTimeMillis(); - if (sourceSelected) { - if (sourceBlock.getLocation().getWorld() != this.player.getWorld()) { - remove(); + if (this.sourceSelected) { + if (this.sourceBlock.getLocation().getWorld() != this.player.getWorld()) { + this.remove(); return; } - - if (sourceBlock.getLocation().distanceSquared(player.getLocation()) > selectRange * selectRange) { + + if (this.sourceBlock.getLocation().distanceSquared(this.player.getLocation()) > this.selectRange * this.selectRange) { return; } - if (player.isSneaking()) { - sourceSelected = false; - settingUp = true; + if (this.player.isSneaking()) { + this.sourceSelected = false; + this.settingUp = true; - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); - } else if (!GeneralMethods.isAdjacentToThreeOrMoreSources(sourceBlock)) { - sourceBlock.setType(Material.AIR); + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); + } else if (!GeneralMethods.isAdjacentToThreeOrMoreSources(this.sourceBlock)) { + this.sourceBlock.setType(Material.AIR); } - source = new TempBlock(sourceBlock, Material.STATIONARY_WATER, (byte) 8); - location = sourceBlock.getLocation(); + this.source = new TempBlock(this.sourceBlock, Material.STATIONARY_WATER, (byte) 8); + this.location = this.sourceBlock.getLocation(); } else { - playFocusWaterEffect(sourceBlock); + playFocusWaterEffect(this.sourceBlock); return; } } - if (settingUp) { - if (!player.isSneaking()) { - location = source.getLocation(); - remove(); + if (this.settingUp) { + if (!this.player.isSneaking()) { + this.location = this.source.getLocation(); + this.remove(); return; } - Location eyeLoc = player.getEyeLocation(); - double startAngle = player.getEyeLocation().getDirection().angle(new Vector(1, 0, 0)); - double dx = radius * Math.cos(startAngle); - double dy = 0; - double dz = radius * Math.sin(startAngle); - Location setup = eyeLoc.clone().add(dx, dy, dz); + final Location eyeLoc = this.player.getEyeLocation(); + final double startAngle = this.player.getEyeLocation().getDirection().angle(new Vector(1, 0, 0)); + final double dx = this.radius * Math.cos(startAngle); + final double dy = 0; + final double dz = this.radius * Math.sin(startAngle); + final Location setup = eyeLoc.clone().add(dx, dy, dz); - if (!location.getWorld().equals(player.getWorld())) { - remove(); + if (!this.location.getWorld().equals(this.player.getWorld())) { + this.remove(); return; - } else if (location.distanceSquared(setup) > range * range) { - remove(); + } else if (this.location.distanceSquared(setup) > this.range * this.range) { + this.remove(); return; } - if (location.getBlockY() > setup.getBlockY()) { - Vector direction = new Vector(0, -1, 0); - location = location.clone().add(direction); - } else if (location.getBlockY() < setup.getBlockY()) { - Vector direction = new Vector(0, 1, 0); - location = location.clone().add(direction); + if (this.location.getBlockY() > setup.getBlockY()) { + final Vector direction = new Vector(0, -1, 0); + this.location = this.location.clone().add(direction); + } else if (this.location.getBlockY() < setup.getBlockY()) { + final Vector direction = new Vector(0, 1, 0); + this.location = this.location.clone().add(direction); } else { - Vector direction = GeneralMethods.getDirection(location, setup).normalize(); - location = location.clone().add(direction); + final Vector direction = GeneralMethods.getDirection(this.location, setup).normalize(); + this.location = this.location.clone().add(direction); } - if (location.distanceSquared(setup) <= 1) { - settingUp = false; - source.revertBlock(); - source = null; - forming = true; - } else if (!location.getBlock().equals(source.getLocation().getBlock())) { - source.revertBlock(); - source = null; - Block block = location.getBlock(); - if (!isTransparent(player, block)) { - remove(); + if (this.location.distanceSquared(setup) <= 1) { + this.settingUp = false; + this.source.revertBlock(); + this.source = null; + this.forming = true; + } else if (!this.location.getBlock().equals(this.source.getLocation().getBlock())) { + this.source.revertBlock(); + this.source = null; + final Block block = this.location.getBlock(); + if (!isTransparent(this.player, block)) { + this.remove(); return; } - source = new TempBlock(location.getBlock(), Material.STATIONARY_WATER, (byte) 8); + this.source = new TempBlock(this.location.getBlock(), Material.STATIONARY_WATER, (byte) 8); } } - if (forming && !player.isSneaking()) { - location = player.getEyeLocation().add(radius, 0, 0); - remove(); + if (this.forming && !this.player.isSneaking()) { + this.location = this.player.getEyeLocation().add(this.radius, 0, 0); + this.remove(); return; } - if (forming || formed) { + if (this.forming || this.formed) { if ((new Random()).nextInt(4) == 0) { - playWaterbendingSound(location); + playWaterbendingSound(this.location); } - for (double theta = startAngle; theta < angle + startAngle; theta += 20) { - Location loc = player.getEyeLocation(); - double phi = Math.toRadians(theta); - double dx = Math.cos(phi) * radius; - double dy = 0; - double dz = Math.sin(phi) * radius; + for (double theta = this.startAngle; theta < this.angle + this.startAngle; theta += 20) { + final Location loc = this.player.getEyeLocation(); + final double phi = Math.toRadians(theta); + final double dx = Math.cos(phi) * this.radius; + final double dy = 0; + final double dz = Math.sin(phi) * this.radius; loc.add(dx, dy, dz); if (isWater(loc.getBlock()) && GeneralMethods.isAdjacentToThreeOrMoreSources(loc.getBlock())) { ParticleEffect.WATER_BUBBLE.display((float) Math.random(), (float) Math.random(), (float) Math.random(), 0f, 5, loc.getBlock().getLocation().clone().add(.5, .5, .5), 255.0); } loc.subtract(dx, dy, dz); } - if (angle < 220) { - angle += 20; + if (this.angle < 220) { + this.angle += 20; } else { - forming = false; - formed = true; + this.forming = false; + this.formed = true; } - formRing(); - if (blocks.isEmpty()) { - remove(); + this.formRing(); + if (this.blocks.isEmpty()) { + this.remove(); return; } } - if (formed && !player.isSneaking() && !launch) { - new TorrentWave(player, radius); - remove(); + if (this.formed && !this.player.isSneaking() && !this.launch) { + new TorrentWave(this.player, this.radius); + this.remove(); return; } - if (launch && formed) { - launching = true; - launch = false; - formed = false; - if (!launch()) { - returnWater(location); - remove(); + if (this.launch && this.formed) { + this.launching = true; + this.launch = false; + this.formed = false; + if (!this.launch()) { + this.returnWater(this.location); + this.remove(); return; } } - if (launching) { - if (!player.isSneaking()) { - remove(); + if (this.launching) { + if (!this.player.isSneaking()) { + this.remove(); return; } - if (!launch()) { - remove(); + if (!this.launch()) { + this.remove(); return; } } } } - @SuppressWarnings("deprecation") private boolean launch() { - if (launchedBlocks.isEmpty() && blocks.isEmpty()) { + if (this.launchedBlocks.isEmpty() && this.blocks.isEmpty()) { return false; } - if (launchedBlocks.isEmpty()) { - clearRing(); - Location loc = player.getEyeLocation(); - ArrayList doneBlocks = new ArrayList(); - for (double theta = startAngle; theta < angle + startAngle; theta += 20) { - double phi = Math.toRadians(theta); - double dx = Math.cos(phi) * radius; - double dy = 0; - double dz = Math.sin(phi) * radius; - Location blockloc = loc.clone().add(dx, dy, dz); + if (this.launchedBlocks.isEmpty()) { + this.clearRing(); + final Location loc = this.player.getEyeLocation(); + final ArrayList doneBlocks = new ArrayList(); + for (double theta = this.startAngle; theta < this.angle + this.startAngle; theta += 20) { + final double phi = Math.toRadians(theta); + final double dx = Math.cos(phi) * this.radius; + final double dy = 0; + final double dz = Math.sin(phi) * this.radius; + final Location blockloc = loc.clone().add(dx, dy, dz); - if (Math.abs(theta - startAngle) < 10) { - location = blockloc.clone(); + if (Math.abs(theta - this.startAngle) < 10) { + this.location = blockloc.clone(); } - Block block = blockloc.getBlock(); + final Block block = blockloc.getBlock(); if (!doneBlocks.contains(block) && !GeneralMethods.isRegionProtectedFromBuild(this, blockloc)) { - if (isTransparent(player, block)) { - launchedBlocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); + if (isTransparent(this.player, block)) { + this.launchedBlocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); doneBlocks.add(block); - } else if (!isTransparent(player, block)) { + } else if (!isTransparent(this.player, block)) { break; } } } - if (launchedBlocks.isEmpty()) { + if (this.launchedBlocks.isEmpty()) { return false; } else { return true; } } - Entity target = GeneralMethods.getTargetedEntity(player, range, hurtEntities); - Location targetLoc = player.getTargetBlock(getTransparentMaterialSet(), (int) range).getLocation(); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range, this.hurtEntities); + Location targetLoc = this.player.getTargetBlock(getTransparentMaterialSet(), (int) this.range).getLocation(); if (target != null) { targetLoc = target.getLocation(); } - ArrayList newBlocks = new ArrayList(); - List entities = GeneralMethods.getEntitiesAroundPoint(player.getLocation(), range + 5); - List affectedEntities = new ArrayList(); - Block realBlock = launchedBlocks.get(0).getBlock(); - Vector dir = GeneralMethods.getDirection(location, targetLoc).normalize(); + final ArrayList newBlocks = new ArrayList(); + final List entities = GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.range + 5); + final List affectedEntities = new ArrayList(); + final Block realBlock = this.launchedBlocks.get(0).getBlock(); + final Vector dir = GeneralMethods.getDirection(this.location, targetLoc).normalize(); if (target != null) { - targetLoc = location.clone().add(dir.clone().multiply(10)); + targetLoc = this.location.clone().add(dir.clone().multiply(10)); } - if (layer == 0) { - location = location.clone().add(dir); + if (this.layer == 0) { + this.location = this.location.clone().add(dir); } - Block locBlock = location.getBlock(); - if (location.distanceSquared(player.getLocation()) > range * range || GeneralMethods.isRegionProtectedFromBuild(this, location)) { - if (layer < maxLayer) { - if (freeze || layer < 1) { - layer++; + final Block locBlock = this.location.getBlock(); + if (this.location.distanceSquared(this.player.getLocation()) > this.range * this.range || GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + if (this.layer < this.maxLayer) { + if (this.freeze || this.layer < 1) { + this.layer++; } } - if (launchedBlocks.size() == 1) { - remove(); + if (this.launchedBlocks.size() == 1) { + this.remove(); return false; } - } else if (!isTransparent(player, locBlock)) { - if (layer < maxLayer) { - if (layer == 0) { - hurtEntities.clear(); + } else if (!isTransparent(this.player, locBlock)) { + if (this.layer < this.maxLayer) { + if (this.layer == 0) { + this.hurtEntities.clear(); } - if (freeze || layer < 1) { - layer++; + if (this.freeze || this.layer < 1) { + this.layer++; } } - if (freeze) { - freeze(); - } else if (launchedBlocks.size() == 1) { - location = realBlock.getLocation(); - remove(); + if (this.freeze) { + this.freeze(); + } else if (this.launchedBlocks.size() == 1) { + this.location = realBlock.getLocation(); + this.remove(); return false; } } else { - if (locBlock.equals(realBlock) && layer == 0) { + if (locBlock.equals(realBlock) && this.layer == 0) { return true; } if (locBlock.getLocation().distanceSquared(targetLoc) > 1) { @@ -387,35 +386,35 @@ private boolean launch() { } newBlocks.add(new TempBlock(locBlock, Material.STATIONARY_WATER, (byte) 8)); } else { - if (layer < maxLayer) { - if (layer == 0) { - hurtEntities.clear(); + if (this.layer < this.maxLayer) { + if (this.layer == 0) { + this.hurtEntities.clear(); } - if (freeze || layer < 1) { - layer++; + if (this.freeze || this.layer < 1) { + this.layer++; } } - if (freeze) { - freeze(); + if (this.freeze) { + this.freeze(); } } } - for (int i = 0; i < launchedBlocks.size(); i++) { - TempBlock block = launchedBlocks.get(i); - if (i == launchedBlocks.size() - 1) { + for (int i = 0; i < this.launchedBlocks.size(); i++) { + final TempBlock block = this.launchedBlocks.get(i); + if (i == this.launchedBlocks.size() - 1) { block.revertBlock(); } else { newBlocks.add(block); - for (Entity entity : entities) { + for (final Entity entity : entities) { if (entity.getWorld() != block.getBlock().getWorld()) { continue; } if (entity.getLocation().distanceSquared(block.getLocation()) <= 1.5 * 1.5 && !affectedEntities.contains(entity)) { if (i == 0) { - affect(entity, dir); + this.affect(entity, dir); } else { - affect(entity, GeneralMethods.getDirection(block.getLocation(), launchedBlocks.get(i - 1).getLocation()).normalize()); + this.affect(entity, GeneralMethods.getDirection(block.getLocation(), this.launchedBlocks.get(i - 1).getLocation()).normalize()); } affectedEntities.add(entity); } @@ -423,41 +422,41 @@ private boolean launch() { } } - launchedBlocks.clear(); - launchedBlocks.addAll(newBlocks); + this.launchedBlocks.clear(); + this.launchedBlocks.addAll(newBlocks); - if (launchedBlocks.isEmpty()) { + if (this.launchedBlocks.isEmpty()) { return false; } return true; } private void formRing() { - clearRing(); - startAngle += 30; - - Location loc = player.getEyeLocation(); - ArrayList doneBlocks = new ArrayList(); - ArrayList affectedEntities = new ArrayList(); - List entities = GeneralMethods.getEntitiesAroundPoint(loc, radius + 2); - - for (double theta = startAngle; theta < angle + startAngle; theta += 20) { - double phi = Math.toRadians(theta); - double dx = Math.cos(phi) * radius; - double dy = 0; - double dz = Math.sin(phi) * radius; - Location blockLoc = loc.clone().add(dx, dy, dz); - Block block = blockLoc.getBlock(); + this.clearRing(); + this.startAngle += 30; + + final Location loc = this.player.getEyeLocation(); + final ArrayList doneBlocks = new ArrayList(); + final ArrayList affectedEntities = new ArrayList(); + final List entities = GeneralMethods.getEntitiesAroundPoint(loc, this.radius + 2); + + for (double theta = this.startAngle; theta < this.angle + this.startAngle; theta += 20) { + final double phi = Math.toRadians(theta); + final double dx = Math.cos(phi) * this.radius; + final double dy = 0; + final double dz = Math.sin(phi) * this.radius; + final Location blockLoc = loc.clone().add(dx, dy, dz); + final Block block = blockLoc.getBlock(); if (!doneBlocks.contains(block)) { - if (isTransparent(player, block)) { - blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); + if (isTransparent(this.player, block)) { + this.blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); doneBlocks.add(block); - for (Entity entity : entities) { + for (final Entity entity : entities) { if (entity.getWorld() != blockLoc.getWorld()) { continue; } if (!affectedEntities.contains(entity) && entity.getLocation().distanceSquared(blockLoc) <= 1.5 * 1.5) { - deflect(entity); + this.deflect(entity); } } } @@ -466,49 +465,48 @@ private void formRing() { } private void clearRing() { - for (TempBlock block : blocks) { + for (final TempBlock block : this.blocks) { block.revertBlock(); } - blocks.clear(); + this.blocks.clear(); } @Override public void remove() { super.remove(); - clearRing(); - for (TempBlock block : launchedBlocks) { + this.clearRing(); + for (final TempBlock block : this.launchedBlocks) { block.revertBlock(); } - launchedBlocks.clear(); - if (source != null) { - source.revertBlock(); + this.launchedBlocks.clear(); + if (this.source != null) { + this.source.revertBlock(); } - if (location != null) { - returnWater(location); + if (this.location != null) { + this.returnWater(this.location); } } - private void returnWater(Location location) { - new WaterReturn(player, location.getBlock()); + private void returnWater(final Location location) { + new WaterReturn(this.player, location.getBlock()); } - @SuppressWarnings("deprecation") - public static void create(Player player) { + public static void create(final Player player) { if (hasAbility(player, Torrent.class)) { return; } if (WaterReturn.hasWaterBottle(player)) { - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { if (block.getType() != Material.WATER) { block.setType(Material.STATIONARY_WATER); block.setData((byte) 8); } - Torrent tor = new Torrent(player); + final Torrent tor = new Torrent(player); if (tor.sourceSelected || tor.settingUp) { WaterReturn.emptyWaterBottle(player); @@ -520,32 +518,32 @@ public static void create(Player player) { } private void use() { - launch = true; - if (launching) { - freeze = true; + this.launch = true; + if (this.launching) { + this.freeze = true; } } - private void deflect(Entity entity) { - if (entity.getEntityId() == player.getEntityId()) { + private void deflect(final Entity entity) { + if (entity.getEntityId() == this.player.getEntityId()) { return; } double x, z, vx, vz, mag; double angle = 50; angle = Math.toRadians(angle); - x = entity.getLocation().getX() - player.getLocation().getX(); - z = entity.getLocation().getZ() - player.getLocation().getZ(); + x = entity.getLocation().getX() - this.player.getLocation().getX(); + z = entity.getLocation().getZ() - this.player.getLocation().getZ(); mag = Math.sqrt(x * x + z * z); vx = (x * Math.cos(angle) - z * Math.sin(angle)) / mag; vz = (x * Math.sin(angle) + z * Math.cos(angle)) / mag; - Vector vec = new Vector(vx, 0, vz).normalize().multiply(push); - Vector velocity = entity.getVelocity(); + final Vector vec = new Vector(vx, 0, vz).normalize().multiply(this.push); + final Vector velocity = entity.getVelocity(); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { velocity.setX(AvatarState.getValue(vec.getX())); velocity.setZ(AvatarState.getValue(vec.getZ())); } else { @@ -556,43 +554,43 @@ private void deflect(Entity entity) { GeneralMethods.setVelocity(entity, velocity); entity.setFallDistance(0); if (entity instanceof LivingEntity) { - double damageDealt = getNightFactor(deflectDamage); + final double damageDealt = this.getNightFactor(this.deflectDamage); DamageHandler.damageEntity(entity, damageDealt, this); AirAbility.breakBreathbendingHold(entity); } } - private void affect(Entity entity, Vector direction) { - if (entity.getEntityId() == player.getEntityId()) { + private void affect(final Entity entity, final Vector direction) { + if (entity.getEntityId() == this.player.getEntityId()) { return; } - if (direction.getY() > maxUpwardForce) { - direction.setY(maxUpwardForce); + if (direction.getY() > this.maxUpwardForce) { + direction.setY(this.maxUpwardForce); } - if (!freeze) { - entity.setVelocity(direction.multiply(push)); + if (!this.freeze) { + entity.setVelocity(direction.multiply(this.push)); } - if (entity instanceof LivingEntity && !hurtEntities.contains(entity)) { - double damageDealt = getNightFactor(damage); - if (hits > 1 && hits <= maxHits) { - damageDealt = getNightFactor(successiveDamage); + if (entity instanceof LivingEntity && !this.hurtEntities.contains(entity)) { + double damageDealt = this.getNightFactor(this.damage); + if (this.hits > 1 && this.hits <= this.maxHits) { + damageDealt = this.getNightFactor(this.successiveDamage); } - if (hits == maxHits) { - hits = maxHits + 1; + if (this.hits == this.maxHits) { + this.hits = this.maxHits + 1; } else { - hits += 1; + this.hits += 1; } DamageHandler.damageEntity(entity, damageDealt, this); AirAbility.breakBreathbendingHold(entity); - hurtEntities.add(entity); + this.hurtEntities.add(entity); ((LivingEntity) entity).setNoDamageTicks(0); } } public static void progressAllCleanup() { - for (TempBlock block : FROZEN_BLOCKS.keySet()) { - Player player = FROZEN_BLOCKS.get(block); - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + for (final TempBlock block : FROZEN_BLOCKS.keySet()) { + final Player player = FROZEN_BLOCKS.get(block); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { FROZEN_BLOCKS.remove(block); continue; @@ -611,36 +609,36 @@ public static void progressAllCleanup() { } } - public static void thaw(Block block) { + public static void thaw(final Block block) { if (TempBlock.isTempBlock(block)) { - TempBlock tblock = TempBlock.get(block); + final TempBlock tblock = TempBlock.get(block); if (FROZEN_BLOCKS.containsKey(tblock)) { thaw(tblock); } } } - public static void thaw(TempBlock block) { + public static void thaw(final TempBlock block) { block.revertBlock(); FROZEN_BLOCKS.remove(block); } - public static boolean canThaw(Block block) { + public static boolean canThaw(final Block block) { if (TempBlock.isTempBlock(block)) { - TempBlock tblock = TempBlock.get(block); + final TempBlock tblock = TempBlock.get(block); return !FROZEN_BLOCKS.containsKey(tblock); } return true; } public static void removeCleanup() { - for (TempBlock block : FROZEN_BLOCKS.keySet()) { + for (final TempBlock block : FROZEN_BLOCKS.keySet()) { thaw(block); } } - public static boolean wasBrokenFor(Player player, Block block) { - Torrent torrent = getAbility(player, Torrent.class); + public static boolean wasBrokenFor(final Player player, final Block block) { + final Torrent torrent = getAbility(player, Torrent.class); if (torrent != null) { if (torrent.sourceBlock == null) { return false; @@ -659,12 +657,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -679,208 +677,207 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return forming || formed || launch || launching; + return this.forming || this.formed || this.launch || this.launching; } - + @Override - public boolean allowBreakPlants() - { + public boolean allowBreakPlants() { return false; } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (TempBlock tblock : blocks) { + final ArrayList locations = new ArrayList<>(); + for (final TempBlock tblock : this.blocks) { locations.add(tblock.getLocation()); } - for (TempBlock tblock : launchedBlocks) { + for (final TempBlock tblock : this.launchedBlocks) { locations.add(tblock.getLocation()); } return locations; } public boolean isSourceSelected() { - return sourceSelected; + return this.sourceSelected; } - public void setSourceSelected(boolean sourceSelected) { + public void setSourceSelected(final boolean sourceSelected) { this.sourceSelected = sourceSelected; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isForming() { - return forming; + return this.forming; } - public void setForming(boolean forming) { + public void setForming(final boolean forming) { this.forming = forming; } public boolean isFormed() { - return formed; + return this.formed; } - public void setFormed(boolean formed) { + public void setFormed(final boolean formed) { this.formed = formed; } public boolean isLaunch() { - return launch; + return this.launch; } - public void setLaunch(boolean launch) { + public void setLaunch(final boolean launch) { this.launch = launch; } public boolean isLaunching() { - return launching; + return this.launching; } - public void setLaunching(boolean launching) { + public void setLaunching(final boolean launching) { this.launching = launching; } public boolean isFreeze() { - return freeze; + return this.freeze; } - public void setFreeze(boolean freeze) { + public void setFreeze(final boolean freeze) { this.freeze = freeze; } public int getLayer() { - return layer; + return this.layer; } - public void setLayer(int layer) { + public void setLayer(final int layer) { this.layer = layer; } public int getMaxLayer() { - return maxLayer; + return this.maxLayer; } - public void setMaxLayer(int maxLayer) { + public void setMaxLayer(final int maxLayer) { this.maxLayer = maxLayer; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getStartAngle() { - return startAngle; + return this.startAngle; } - public void setStartAngle(double startAngle) { + public void setStartAngle(final double startAngle) { this.startAngle = startAngle; } public double getAngle() { - return angle; + return this.angle; } - public void setAngle(double angle) { + public void setAngle(final double angle) { this.angle = angle; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getPush() { - return push; + return this.push; } - public void setPush(double push) { + public void setPush(final double push) { this.push = push; } public double getMaxUpwardForce() { - return maxUpwardForce; + return this.maxUpwardForce; } - public void setMaxUpwardForce(double maxUpwardForce) { + public void setMaxUpwardForce(final double maxUpwardForce) { this.maxUpwardForce = maxUpwardForce; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getDeflectDamage() { - return deflectDamage; + return this.deflectDamage; } - public void setDeflectDamage(double deflectDamage) { + public void setDeflectDamage(final double deflectDamage) { this.deflectDamage = deflectDamage; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public TempBlock getSource() { - return source; + return this.source; } - public void setSource(TempBlock source) { + public void setSource(final TempBlock source) { this.source = source; } public ArrayList getBlocks() { - return blocks; + return this.blocks; } - public void setBlocks(ArrayList blocks) { + public void setBlocks(final ArrayList blocks) { this.blocks = blocks; } @@ -893,18 +890,18 @@ public static Map getFrozenBlocks() { } public ArrayList getLaunchedBlocks() { - return launchedBlocks; + return this.launchedBlocks; } public ArrayList getHurtEntities() { - return hurtEntities; + return this.hurtEntities; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/TorrentWave.java b/src/com/projectkorra/projectkorra/waterbending/TorrentWave.java index d6e5bf43b..8493a9a26 100644 --- a/src/com/projectkorra/projectkorra/waterbending/TorrentWave.java +++ b/src/com/projectkorra/projectkorra/waterbending/TorrentWave.java @@ -1,9 +1,10 @@ package com.projectkorra.projectkorra.waterbending; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.util.TempBlock; -import com.projectkorra.projectkorra.waterbending.util.WaterReturn; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -12,11 +13,10 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.util.TempBlock; +import com.projectkorra.projectkorra.waterbending.util.WaterReturn; public class TorrentWave extends WaterAbility { @@ -33,14 +33,14 @@ public class TorrentWave extends WaterAbility { private ArrayList affectedEntities; private Map> heights; - public TorrentWave(Player player, double radius) { + public TorrentWave(final Player player, final double radius) { this(player, player.getEyeLocation(), radius); } - public TorrentWave(Player player, Location location, double radius) { + public TorrentWave(final Player player, final Location location, final double radius) { super(player); - if (bPlayer.isOnCooldown("TorrentWave")) { + if (this.bPlayer.isOnCooldown("TorrentWave")) { return; } @@ -57,140 +57,140 @@ public TorrentWave(Player player, Location location, double radius) { this.blocks = new ArrayList<>(); this.affectedEntities = new ArrayList<>(); - this.knockback = getNightFactor(knockback); - this.maxRadius = getNightFactor(maxRadius); + this.knockback = this.getNightFactor(this.knockback); + this.maxRadius = this.getNightFactor(this.maxRadius); - initializeHeightsMap(); - start(); - bPlayer.addCooldown("TorrentWave", cooldown); + this.initializeHeightsMap(); + this.start(); + this.bPlayer.addCooldown("TorrentWave", this.cooldown); } private void initializeHeightsMap() { - for (int i = -1; i <= maxHeight; i++) { - ConcurrentHashMap angles = new ConcurrentHashMap<>(); - double dtheta = Math.toDegrees(1 / (maxRadius + 2)); + for (int i = -1; i <= this.maxHeight; i++) { + final ConcurrentHashMap angles = new ConcurrentHashMap<>(); + final double dtheta = Math.toDegrees(1 / (this.maxRadius + 2)); int j = 0; for (double theta = 0; theta < 360; theta += dtheta) { angles.put(j, theta); j++; } - heights.put(i, angles); + this.heights.put(i, angles); } } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() > time + interval) { - if (radius < maxRadius) { - radius += growSpeed; + if (System.currentTimeMillis() > this.time + this.interval) { + if (this.radius < this.maxRadius) { + this.radius += this.growSpeed; } else { - remove(); - returnWater(); + this.remove(); + this.returnWater(); return; } - formBurst(); - time = System.currentTimeMillis(); + this.formBurst(); + this.time = System.currentTimeMillis(); } } private void formBurst() { - for (TempBlock tempBlock : blocks) { + for (final TempBlock tempBlock : this.blocks) { tempBlock.revertBlock(); } - blocks.clear(); - affectedEntities.clear(); + this.blocks.clear(); + this.affectedEntities.clear(); - ArrayList indexList = new ArrayList(); - indexList.addAll(GeneralMethods.getEntitiesAroundPoint(origin, radius + 2)); - ArrayList torrentBlocks = new ArrayList(); + final ArrayList indexList = new ArrayList(); + indexList.addAll(GeneralMethods.getEntitiesAroundPoint(this.origin, this.radius + 2)); + final ArrayList torrentBlocks = new ArrayList(); - if (indexList.contains(player)) { - indexList.remove(player); + if (indexList.contains(this.player)) { + indexList.remove(this.player); } - for (int id : heights.keySet()) { - ConcurrentHashMap angles = heights.get(id); - for (int index : angles.keySet()) { - double angle = angles.get(index); - double theta = Math.toRadians(angle); - double dx = Math.cos(theta) * radius; - double dy = id; - double dz = Math.sin(theta) * radius; + for (final int id : this.heights.keySet()) { + final ConcurrentHashMap angles = this.heights.get(id); + for (final int index : angles.keySet()) { + final double angle = angles.get(index); + final double theta = Math.toRadians(angle); + final double dx = Math.cos(theta) * this.radius; + final double dy = id; + final double dz = Math.sin(theta) * this.radius; - Location location = origin.clone().add(dx, dy, dz); - Block block = location.getBlock(); + final Location location = this.origin.clone().add(dx, dy, dz); + final Block block = location.getBlock(); if (torrentBlocks.contains(block)) { continue; } - if (isTransparent(player, block)) { - TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 8); - blocks.add(tempBlock); + if (isTransparent(this.player, block)) { + final TempBlock tempBlock = new TempBlock(block, Material.STATIONARY_WATER, (byte) 8); + this.blocks.add(tempBlock); torrentBlocks.add(block); } else { angles.remove(index); continue; } - for (Entity entity : indexList) { - if (!affectedEntities.contains(entity)) { + for (final Entity entity : indexList) { + if (!this.affectedEntities.contains(entity)) { if (entity.getLocation().distanceSquared(location) <= 4) { - affectedEntities.add(entity); - affect(entity); + this.affectedEntities.add(entity); + this.affect(entity); } } } - Random random = new Random(); - for (Block sound : torrentBlocks) { + final Random random = new Random(); + for (final Block sound : torrentBlocks) { if (random.nextInt(50) == 0) { playWaterbendingSound(sound.getLocation()); } } } if (angles.isEmpty()) { - heights.remove(id); + this.heights.remove(id); } } - if (heights.isEmpty()) { - remove(); + if (this.heights.isEmpty()) { + this.remove(); } } - private void affect(Entity entity) { - Vector direction = GeneralMethods.getDirection(origin, entity.getLocation()); + private void affect(final Entity entity) { + final Vector direction = GeneralMethods.getDirection(this.origin, entity.getLocation()); direction.setY(0); direction.normalize(); - entity.setVelocity(entity.getVelocity().clone().add(direction.multiply(knockback))); + entity.setVelocity(entity.getVelocity().clone().add(direction.multiply(this.knockback))); } @Override public void remove() { super.remove(); - for (TempBlock block : blocks) { + for (final TempBlock block : this.blocks) { block.revertBlock(); } } private void returnWater() { - Location location = new Location(origin.getWorld(), origin.getX() + radius, origin.getY(), origin.getZ()); - if (!location.getWorld().equals(player.getWorld())) { + final Location location = new Location(this.origin.getWorld(), this.origin.getX() + this.radius, this.origin.getY(), this.origin.getZ()); + if (!location.getWorld().equals(this.player.getWorld())) { return; } - double radiusOffsetSquared = (maxRadius + 5) * (maxRadius + 5); - if (location.distanceSquared(player.getLocation()) > radiusOffsetSquared) { + final double radiusOffsetSquared = (this.maxRadius + 5) * (this.maxRadius + 5); + if (location.distanceSquared(this.player.getLocation()) > radiusOffsetSquared) { return; } - new WaterReturn(player, location.getBlock()); + new WaterReturn(this.player, location.getBlock()); } @Override @@ -200,12 +200,12 @@ public String getName() { @Override public Location getLocation() { - return origin; + return this.origin; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -220,90 +220,90 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (TempBlock tblock : blocks) { + final ArrayList locations = new ArrayList<>(); + for (final TempBlock tblock : this.blocks) { locations.add(tblock.getLocation()); } return locations; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getMaxRadius() { - return maxRadius; + return this.maxRadius; } - public void setMaxRadius(double maxRadius) { + public void setMaxRadius(final double maxRadius) { this.maxRadius = maxRadius; } public double getKnockback() { - return knockback; + return this.knockback; } - public void setKnockback(double knockback) { + public void setKnockback(final double knockback) { this.knockback = knockback; } public double getMaxHeight() { - return maxHeight; + return this.maxHeight; } - public void setMaxHeight(double maxHeight) { + public void setMaxHeight(final double maxHeight) { this.maxHeight = maxHeight; } public double getGrowSpeed() { - return growSpeed; + return this.growSpeed; } - public void setGrowSpeed(double growSpeed) { + public void setGrowSpeed(final double growSpeed) { this.growSpeed = growSpeed; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public ArrayList getBlocks() { - return blocks; + return this.blocks; } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public Map> getHeights() { - return heights; + return this.heights; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/waterbending/WaterBubble.java b/src/com/projectkorra/projectkorra/waterbending/WaterBubble.java index d3c7a6e99..8fec44546 100644 --- a/src/com/projectkorra/projectkorra/waterbending/WaterBubble.java +++ b/src/com/projectkorra/projectkorra/waterbending/WaterBubble.java @@ -1,10 +1,5 @@ package com.projectkorra.projectkorra.waterbending; -import com.projectkorra.projectkorra.ability.CoreAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.configuration.ConfigManager; -import com.projectkorra.projectkorra.util.TempBlock; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -18,34 +13,39 @@ import org.bukkit.entity.Player; import org.bukkit.material.MaterialData; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.configuration.ConfigManager; +import com.projectkorra.projectkorra.util.TempBlock; + public class WaterBubble extends WaterAbility { - private static long clickDuration; //How long the click variant lasts + private static long clickDuration; // How long the click variant lasts. private static double maxRadius; private static double speed; private static boolean requireAir = false; - + private boolean isShift; private double radius; - private boolean removing = false; //Is true when the radius is shrinking - private Map waterOrigins = new ConcurrentHashMap(); + private boolean removing = false; // Is true when the radius is shrinking. + private final Map waterOrigins = new ConcurrentHashMap(); private Location location; - private long lastActivation; //When the last click happened - - public WaterBubble(Player player, boolean isShift) { + private long lastActivation; // When the last click happened. + + public WaterBubble(final Player player, final boolean isShift) { super(player); - - setFields(); - + + this.setFields(); + if (CoreAbility.hasAbility(player, this.getClass())) { - WaterBubble bubble = CoreAbility.getAbility(player, this.getClass()); - + final WaterBubble bubble = CoreAbility.getAbility(player, this.getClass()); + if (bubble.location.getWorld().equals(player.getWorld())) { if (bubble.location.distanceSquared(player.getLocation()) < maxRadius * maxRadius) { if (bubble.removing) { bubble.removing = false; } - + bubble.location = player.getLocation(); bubble.isShift = isShift; bubble.lastActivation = System.currentTimeMillis(); @@ -56,19 +56,19 @@ public WaterBubble(Player player, boolean isShift) { } else if (requireAir && !(!player.getEyeLocation().getBlock().getType().isSolid() && !player.getEyeLocation().getBlock().isLiquid())) { return; } - - if (!bPlayer.canBend(this)) { + + if (!this.bPlayer.canBend(this)) { return; } - + this.radius = 0; this.isShift = isShift; this.location = player.getLocation(); this.lastActivation = System.currentTimeMillis(); - - start(); + + this.start(); } - + public void setFields() { clickDuration = ConfigManager.defaultConfig.get().getLong("Abilities.Water.WaterBubble.ClickDuration"); maxRadius = ConfigManager.defaultConfig.get().getDouble("Abilities.Water.WaterBubble.Radius"); @@ -81,23 +81,22 @@ public String getName() { return "WaterBubble"; } - @SuppressWarnings("deprecation") @Override public void progress() { - if (!bPlayer.canBend(this) || (isShift && !player.isSneaking()) || !this.location.getWorld().equals(player.getWorld())) { + if (!this.bPlayer.canBend(this) || (this.isShift && !this.player.isSneaking()) || !this.location.getWorld().equals(this.player.getWorld())) { this.removing = true; } - - if (System.currentTimeMillis() - this.lastActivation > clickDuration && !isShift) { + + if (System.currentTimeMillis() - this.lastActivation > clickDuration && !this.isShift) { this.removing = true; } - - if (removing) { + + if (this.removing) { this.radius -= speed; - - if (radius <= 0.1) { - radius = 0.1; - remove(); + + if (this.radius <= 0.1) { + this.radius = 0.1; + this.remove(); } } else { this.radius += speed; @@ -107,51 +106,51 @@ public void progress() { } } - List list = new ArrayList(); - - if (this.radius < maxRadius || !this.location.getBlock().equals(player.getLocation().getBlock())) { - - for (double x = -radius; x < radius; x+= 0.5) { - for (double y = -radius; y < radius; y+=0.5) { - for (double z = -radius; z < radius; z+=0.5) { - if (x * x + y * y + z * z <= radius * radius) { - Block b = location.add(x, y, z).getBlock(); - - if (!waterOrigins.containsKey(b)) { + final List list = new ArrayList(); + + if (this.radius < maxRadius || !this.location.getBlock().equals(this.player.getLocation().getBlock())) { + + for (double x = -this.radius; x < this.radius; x += 0.5) { + for (double y = -this.radius; y < this.radius; y += 0.5) { + for (double z = -this.radius; z < this.radius; z += 0.5) { + if (x * x + y * y + z * z <= this.radius * this.radius) { + final Block b = this.location.add(x, y, z).getBlock(); + + if (!this.waterOrigins.containsKey(b)) { if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.WATER) { if (!TempBlock.isTempBlock(b)) { - waterOrigins.put(b, b.getState().getData()); + this.waterOrigins.put(b, b.getState().getData()); } b.setType(Material.AIR); } } - list.add(b); //Store it to say that it should be there - location.subtract(x, y, z); + list.add(b); // Store it to say that it should be there. + this.location.subtract(x, y, z); } } } } - - //Remove all blocks that shouldn't be there - Set set = new HashSet(); - set.addAll(waterOrigins.keySet()); + + // Remove all blocks that shouldn't be there. + final Set set = new HashSet(); + set.addAll(this.waterOrigins.keySet()); set.removeAll(list); - - for (Block b : set) { + + for (final Block b : set) { if (b.getType() == Material.AIR) { - b.setType(waterOrigins.get(b).getItemType()); - b.setData(waterOrigins.get(b).getData()); + b.setType(this.waterOrigins.get(b).getItemType()); + b.setData(this.waterOrigins.get(b).getData()); } - waterOrigins.remove(b); + this.waterOrigins.remove(b); } } - - this.location = player.getLocation(); + + this.location = this.player.getLocation(); } @Override public Location getLocation() { - return location; + return this.location; } @Override @@ -168,28 +167,28 @@ public boolean isSneakAbility() { public boolean isHarmlessAbility() { return false; } - - @SuppressWarnings("deprecation") + @Override public void remove() { super.remove(); - - for (Block b : waterOrigins.keySet()) { + + for (final Block b : this.waterOrigins.keySet()) { if (b.getType() == Material.AIR) { - b.setType(waterOrigins.get(b).getItemType()); - b.setData(waterOrigins.get(b).getData()); + b.setType(this.waterOrigins.get(b).getItemType()); + b.setData(this.waterOrigins.get(b).getData()); } } } - + /** - * Returns whether the block provided is one of the air blocks used by WaterBubble - * + * Returns whether the block provided is one of the air blocks used by + * WaterBubble + * * @param block The block being tested - * @return True if it's in use + * @return True if it's in use */ - public static boolean isAir(Block block) { - for (WaterBubble bubble : CoreAbility.getAbilities(WaterBubble.class)) { + public static boolean isAir(final Block block) { + for (final WaterBubble bubble : CoreAbility.getAbilities(WaterBubble.class)) { if (bubble.waterOrigins.containsKey(block)) { return false; } @@ -197,4 +196,4 @@ public static boolean isAir(Block block) { return true; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/WaterManipulation.java b/src/com/projectkorra/projectkorra/waterbending/WaterManipulation.java index 3684ef378..c855d04cd 100644 --- a/src/com/projectkorra/projectkorra/waterbending/WaterManipulation.java +++ b/src/com/projectkorra/projectkorra/waterbending/WaterManipulation.java @@ -56,9 +56,13 @@ public class WaterManipulation extends WaterAbility { private Location targetDestination; private Vector firstDirection; private Vector targetDirection; - private HashSet waterTypes; + private final HashSet waterTypes; - public WaterManipulation(Player player) { + public WaterManipulation(final Player player) { + this(player, prepare(player, getConfig().getDouble("Abilities.Water.WaterManipulation.SelectRange"))); + } + + public WaterManipulation(final Player player, final Block source) { super(player); this.progressing = false; @@ -75,38 +79,40 @@ public WaterManipulation(Player player) { this.deflectRange = getConfig().getDouble("Abilities.Water.WaterManipulation.DeflectRange"); this.waterTypes = new HashSet(); - this.interval = (long) (1000. / speed); + this.interval = (long) (1000. / this.speed); this.waterTypes.add((byte) 0); this.waterTypes.add((byte) 8); this.waterTypes.add((byte) 9); - if (prepare()) { - prepared = true; - start(); - time = System.currentTimeMillis(); + if (source != null) { + this.sourceBlock = source; + this.focusBlock(); + this.prepared = true; + this.start(); + this.time = System.currentTimeMillis(); } } - private void cancelPrevious() { - Collection manips = getAbilities(player, WaterManipulation.class); - for (WaterManipulation oldmanip : manips) { + private static void cancelPrevious(final Player player) { + final Collection manips = getAbilities(player, WaterManipulation.class); + for (final WaterManipulation oldmanip : manips) { if (oldmanip != null && !oldmanip.progressing) { oldmanip.remove(); } } } - private void finalRemoveWater(Block block) { - if (trail != null) { - trail.revertBlock(); - trail = null; + private void finalRemoveWater(final Block block) { + if (this.trail != null) { + this.trail.revertBlock(); + this.trail = null; } - if (trail2 != null) { - trail2.revertBlock(); - trail = null; + if (this.trail2 != null) { + this.trail2.revertBlock(); + this.trail = null; } - if (displacing) { - removeWater(block); + if (this.displacing) { + this.removeWater(block); return; } if (AFFECTED_BLOCKS.containsKey(block)) { @@ -118,211 +124,207 @@ private void finalRemoveWater(Block block) { } private void focusBlock() { - location = sourceBlock.getLocation(); + this.location = this.sourceBlock.getLocation(); } private Location getToEyeLevel() { - Location loc = sourceBlock.getLocation().clone(); - double dy = targetDestination.getY() - sourceBlock.getY(); + final Location loc = this.sourceBlock.getLocation().clone(); + final double dy = this.targetDestination.getY() - this.sourceBlock.getY(); if (dy <= 2) { - loc.setY(sourceBlock.getY() + 2); + loc.setY(this.sourceBlock.getY() + 2); } else { - loc.setY(targetDestination.getY() - 1); + loc.setY(this.targetDestination.getY() - 1); } return loc; } public void moveWater() { - if (sourceBlock != null) { - if (sourceBlock.getWorld().equals(player.getWorld())) { - targetDestination = getTargetLocation(player, range); - - if (targetDestination.distanceSquared(location) <= 1) { - progressing = false; - targetDestination = null; - remove(); + if (this.sourceBlock != null) { + if (this.sourceBlock.getWorld().equals(this.player.getWorld())) { + this.targetDestination = getTargetLocation(this.player, this.range); + + if (this.targetDestination.distanceSquared(this.location) <= 1) { + this.progressing = false; + this.targetDestination = null; + this.remove(); return; } else { - progressing = true; - settingUp = true; - firstDestination = getToEyeLevel(); - firstDirection = GeneralMethods.getDirection(sourceBlock.getLocation(), firstDestination).normalize(); - targetDestination = GeneralMethods.getPointOnLine(firstDestination, targetDestination, range); - targetDirection = GeneralMethods.getDirection(firstDestination, targetDestination).normalize(); - - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); - } else if (!isIce(sourceBlock)) { - addWater(sourceBlock); + this.progressing = true; + this.settingUp = true; + this.firstDestination = this.getToEyeLevel(); + this.firstDirection = GeneralMethods.getDirection(this.sourceBlock.getLocation(), this.firstDestination).normalize(); + this.targetDestination = GeneralMethods.getPointOnLine(this.firstDestination, this.targetDestination, this.range); + this.targetDirection = GeneralMethods.getDirection(this.firstDestination, this.targetDestination).normalize(); + + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); + } else if (!isIce(this.sourceBlock)) { + addWater(this.sourceBlock); } } } - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } } - public boolean prepare() { - Block block = BlockSource.getWaterSourceBlock(player, selectRange, ClickType.SHIFT_DOWN, true, true, bPlayer.canPlantbend()); - cancelPrevious(); - //block(player); + private static Block prepare(final Player player, final double selectRange) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); - if (block != null) { - sourceBlock = block; - focusBlock(); - return true; - } - return false; + final Block block = BlockSource.getWaterSourceBlock(player, selectRange, ClickType.SHIFT_DOWN, true, true, bPlayer.canPlantbend()); + cancelPrevious(player); + + return block; } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - if (System.currentTimeMillis() - time >= interval) { - if (!progressing && !falling && !bPlayer.getBoundAbilityName().equalsIgnoreCase(getName())) { - remove(); + if (System.currentTimeMillis() - this.time >= this.interval) { + if (!this.progressing && !this.falling && !this.bPlayer.getBoundAbilityName().equalsIgnoreCase(this.getName())) { + this.remove(); return; } - if (falling) { - remove(); - new WaterReturn(player, sourceBlock); + if (this.falling) { + this.remove(); + new WaterReturn(this.player, this.sourceBlock); return; } else { - if (!progressing) { - if (!(isWater(sourceBlock.getType()) || (isIce(sourceBlock) && bPlayer.canIcebend()) || (isSnow(sourceBlock) && bPlayer.canIcebend()) || (isPlant(sourceBlock) && bPlayer.canPlantbend()))) { - remove(); + if (!this.progressing) { + if (!(isWater(this.sourceBlock.getType()) || (isIce(this.sourceBlock) && this.bPlayer.canIcebend()) || (isSnow(this.sourceBlock) && this.bPlayer.canIcebend()) || (isPlant(this.sourceBlock) && this.bPlayer.canPlantbend()))) { + this.remove(); return; } - sourceBlock.getWorld().playEffect(location, Effect.SMOKE, 4, (int) selectRange); + this.sourceBlock.getWorld().playEffect(this.location, Effect.SMOKE, 4, (int) this.selectRange); return; } - if (sourceBlock.getLocation().distanceSquared(firstDestination) < 0.5 * 0.5) { - settingUp = false; + if (this.sourceBlock.getLocation().distanceSquared(this.firstDestination) < 0.5 * 0.5) { + this.settingUp = false; } Vector direction; - if (settingUp) { - direction = firstDirection; + if (this.settingUp) { + direction = this.firstDirection; } else { - direction = targetDirection; + direction = this.targetDirection; } - Block block = location.getBlock(); - if (displacing) { - Block targetBlock = player.getTargetBlock((HashSet) null, dispelRange); - direction = GeneralMethods.getDirection(location, targetBlock.getLocation()).normalize(); - if (!location.getBlock().equals(targetBlock.getLocation())) { - location = location.clone().add(direction); - - block = location.getBlock(); - if (block.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block = location.getBlock(); + Block block = this.location.getBlock(); + if (this.displacing) { + final Block targetBlock = this.player.getTargetBlock((HashSet) null, this.dispelRange); + direction = GeneralMethods.getDirection(this.location, targetBlock.getLocation()).normalize(); + if (!this.location.getBlock().equals(targetBlock)) { + this.location = this.location.clone().add(direction); + + block = this.location.getBlock(); + if (block.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); } } } else { if ((new Random()).nextInt(4) == 0) { - playWaterbendingSound(location); + playWaterbendingSound(this.location); } - location = location.clone().add(direction); - block = location.getBlock(); - if (block.getLocation().equals(sourceBlock.getLocation())) { - location = location.clone().add(direction); - block = location.getBlock(); + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); + if (block.getLocation().equals(this.sourceBlock.getLocation())) { + this.location = this.location.clone().add(direction); + block = this.location.getBlock(); } } - if (trail2 != null) { - if (!TempBlock.isTempBlock(block) && (trail2.getBlock().equals(block))) { - trail2.revertBlock(); - trail2 = null; + if (this.trail2 != null) { + if (!TempBlock.isTempBlock(block) && (this.trail2.getBlock().equals(block))) { + this.trail2.revertBlock(); + this.trail2 = null; } } - if (trail != null) { - if (!TempBlock.isTempBlock(block) && trail.getBlock().equals(block)) { - trail.revertBlock(); - trail = null; - if (trail2 != null) { - trail2.revertBlock(); - trail2 = null; + if (this.trail != null) { + if (!TempBlock.isTempBlock(block) && this.trail.getBlock().equals(block)) { + this.trail.revertBlock(); + this.trail = null; + if (this.trail2 != null) { + this.trail2.revertBlock(); + this.trail2 = null; } } } - if (isTransparent(player, block) && !block.isLiquid()) { + if (isTransparent(this.player, block) && !block.isLiquid()) { GeneralMethods.breakBlock(block); } else if (block.getType() != Material.AIR && !isWater(block)) { - remove(); - new WaterReturn(player, sourceBlock); + this.remove(); + new WaterReturn(this.player, this.sourceBlock); return; } - if (!displacing) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { - if (entity instanceof LivingEntity && entity.getEntityId() != player.getEntityId()) { - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - entity.setVelocity(vector.normalize().multiply(pushFactor)); + if (!this.displacing) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { + if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId()) { + final Location location = this.player.getEyeLocation(); + final Vector vector = location.getDirection(); + entity.setVelocity(vector.normalize().multiply(this.pushFactor)); - if (bPlayer.isAvatarState()) { - damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.WaterManipulation.Damage"); + if (this.bPlayer.isAvatarState()) { + this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.WaterManipulation.Damage"); } - damage = getNightFactor(damage); - DamageHandler.damageEntity(entity, damage, this); + this.damage = this.getNightFactor(this.damage); + DamageHandler.damageEntity(entity, this.damage, this); AirAbility.breakBreathbendingHold(entity); - progressing = false; + this.progressing = false; } } } - if (!progressing) { - remove(); - new WaterReturn(player, sourceBlock); + if (!this.progressing) { + this.remove(); + new WaterReturn(this.player, this.sourceBlock); return; } addWater(block); - reduceWater(sourceBlock); + this.reduceWater(this.sourceBlock); - if (trail2 != null) { - trail2.revertBlock(); - trail2 = null; + if (this.trail2 != null) { + this.trail2.revertBlock(); + this.trail2 = null; } - if (trail != null) { - trail2 = trail; - trail2.setType(Material.STATIONARY_WATER, (byte) 2); + if (this.trail != null) { + this.trail2 = this.trail; + this.trail2.setType(Material.STATIONARY_WATER, (byte) 2); } - trail = new TempBlock(sourceBlock, Material.STATIONARY_WATER, (byte) 1); - sourceBlock = block; + this.trail = new TempBlock(this.sourceBlock, Material.STATIONARY_WATER, (byte) 1); + this.sourceBlock = block; - if (location.distanceSquared(targetDestination) <= 1 || location.distanceSquared(firstDestination) > range * range) { - falling = true; - progressing = false; + if (this.location.distanceSquared(this.targetDestination) <= 1 || this.location.distanceSquared(this.firstDestination) > this.range * this.range) { + this.falling = true; + this.progressing = false; } } } } - private void redirect(Player player, Location targetlocation) { - if (progressing && !settingUp) { - if (location.distanceSquared(player.getLocation()) <= range * range) { - targetDirection = GeneralMethods.getDirection(location, targetlocation).normalize(); + private void redirect(final Player player, final Location targetlocation) { + if (this.progressing && !this.settingUp) { + if (this.location.distanceSquared(player.getLocation()) <= this.range * this.range) { + this.targetDirection = GeneralMethods.getDirection(this.location, targetlocation).normalize(); } - targetDestination = targetlocation; + this.targetDestination = targetlocation; this.setPlayer(player); } } - private void reduceWater(Block block) { - if (displacing) { - removeWater(block); + private void reduceWater(final Block block) { + if (this.displacing) { + this.removeWater(block); return; } if (AFFECTED_BLOCKS.containsKey(block)) { @@ -333,7 +335,7 @@ private void reduceWater(Block block) { } } - private void removeWater(Block block) { + private void removeWater(final Block block) { if (block != null) { if (AFFECTED_BLOCKS.containsKey(block)) { if (!GeneralMethods.isAdjacentToThreeOrMoreSources(block)) { @@ -344,7 +346,7 @@ private void removeWater(Block block) { } } - private static void addWater(Block block) { + private static void addWater(final Block block) { if (!isWater(block)) { if (!AFFECTED_BLOCKS.containsKey(block)) { AFFECTED_BLOCKS.put(block, block); @@ -366,9 +368,9 @@ private static void addWater(Block block) { * {@link Collision} for the new system. */ @Deprecated - public static boolean annihilateBlasts(Location location, double radius, Player player) { + public static boolean annihilateBlasts(final Location location, final double radius, final Player player) { boolean broke = false; - for (WaterManipulation manip : getAbilities(WaterManipulation.class)) { + for (final WaterManipulation manip : getAbilities(WaterManipulation.class)) { if (manip.location.getWorld().equals(location.getWorld()) && !player.equals(manip.player) && manip.progressing) { if (manip.location.distanceSquared(location) <= radius * radius) { manip.remove(); @@ -380,8 +382,8 @@ public static boolean annihilateBlasts(Location location, double radius, Player } /** Blocks other water manips */ - public static void block(Player player) { - for (WaterManipulation manip : getAbilities(WaterManipulation.class)) { + public static void block(final Player player) { + for (final WaterManipulation manip : getAbilities(WaterManipulation.class)) { if (!manip.location.getWorld().equals(player.getWorld())) { continue; } else if (!manip.progressing) { @@ -392,20 +394,20 @@ public static void block(Player player) { continue; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = manip.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = manip.location; if (mloc.distanceSquared(location) <= manip.selectRange * manip.selectRange && GeneralMethods.getDistanceFromLine(vector, location, manip.location) < manip.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { manip.remove(); } } } - public static boolean canBubbleWater(Block block) { + public static boolean canBubbleWater(final Block block) { return canPhysicsChange(block); } - public static boolean canFlowFromTo(Block from, Block to) { + public static boolean canFlowFromTo(final Block from, final Block to) { if (AFFECTED_BLOCKS.containsKey(to) || AFFECTED_BLOCKS.containsKey(from)) { return false; } else if (WaterSpout.getAffectedBlocks().containsKey(to) || WaterSpout.getAffectedBlocks().containsKey(from)) { @@ -422,7 +424,7 @@ public static boolean canFlowFromTo(Block from, Block to) { return true; } - public static boolean canPhysicsChange(Block block) { + public static boolean canPhysicsChange(final Block block) { if (AFFECTED_BLOCKS.containsKey(block)) { return false; } else if (WaterSpout.getAffectedBlocks().containsKey(block)) { @@ -439,20 +441,20 @@ public static boolean canPhysicsChange(Block block) { return true; } - private static Location getTargetLocation(Player player, double range) { + private static Location getTargetLocation(final Player player, final double range) { Location location; - Entity target = GeneralMethods.getTargetedEntity(player, range); + final Entity target = GeneralMethods.getTargetedEntity(player, range); if (target == null) { location = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterials()); } else { - location = ((LivingEntity) target).getEyeLocation(); + location = target.getLocation(); } return location; } - public static void moveWater(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void moveWater(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; } @@ -463,7 +465,7 @@ public static void moveWater(Player player) { boolean handledPrepare = false; double range = 25; - for (WaterManipulation waterManip : getAbilities(player, WaterManipulation.class)) { + for (final WaterManipulation waterManip : getAbilities(player, WaterManipulation.class)) { range = waterManip.range; if (waterManip.prepared) { waterManip.prepared = false; @@ -472,18 +474,23 @@ public static void moveWater(Player player) { } } + if (redirectTargettedBlasts(player)) { + // Don't create a new WaterManipulation if one was redirected. + return; + } + if (!handledPrepare && WaterReturn.hasWaterBottle(player)) { - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); if (!AFFECTED_BLOCKS.containsKey(block)) { AFFECTED_BLOCKS.put(block, block); } if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { if (getTargetLocation(player, range).distanceSquared(block.getLocation()) > 1) { - TempBlock tb = new TempBlock(block, Material.WATER, (byte) 0); + final TempBlock tb = new TempBlock(block, Material.WATER, (byte) 0); - WaterManipulation waterManip = new WaterManipulation(player); + final WaterManipulation waterManip = new WaterManipulation(player, block); waterManip.moveWater(); if (!waterManip.progressing) { block.setType(Material.AIR); @@ -495,11 +502,12 @@ public static void moveWater(Player player) { } } } - redirectTargettedBlasts(player); } - private static void redirectTargettedBlasts(Player player) { - for (WaterManipulation manip : getAbilities(WaterManipulation.class)) { + private static boolean redirectTargettedBlasts(final Player player) { + boolean redirected = false; + + for (final WaterManipulation manip : getAbilities(WaterManipulation.class)) { if (!manip.progressing) { continue; } else if (!manip.location.getWorld().equals(player.getWorld())) { @@ -510,25 +518,29 @@ private static void redirectTargettedBlasts(Player player) { if (manip.player.equals(player)) { manip.redirect(player, getTargetLocation(player, manip.range)); + redirected = true; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = manip.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = manip.location; if (mloc.distanceSquared(location) <= manip.selectRange * manip.selectRange && GeneralMethods.getDistanceFromLine(vector, location, manip.location) < manip.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { - manip.redirect(player, getTargetLocation(player, manip.selectRange)); + manip.redirect(player, getTargetLocation(player, manip.range)); + redirected = true; } } + + return redirected; } @Override public void remove() { super.remove(); - finalRemoveWater(sourceBlock); + this.finalRemoveWater(this.sourceBlock); } - public static void removeAroundPoint(Location location, double radius) { - for (WaterManipulation manip : getAbilities(WaterManipulation.class)) { + public static void removeAroundPoint(final Location location, final double radius) { + for (final WaterManipulation manip : getAbilities(WaterManipulation.class)) { if (manip.location.getWorld().equals(location.getWorld())) { if (manip.location.distanceSquared(location) <= radius * radius) { manip.remove(); @@ -544,17 +556,17 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; - } else if (sourceBlock != null) { - return sourceBlock.getLocation(); + if (this.location != null) { + return this.location; + } else if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); } return null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -569,187 +581,187 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return progressing; + return this.progressing; } @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { super.handleCollision(collision); if (collision.isRemovingFirst()) { - new WaterReturn(player, sourceBlock); + new WaterReturn(this.player, this.sourceBlock); } } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public boolean isFalling() { - return falling; + return this.falling; } - public void setFalling(boolean falling) { + public void setFalling(final boolean falling) { this.falling = falling; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isDisplacing() { - return displacing; + return this.displacing; } - public void setDisplacing(boolean displacing) { + public void setDisplacing(final boolean displacing) { this.displacing = displacing; } public boolean isPrepared() { - return prepared; + return this.prepared; } - public void setPrepared(boolean prepared) { + public void setPrepared(final boolean prepared) { this.prepared = prepared; } public int getDispelRange() { - return dispelRange; + return this.dispelRange; } - public void setDispelRange(int dispelRange) { + public void setDispelRange(final int dispelRange) { this.dispelRange = dispelRange; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public double getPushFactor() { - return pushFactor; + return this.pushFactor; } - public void setPushFactor(double pushFactor) { + public void setPushFactor(final double pushFactor) { this.pushFactor = pushFactor; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getDeflectRange() { - return deflectRange; + return this.deflectRange; } - public void setDeflectRange(double deflectRange) { + public void setDeflectRange(final double deflectRange) { this.deflectRange = deflectRange; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public TempBlock getTrail() { - return trail; + return this.trail; } - public void setTrail(TempBlock trail) { + public void setTrail(final TempBlock trail) { this.trail = trail; } public TempBlock getTrail2() { - return trail2; + return this.trail2; } - public void setTrail2(TempBlock trail2) { + public void setTrail2(final TempBlock trail2) { this.trail2 = trail2; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Location getTargetDestination() { - return targetDestination; + return this.targetDestination; } - public void setTargetDestination(Location targetDestination) { + public void setTargetDestination(final Location targetDestination) { this.targetDestination = targetDestination; } public Vector getFirstDirection() { - return firstDirection; + return this.firstDirection; } - public void setFirstDirection(Vector firstDirection) { + public void setFirstDirection(final Vector firstDirection) { this.firstDirection = firstDirection; } public Vector getTargetDirection() { - return targetDirection; + return this.targetDirection; } - public void setTargetDirection(Vector targetDirection) { + public void setTargetDirection(final Vector targetDirection) { this.targetDirection = targetDirection; } @@ -758,18 +770,18 @@ public static Map getAffectedBlocks() { } public HashSet getWaterTypes() { - return waterTypes; + return this.waterTypes; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } diff --git a/src/com/projectkorra/projectkorra/waterbending/WaterSpout.java b/src/com/projectkorra/projectkorra/waterbending/WaterSpout.java index 882ef5cf8..fffacf8b5 100644 --- a/src/com/projectkorra/projectkorra/waterbending/WaterSpout.java +++ b/src/com/projectkorra/projectkorra/waterbending/WaterSpout.java @@ -13,16 +13,17 @@ import org.bukkit.potion.PotionEffectType; import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.ability.util.Collision; -import com.projectkorra.projectkorra.util.Flight; +import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.util.ParticleEffect; import com.projectkorra.projectkorra.util.TempBlock; public class WaterSpout extends WaterAbility { private static final Map AFFECTED_BLOCKS = new ConcurrentHashMap(); - private List blocks = new ArrayList(); + private final List blocks = new ArrayList(); private boolean canBendOnPackedIce; private boolean useParticles; @@ -30,18 +31,20 @@ public class WaterSpout extends WaterAbility { private int angle; private long time; private long interval; + @Attribute(Attribute.COOLDOWN) + private long cooldown; + private long duration; + private long startTime; private double rotation; private double height; private double maxHeight; private Block base; private TempBlock baseBlock; - private boolean canFly; - private boolean hadFly; - public WaterSpout(Player player) { + public WaterSpout(final Player player) { super(player); - WaterSpout oldSpout = getAbility(player, WaterSpout.class); + final WaterSpout oldSpout = getAbility(player, WaterSpout.class); if (oldSpout != null) { oldSpout.remove(); return; @@ -50,62 +53,62 @@ public WaterSpout(Player player) { this.canBendOnPackedIce = getConfig().getStringList("Properties.Water.IceBlocks").contains(Material.PACKED_ICE.toString()); this.useParticles = getConfig().getBoolean("Abilities.Water.WaterSpout.Particles"); this.useBlockSpiral = getConfig().getBoolean("Abilities.Water.WaterSpout.BlockSpiral"); + this.cooldown = getConfig().getLong("Abilities.Water.WaterSpout.Cooldown"); this.height = getConfig().getDouble("Abilities.Water.WaterSpout.Height"); this.interval = getConfig().getLong("Abilities.Water.WaterSpout.Interval"); + this.duration = getConfig().getLong("Abilities.Water.WaterSpout.Duration"); + this.startTime = System.currentTimeMillis(); - hadFly = player.isFlying(); - canFly = player.getAllowFlight(); - maxHeight = getNightFactor(height); - WaterSpoutWave spoutWave = new WaterSpoutWave(player, WaterSpoutWave.AbilityType.CLICK); + this.maxHeight = this.getNightFactor(this.height); + final WaterSpoutWave spoutWave = new WaterSpoutWave(player, WaterSpoutWave.AbilityType.CLICK); if (spoutWave.isStarted() && !spoutWave.isRemoved()) { return; } - Block topBlock = GeneralMethods.getTopBlock(player.getLocation(), (int) -getNightFactor(height), (int) -getNightFactor(height)); + Block topBlock = GeneralMethods.getTopBlock(player.getLocation(), (int) -this.getNightFactor(this.height), (int) -this.getNightFactor(this.height)); if (topBlock == null) { topBlock = player.getLocation().getBlock(); } - if (!isWater(topBlock) && !isIcebendable(topBlock) && !isSnow(topBlock)) { + if (!isWater(topBlock) && !this.isIcebendable(topBlock) && !isSnow(topBlock)) { return; - } else if (topBlock.getType() == Material.PACKED_ICE && !canBendOnPackedIce) { + } else if (topBlock.getType() == Material.PACKED_ICE && !this.canBendOnPackedIce) { return; } - double heightRemoveThreshold = 2; - if (!isWithinMaxSpoutHeight(topBlock.getLocation(), heightRemoveThreshold)) { + final double heightRemoveThreshold = 2; + if (!this.isWithinMaxSpoutHeight(topBlock.getLocation(), heightRemoveThreshold)) { return; } - - new Flight(player); + ProjectKorra.flightHandler.createInstance(player, this.getName()); player.setAllowFlight(true); - spoutableWaterHeight(player.getLocation()); //Sets base - start(); + this.spoutableWaterHeight(player.getLocation()); // Sets base. + this.start(); } - private void displayWaterSpiral(Location location) { - if (!useBlockSpiral) { + private void displayWaterSpiral(final Location location) { + if (!this.useBlockSpiral) { return; } - double maxHeight = player.getLocation().getY() - location.getY() - .5; + final double maxHeight = this.player.getLocation().getY() - location.getY() - .5; double height = 0; - rotation += .4; + this.rotation += .4; int i = 0; while (height < maxHeight) { i += 20; height += .4; - double angle = (i * Math.PI / 180); - double x = 1 * Math.cos(angle + rotation); - double z = 1 * Math.sin(angle + rotation); + final double angle = (i * Math.PI / 180); + final double x = 1 * Math.cos(angle + this.rotation); + final double z = 1 * Math.sin(angle + this.rotation); - Location loc = location.clone().getBlock().getLocation().add(.5, .5, .5); + final Location loc = location.clone().getBlock().getLocation().add(.5, .5, .5); loc.add(x, height, z); - Block block = loc.getBlock(); + final Block block = loc.getBlock(); if ((!TempBlock.isTempBlock(block)) && (block.getType().equals(Material.AIR) || !GeneralMethods.isSolid(block))) { - blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 1)); + this.blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 1)); AFFECTED_BLOCKS.put(block, block); } } @@ -113,32 +116,37 @@ private void displayWaterSpiral(Location location) { @Override public void progress() { - for (TempBlock tb : blocks) { + for (final TempBlock tb : this.blocks) { AFFECTED_BLOCKS.remove(tb.getBlock()); tb.revertBlock(); } - if (player.isDead() || !player.isOnline() || !bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (this.player.isDead() || !this.player.isOnline() || !this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); + return; + } else if (this.duration != 0 && System.currentTimeMillis() > this.startTime + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); return; } else { - blocks.clear(); - player.setFallDistance(0); - player.setSprinting(false); + this.blocks.clear(); + this.player.setFallDistance(0); + this.player.setSprinting(false); if ((new Random()).nextInt(10) == 0) { - playWaterbendingSound(player.getLocation()); + playWaterbendingSound(this.player.getLocation()); } - player.removePotionEffect(PotionEffectType.SPEED); + this.player.removePotionEffect(PotionEffectType.SPEED); - Location location = player.getLocation().clone().add(0, .2, 0); + Location location = this.player.getLocation().clone().add(0, .2, 0); Block block = location.clone().getBlock(); - double height = spoutableWaterHeight(location); + final double height = this.spoutableWaterHeight(location); if (height != -1) { - location = base.getLocation(); - double heightRemoveThreshold = 2; - if (!isWithinMaxSpoutHeight(location, heightRemoveThreshold)) { - remove(); + location = this.base.getLocation(); + final double heightRemoveThreshold = 2; + if (!this.isWithinMaxSpoutHeight(location, heightRemoveThreshold)) { + this.bPlayer.addCooldown(this); + this.remove(); return; } for (int i = 1; i <= height; i++) { @@ -146,22 +154,22 @@ public void progress() { block = location.clone().add(0, i, 0).getBlock(); if (!TempBlock.isTempBlock(block)) { - blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); + this.blocks.add(new TempBlock(block, Material.STATIONARY_WATER, (byte) 8)); AFFECTED_BLOCKS.put(block, block); } - rotateParticles(block); + this.rotateParticles(block); } - displayWaterSpiral(location.clone().add(.5, 0, .5)); - if (player.getLocation().getBlockY() > block.getY()) { - player.setFlying(false); + this.displayWaterSpiral(location.clone().add(.5, 0, .5)); + if (this.player.getLocation().getBlockY() > block.getY()) { + this.player.setFlying(false); } else { - new Flight(player); - player.setAllowFlight(true); - player.setFlying(true); + this.player.setAllowFlight(true); + this.player.setFlying(true); } } else { - remove(); + this.bPlayer.addCooldown(this); + this.remove(); return; } } @@ -170,56 +178,55 @@ public void progress() { @Override public void remove() { super.remove(); - revertBaseBlock(); - for (TempBlock tb : blocks) { + this.revertBaseBlock(); + for (final TempBlock tb : this.blocks) { AFFECTED_BLOCKS.remove(tb.getBlock()); tb.revertBlock(); } - player.setAllowFlight(canFly); - player.setFlying(hadFly); + ProjectKorra.flightHandler.removeInstance(this.player, this.getName()); } public void revertBaseBlock() { - if (baseBlock != null) { - baseBlock.revertBlock(); - baseBlock = null; + if (this.baseBlock != null) { + this.baseBlock.revertBlock(); + this.baseBlock = null; } } - private boolean isWithinMaxSpoutHeight(Location baseBlockLocation, double threshold) { + private boolean isWithinMaxSpoutHeight(final Location baseBlockLocation, final double threshold) { if (baseBlockLocation == null) { return false; } - double playerHeight = player.getLocation().getY(); - if (playerHeight > baseBlockLocation.getY() + maxHeight + threshold) { + final double playerHeight = this.player.getLocation().getY(); + if (playerHeight > baseBlockLocation.getY() + this.maxHeight + threshold) { return false; } return true; } - public void rotateParticles(Block block) { - if (!useParticles) { + public void rotateParticles(final Block block) { + if (!this.useParticles) { return; } - if (System.currentTimeMillis() >= time + interval) { - time = System.currentTimeMillis(); + if (System.currentTimeMillis() >= this.time + this.interval) { + this.time = System.currentTimeMillis(); Location location = block.getLocation(); - Location playerLoc = player.getLocation(); + final Location playerLoc = this.player.getLocation(); location = new Location(location.getWorld(), playerLoc.getX(), location.getY(), playerLoc.getZ()); double dy = playerLoc.getY() - block.getY(); - if (dy > height) { - dy = height; + if (dy > this.height) { + dy = this.height; } - float[] directions = { -0.5f, 0.325f, 0.25f, 0.125f, 0.f, 0.125f, 0.25f, 0.325f, 0.5f }; - int index = angle; - angle++; - if (angle >= directions.length) { - angle = 0; + final float[] directions = { -0.5f, 0.325f, 0.25f, 0.125f, 0.f, 0.125f, 0.25f, 0.325f, 0.5f }; + int index = this.angle; + this.angle++; + if (this.angle >= directions.length) { + this.angle = 0; } for (int i = 1; i <= dy; i++) { index += 1; @@ -227,63 +234,63 @@ public void rotateParticles(Block block) { index = 0; } - Location effectLoc2 = new Location(location.getWorld(), location.getX(), block.getY() + i, location.getZ()); - ParticleEffect.WATER_SPLASH.display(effectLoc2, directions[index], directions[index], directions[index], 5, (int) (height + 5)); + final Location effectLoc2 = new Location(location.getWorld(), location.getX(), block.getY() + i, location.getZ()); + ParticleEffect.WATER_SPLASH.display(effectLoc2, directions[index], directions[index], directions[index], 5, (int) (this.height + 5)); } } } - private double spoutableWaterHeight(Location location) { - double newHeight = height; - if (isNight(player.getWorld())) { - newHeight = getNightFactor(newHeight); + private double spoutableWaterHeight(final Location location) { + double newHeight = this.height; + if (isNight(this.player.getWorld())) { + newHeight = this.getNightFactor(newHeight); } this.maxHeight = newHeight + 5; Block blocki; - for (int i = 0; i < maxHeight; i++) { + for (int i = 0; i < this.maxHeight; i++) { blocki = location.clone().add(0, -i, 0).getBlock(); if (GeneralMethods.isRegionProtectedFromBuild(this, blocki.getLocation())) { return -1; } - if (!blocks.contains(blocki)) { + if (TempBlock.get(blocki) == null || !this.blocks.contains(TempBlock.get(blocki))) { if (isWater(blocki)) { if (!TempBlock.isTempBlock(blocki)) { - revertBaseBlock(); + this.revertBaseBlock(); } - base = blocki; + this.base = blocki; if (i > newHeight) { return newHeight; } return i; } - if (isIcebendable(blocki) || isSnow(blocki)) { - if (isIcebendable(blocki)) { - if (blocki.getType() == Material.PACKED_ICE && !canBendOnPackedIce) { - remove(); + if (this.isIcebendable(blocki) || isSnow(blocki)) { + if (this.isIcebendable(blocki)) { + if (blocki.getType() == Material.PACKED_ICE && !this.canBendOnPackedIce) { + this.remove(); return -1; } } if (!TempBlock.isTempBlock(blocki)) { - revertBaseBlock(); - baseBlock = new TempBlock(blocki, Material.STATIONARY_WATER, (byte) 8); + this.revertBaseBlock(); + this.baseBlock = new TempBlock(blocki, Material.STATIONARY_WATER, (byte) 8); } - base = blocki; + this.base = blocki; if (i > newHeight) { return newHeight; } return i; } - if ((blocki.getType() != Material.AIR && (!isPlant(blocki) || !bPlayer.canPlantbend()))) { - revertBaseBlock(); + if ((blocki.getType() != Material.AIR && (!isPlant(blocki) || !this.bPlayer.canPlantbend()))) { + this.revertBaseBlock(); return -1; } } @@ -296,15 +303,15 @@ private double spoutableWaterHeight(Location location) { * {@link Collision} for the new system. */ @Deprecated - public static boolean removeSpouts(Location loc0, double radius, Player sourcePlayer) { + public static boolean removeSpouts(final Location loc0, final double radius, final Player sourcePlayer) { boolean removed = false; - for (WaterSpout spout : getAbilities(WaterSpout.class)) { + for (final WaterSpout spout : getAbilities(WaterSpout.class)) { if (!spout.player.equals(sourcePlayer)) { - Location top = spout.getLocation(); - Location base = spout.getBase().getLocation(); - double dist = top.getBlockY() - base.getBlockY(); + final Location top = spout.getLocation(); + final Location base = spout.getBase().getLocation(); + final double dist = top.getBlockY() - base.getBlockY(); for (double d = 0; d <= dist; d += 0.5) { - Location spoutLoc = base.clone().add(0, d, 0); + final Location spoutLoc = base.clone().add(0, d, 0); if (loc0.getWorld().equals(spoutLoc.getWorld()) && loc0.distance(spoutLoc) <= radius) { removed = true; spout.remove(); @@ -322,12 +329,12 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return 0; + return this.cooldown; } @Override @@ -347,10 +354,10 @@ public boolean isCollidable() { @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - Location top = this.getLocation(); - Location iterLoc = getBase().getLocation(); - double ySpacing = 2; + final ArrayList locations = new ArrayList<>(); + final Location top = this.getLocation(); + final Location iterLoc = this.getBase().getLocation(); + final double ySpacing = 2; while (iterLoc.getY() <= top.getY()) { locations.add(iterLoc.clone()); iterLoc.add(0, ySpacing, 0); @@ -359,82 +366,82 @@ public List getLocations() { } public boolean isCanBendOnPackedIce() { - return canBendOnPackedIce; + return this.canBendOnPackedIce; } - public void setCanBendOnPackedIce(boolean canBendOnPackedIce) { + public void setCanBendOnPackedIce(final boolean canBendOnPackedIce) { this.canBendOnPackedIce = canBendOnPackedIce; } public boolean isUseParticles() { - return useParticles; + return this.useParticles; } - public void setUseParticles(boolean useParticles) { + public void setUseParticles(final boolean useParticles) { this.useParticles = useParticles; } public boolean isUseBlockSpiral() { - return useBlockSpiral; + return this.useBlockSpiral; } - public void setUseBlockSpiral(boolean useBlockSpiral) { + public void setUseBlockSpiral(final boolean useBlockSpiral) { this.useBlockSpiral = useBlockSpiral; } public int getAngle() { - return angle; + return this.angle; } - public void setAngle(int angle) { + public void setAngle(final int angle) { this.angle = angle; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRotation() { - return rotation; + return this.rotation; } - public void setRotation(double rotation) { + public void setRotation(final double rotation) { this.rotation = rotation; } public double getHeight() { - return height; + return this.height; } - public void setHeight(double height) { + public void setHeight(final double height) { this.height = height; } public Block getBase() { - return base; + return this.base; } - public void setBase(Block base) { + public void setBase(final Block base) { this.base = base; } public TempBlock getBaseBlock() { - return baseBlock; + return this.baseBlock; } - public void setBaseBlock(TempBlock baseBlock) { + public void setBaseBlock(final TempBlock baseBlock) { this.baseBlock = baseBlock; } diff --git a/src/com/projectkorra/projectkorra/waterbending/WaterSpoutWave.java b/src/com/projectkorra/projectkorra/waterbending/WaterSpoutWave.java index 05be29478..2ecbf5d26 100644 --- a/src/com/projectkorra/projectkorra/waterbending/WaterSpoutWave.java +++ b/src/com/projectkorra/projectkorra/waterbending/WaterSpoutWave.java @@ -68,7 +68,7 @@ public static enum AnimateState { private ArrayList tasks; private ConcurrentHashMap affectedBlocks; - public WaterSpoutWave(Player player, AbilityType type) { + public WaterSpoutWave(final Player player, final AbilityType type) { super(player); this.charging = false; @@ -92,13 +92,13 @@ public WaterSpoutWave(Player player, AbilityType type) { this.affectedEntities = new ArrayList<>(); this.tasks = new ArrayList<>(); - this.damage = getNightFactor(this.damage); + this.damage = this.getNightFactor(this.damage); - if (!bPlayer.canBend(this)) { + if (!this.bPlayer.canBend(this)) { return; } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.chargeTime = 0; this.flightTime = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.WaterWave.FlightTime"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceWave.Damage"); @@ -109,205 +109,205 @@ public WaterSpoutWave(Player player, AbilityType type) { this.type = type; if (type == AbilityType.CLICK && CoreAbility.getAbility(player, WaterSpoutWave.class) != null) { - WaterSpoutWave wave = CoreAbility.getAbility(player, WaterSpoutWave.class); + final WaterSpoutWave wave = CoreAbility.getAbility(player, WaterSpoutWave.class); if (wave.charging || wave.moving) { - remove(); + this.remove(); return; } } - start(); + this.start(); if (type == AbilityType.CLICK) { - // Need to progress immediately for the WaterSpout check - progress(); + // Need to progress immediately for the WaterSpout check. + this.progress(); } } @Override public void progress() { - progressCounter++; - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + this.progressCounter++; + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; } - - if (CoreAbility.hasAbility(player, WaterSpout.class)) { - WaterSpout waterSpout = CoreAbility.getAbility(player, WaterSpout.class); + + if (CoreAbility.hasAbility(this.player, WaterSpout.class)) { + final WaterSpout waterSpout = CoreAbility.getAbility(this.player, WaterSpout.class); waterSpout.remove(); } - if (type != AbilityType.RELEASE) { - if (!player.hasPermission("bending.ability.WaterSpout.Wave")) { - remove(); + if (this.type != AbilityType.RELEASE) { + if (!this.player.hasPermission("bending.ability.WaterSpout.Wave")) { + this.remove(); return; - } else if (!bPlayer.getBoundAbilityName().equals(getName())) { - remove(); + } else if (!this.bPlayer.getBoundAbilityName().equals(this.getName())) { + this.remove(); return; } } - if (type == AbilityType.CLICK) { - if (origin == null) { - removeOldType(player, AbilityType.CLICK); - Block block = getWaterSourceBlock(player, selectRange, plant); + if (this.type == AbilityType.CLICK) { + if (this.origin == null) { + this.removeOldType(this.player, AbilityType.CLICK); + final Block block = getWaterSourceBlock(this.player, this.selectRange, this.plant); if (block == null) { - remove(); + this.remove(); return; } - Block blockAbove = block.getRelative(BlockFace.UP); - if (blockAbove.getType() != Material.AIR && !isWaterbendable(blockAbove)) { - remove(); + final Block blockAbove = block.getRelative(BlockFace.UP); + if (blockAbove.getType() != Material.AIR && !this.isWaterbendable(blockAbove)) { + this.remove(); return; } - origin = block.getLocation(); - if (!isWaterbendable(block) || GeneralMethods.isRegionProtectedFromBuild(this, origin)) { - remove(); + this.origin = block.getLocation(); + if (!this.isWaterbendable(block) || GeneralMethods.isRegionProtectedFromBuild(this, this.origin)) { + this.remove(); return; - } else if (iceOnly && !(isIcebendable(block) || isSnow(block))) { - remove(); + } else if (this.iceOnly && !(this.isIcebendable(block) || isSnow(block))) { + this.remove(); return; } } - if (player.getLocation().distanceSquared(origin) > selectRange * selectRange) { - remove(); + if (this.player.getLocation().distanceSquared(this.origin) > this.selectRange * this.selectRange) { + this.remove(); return; - } else if (player.isSneaking()) { - setType(AbilityType.SHIFT); + } else if (this.player.isSneaking()) { + this.setType(AbilityType.SHIFT); return; } - playFocusWaterEffect(origin.getBlock()); - } else if (type == AbilityType.SHIFT) { - if (direction == null) { - direction = player.getEyeLocation().getDirection(); + playFocusWaterEffect(this.origin.getBlock()); + } else if (this.type == AbilityType.SHIFT) { + if (this.direction == null) { + this.direction = this.player.getEyeLocation().getDirection(); } - if (!charging) { - if (!containsType(player, AbilityType.SHIFT)) { - removeOldType(player, AbilityType.CLICK); - remove(); + if (!this.charging) { + if (!containsType(this.player, AbilityType.SHIFT)) { + this.removeOldType(this.player, AbilityType.CLICK); + this.remove(); return; } - charging = true; - animation = AnimateState.RISE; - location = origin.clone(); + this.charging = true; + this.animation = AnimateState.RISE; + this.location = this.origin.clone(); - if (isPlant(origin.getBlock()) || isSnow(origin.getBlock())) { - new PlantRegrowth(player, origin.getBlock()); - origin.getBlock().setType(Material.AIR); + if (isPlant(this.origin.getBlock()) || isSnow(this.origin.getBlock())) { + new PlantRegrowth(this.player, this.origin.getBlock()); + this.origin.getBlock().setType(Material.AIR); } } - removeOldType(player, AbilityType.CLICK); - if (!player.isSneaking()) { - if (System.currentTimeMillis() - time > chargeTime) { - setType(AbilityType.RELEASE); - setAnimation(AnimateState.SHRINK); + this.removeOldType(this.player, AbilityType.CLICK); + if (!this.player.isSneaking()) { + if (System.currentTimeMillis() - this.time > this.chargeTime) { + this.setType(AbilityType.RELEASE); + this.setAnimation(AnimateState.SHRINK); } else { - remove(); + this.remove(); } return; } - if (animation == AnimateState.RISE && location != null) { - revertBlocks(); - location.add(0, animationSpeed, 0); - Block block = location.getBlock(); + if (this.animation == AnimateState.RISE && this.location != null) { + this.revertBlocks(); + this.location.add(0, this.animationSpeed, 0); + final Block block = this.location.getBlock(); - if (!(isWaterbendable(block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - remove(); + if (!(this.isWaterbendable(block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { + this.remove(); return; } - createBlock(block, Material.STATIONARY_WATER); - if (location.distanceSquared(origin) > 4) { - animation = AnimateState.TOWARD_PLAYER; + this.createBlock(block, Material.STATIONARY_WATER); + if (this.location.distanceSquared(this.origin) > 4) { + this.animation = AnimateState.TOWARD_PLAYER; } - } else if (animation == AnimateState.TOWARD_PLAYER) { - revertBlocks(); - Location eyeLoc = player.getTargetBlock((HashSet) null, 2).getLocation(); - eyeLoc.setY(player.getEyeLocation().getY()); - Vector vec = GeneralMethods.getDirection(location, eyeLoc); - location.add(vec.normalize().multiply(animationSpeed)); - Block block = location.getBlock(); - - if (!(isWaterbendable(block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - remove(); + } else if (this.animation == AnimateState.TOWARD_PLAYER) { + this.revertBlocks(); + final Location eyeLoc = this.player.getTargetBlock((HashSet) null, 2).getLocation(); + eyeLoc.setY(this.player.getEyeLocation().getY()); + final Vector vec = GeneralMethods.getDirection(this.location, eyeLoc); + this.location.add(vec.normalize().multiply(this.animationSpeed)); + final Block block = this.location.getBlock(); + + if (!(this.isWaterbendable(block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { + this.remove(); return; } - createBlock(block, Material.STATIONARY_WATER); - if (location.distanceSquared(eyeLoc) < 1.7) { - animation = AnimateState.CIRCLE; - Vector tempDir = player.getLocation().getDirection(); + this.createBlock(block, Material.STATIONARY_WATER); + if (this.location.distanceSquared(eyeLoc) < 1.7) { + this.animation = AnimateState.CIRCLE; + final Vector tempDir = this.player.getLocation().getDirection(); tempDir.setY(0); - direction = tempDir.normalize(); - revertBlocks(); + this.direction = tempDir.normalize(); + this.revertBlocks(); } - } else if (animation == AnimateState.CIRCLE) { - drawCircle(120, 5); + } else if (this.animation == AnimateState.CIRCLE) { + this.drawCircle(120, 5); } - } else if (type == AbilityType.RELEASE) { - if (animation == AnimateState.SHRINK) { - radius -= 0.20; - drawCircle(360, 15); - - if (radius < 1) { - revertBlocks(); - time = System.currentTimeMillis(); - animation = null; + } else if (this.type == AbilityType.RELEASE) { + if (this.animation == AnimateState.SHRINK) { + this.radius -= 0.20; + this.drawCircle(360, 15); + + if (this.radius < 1) { + this.revertBlocks(); + this.time = System.currentTimeMillis(); + this.animation = null; } } else { - moving = true; - collidable = true; - if ((System.currentTimeMillis() - time > flightTime && !bPlayer.isAvatarState()) || player.isSneaking()) { - remove(); + this.moving = true; + this.collidable = true; + if ((System.currentTimeMillis() - this.time > this.flightTime && !this.bPlayer.isAvatarState()) || this.player.isSneaking()) { + this.remove(); return; } - player.setFallDistance(0f); - double currentSpeed = speed - (speed * (System.currentTimeMillis() - time) / flightTime); - double nightSpeed = getNightFactor(currentSpeed * 0.9); + this.player.setFallDistance(0f); + double currentSpeed = this.speed - (this.speed * (System.currentTimeMillis() - this.time) / this.flightTime); + final double nightSpeed = this.getNightFactor(currentSpeed * 0.9); currentSpeed = nightSpeed > currentSpeed ? nightSpeed : currentSpeed; - if (bPlayer.isAvatarState()) { - currentSpeed = getNightFactor(speed); + if (this.bPlayer.isAvatarState()) { + currentSpeed = this.getNightFactor(this.speed); } - player.setVelocity(player.getEyeLocation().getDirection().normalize().multiply(currentSpeed)); - for (Block block : GeneralMethods.getBlocksAroundPoint(player.getLocation().add(0, -1, 0), waveRadius)) { + this.player.setVelocity(this.player.getEyeLocation().getDirection().normalize().multiply(currentSpeed)); + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.player.getLocation().add(0, -1, 0), this.waveRadius)) { if (block.getType() == Material.AIR && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - if (iceWave) { - createBlockDelay(block, Material.ICE, (byte) 0, 2L); + if (this.iceWave) { + this.createBlockDelay(block, Material.ICE, (byte) 0, 2L); } else { - createBlock(block, Material.STATIONARY_WATER, (byte) 0); + this.createBlock(block, Material.STATIONARY_WATER, (byte) 0); } } } - revertBlocksDelay(20L); - - if (iceWave && progressCounter % 3 == 0) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation().add(0, -1, 0), waveRadius * 1.5)) { - if (entity != this.player && entity instanceof LivingEntity && !affectedEntities.contains(entity)) { - affectedEntities.add(entity); - final double augment = getNightFactor(player.getWorld()); - DamageHandler.damageEntity(entity, damage, CoreAbility.getAbility(player, IceWave.class)); + this.revertBlocksDelay(20L); + + if (this.iceWave && this.progressCounter % 3 == 0) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.player.getLocation().add(0, -1, 0), this.waveRadius * 1.5)) { + if (entity != this.player && entity instanceof LivingEntity && !this.affectedEntities.contains(entity)) { + this.affectedEntities.add(entity); + final double augment = getNightFactor(this.player.getWorld()); + DamageHandler.damageEntity(entity, this.damage, CoreAbility.getAbility(this.player, IceWave.class)); final Player fplayer = this.player; final Entity fent = entity; new BukkitRunnable() { @Override public void run() { - createIceSphere(fplayer, fent, augment * 2.5); + WaterSpoutWave.this.createIceSphere(fplayer, fent, augment * 2.5); } }.runTaskLater(ProjectKorra.plugin, 6); } } - for (Block block : FROZEN_BLOCKS.keySet()) { - TempBlock tBlock = FROZEN_BLOCKS.get(block); - if (tBlock.getBlock().getWorld().equals(player.getWorld()) && tBlock.getLocation().distance(player.getLocation()) >= thawRadius) { + for (final Block block : FROZEN_BLOCKS.keySet()) { + final TempBlock tBlock = FROZEN_BLOCKS.get(block); + if (tBlock.getBlock().getWorld().equals(this.player.getWorld()) && tBlock.getLocation().distance(this.player.getLocation()) >= this.thawRadius) { tBlock.revertBlock(); FROZEN_BLOCKS.remove(block); } @@ -317,17 +317,17 @@ public void run() { } } - public void drawCircle(double theta, double increment) { - double rotateSpeed = 45; - revertBlocks(); - direction = GeneralMethods.rotateXZ(direction, rotateSpeed); + public void drawCircle(final double theta, final double increment) { + final double rotateSpeed = 45; + this.revertBlocks(); + this.direction = GeneralMethods.rotateXZ(this.direction, rotateSpeed); for (double i = 0; i < theta; i += increment) { - Vector dir = GeneralMethods.rotateXZ(direction, i - theta / 2).normalize().multiply(radius); + final Vector dir = GeneralMethods.rotateXZ(this.direction, i - theta / 2).normalize().multiply(this.radius); dir.setY(0); - Block block = player.getEyeLocation().add(dir).getBlock(); - location = block.getLocation(); + final Block block = this.player.getEyeLocation().add(dir).getBlock(); + this.location = block.getLocation(); if (block.getType() == Material.AIR && !GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { - createBlock(block, Material.STATIONARY_WATER, (byte) 8); + this.createBlock(block, Material.STATIONARY_WATER, (byte) 8); } } } @@ -335,49 +335,49 @@ public void drawCircle(double theta, double increment) { @Override public void remove() { super.remove(); - if (moving) { - bPlayer.addCooldown(this); + if (this.moving) { + this.bPlayer.addCooldown(this); } - revertBlocks(); - for (BukkitRunnable task : tasks) { + this.revertBlocks(); + for (final BukkitRunnable task : this.tasks) { task.cancel(); } } - public void createBlockDelay(final Block block, final Material mat, final byte data, long delay) { - BukkitRunnable br = new BukkitRunnable() { + public void createBlockDelay(final Block block, final Material mat, final byte data, final long delay) { + final BukkitRunnable br = new BukkitRunnable() { @Override public void run() { - createBlock(block, mat, data); + WaterSpoutWave.this.createBlock(block, mat, data); } }; br.runTaskLater(ProjectKorra.plugin, delay); - tasks.add(br); + this.tasks.add(br); } - public void createBlock(Block block, Material mat) { - createBlock(block, mat, (byte) 0); + public void createBlock(final Block block, final Material mat) { + this.createBlock(block, mat, (byte) 0); } - public void createBlock(Block block, Material mat, byte data) { - affectedBlocks.put(block, new TempBlock(block, mat, data)); + public void createBlock(final Block block, final Material mat, final byte data) { + this.affectedBlocks.put(block, new TempBlock(block, mat, data)); } public void revertBlocks() { - Enumeration keys = affectedBlocks.keys(); + final Enumeration keys = this.affectedBlocks.keys(); while (keys.hasMoreElements()) { - Block block = keys.nextElement(); - affectedBlocks.get(block).revertBlock(); - affectedBlocks.remove(block); + final Block block = keys.nextElement(); + this.affectedBlocks.get(block).revertBlock(); + this.affectedBlocks.remove(block); } } - public void revertBlocksDelay(long delay) { - Enumeration keys = affectedBlocks.keys(); + public void revertBlocksDelay(final long delay) { + final Enumeration keys = this.affectedBlocks.keys(); while (keys.hasMoreElements()) { final Block block = keys.nextElement(); - final TempBlock tblock = affectedBlocks.get(block); - affectedBlocks.remove(block); + final TempBlock tblock = this.affectedBlocks.get(block); + this.affectedBlocks.remove(block); new BukkitRunnable() { @Override @@ -390,21 +390,21 @@ public void run() { } } - public void createIceSphere(Player player, Entity entity, double radius) { + public void createIceSphere(final Player player, final Entity entity, final double radius) { for (double x = -radius; x <= radius; x += 0.5) { for (double y = -radius; y <= radius; y += 0.5) { for (double z = -radius; z <= radius; z += 0.5) { - Block block = entity.getLocation().getBlock().getLocation().add(x, y, z).getBlock(); + final Block block = entity.getLocation().getBlock().getLocation().add(x, y, z).getBlock(); if (block.getLocation().distanceSquared(entity.getLocation().getBlock().getLocation()) > radius * radius) { continue; } - if (block.getType() == Material.AIR || block.getType() == Material.ICE || isWaterbendable(block)) { + if (block.getType() == Material.AIR || block.getType() == Material.ICE || this.isWaterbendable(block)) { if (!FROZEN_BLOCKS.containsKey(block)) { - TempBlock tblock = new TempBlock(block, Material.ICE, (byte) 1); + final TempBlock tblock = new TempBlock(block, Material.ICE, (byte) 1); FROZEN_BLOCKS.put(block, tblock); - if (revertIceSphere) { - tblock.setRevertTime(revertSphereTime + (new Random().nextInt(1000) - 500)); + if (this.revertIceSphere) { + tblock.setRevertTime(this.revertSphereTime + (new Random().nextInt(1000) - 500)); } } } @@ -413,8 +413,8 @@ public void createIceSphere(Player player, Entity entity, double radius) { } } - public static boolean containsType(Player player, AbilityType type) { - for (WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { + public static boolean containsType(final Player player, final AbilityType type) { + for (final WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { if (wave.type.equals(type)) { return true; } @@ -422,17 +422,17 @@ public static boolean containsType(Player player, AbilityType type) { return false; } - public void removeOldType(Player player, AbilityType type) { - for (WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { + public void removeOldType(final Player player, final AbilityType type) { + for (final WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { if (wave.type.equals(type) && !wave.equals(this)) { wave.remove(); } } } - public static ArrayList getType(Player player, AbilityType type) { - ArrayList list = new ArrayList(); - for (WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { + public static ArrayList getType(final Player player, final AbilityType type) { + final ArrayList list = new ArrayList(); + for (final WaterSpoutWave wave : getAbilities(player, WaterSpoutWave.class)) { if (wave.type.equals(type)) { list.add(wave); } @@ -440,10 +440,10 @@ public static ArrayList getType(Player player, AbilityType type) return list; } - public static boolean wasBrokenFor(Player player, Block block) { - ArrayList waves = getType(player, AbilityType.CLICK); + public static boolean wasBrokenFor(final Player player, final Block block) { + final ArrayList waves = getType(player, AbilityType.CLICK); if (!waves.isEmpty()) { - WaterSpoutWave wave = waves.get(0); + final WaterSpoutWave wave = waves.get(0); if (wave.origin == null) { return false; } else if (wave.origin.getBlock().equals(block)) { @@ -452,14 +452,14 @@ public static boolean wasBrokenFor(Player player, Block block) { } return false; } - + public static void progressAllCleanup() { - for (Block block : FROZEN_BLOCKS.keySet()) { - TempBlock tb = FROZEN_BLOCKS.get(block); + for (final Block block : FROZEN_BLOCKS.keySet()) { + final TempBlock tb = FROZEN_BLOCKS.get(block); if (block.getType() != Material.ICE) { FROZEN_BLOCKS.remove(block); continue; - } + } if (tb == null || !TempBlock.isTempBlock(block)) { FROZEN_BLOCKS.remove(block); continue; @@ -467,11 +467,11 @@ public static void progressAllCleanup() { } } - public static boolean canThaw(Block block) { + public static boolean canThaw(final Block block) { return FROZEN_BLOCKS.containsKey(block); } - public static void thaw(Block block) { + public static void thaw(final Block block) { if (FROZEN_BLOCKS.containsKey(block)) { FROZEN_BLOCKS.get(block).revertBlock(); FROZEN_BLOCKS.remove(block); @@ -480,10 +480,10 @@ public static void thaw(Block block) { @Override public Location getLocation() { - if (location != null) { - return location; + if (this.location != null) { + return this.location; } else { - return origin; + return this.origin; } } @@ -499,7 +499,7 @@ public Element getElement() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -514,159 +514,160 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return collidable; + return this.collidable; } @Override public double getCollisionRadius() { - return getRadius(); + return this.getRadius(); } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public boolean isCharging() { - return charging; + return this.charging; } - public void setCharging(boolean charging) { + public void setCharging(final boolean charging) { this.charging = charging; } public boolean isIceWave() { - return iceWave; + return this.iceWave; } - public void setIceWave(boolean iceWave) { + public void setIceWave(final boolean iceWave) { this.iceWave = iceWave; } public boolean isIceOnly() { - return iceOnly; + return this.iceOnly; } - public void setIceOnly(boolean iceOnly) { + public void setIceOnly(final boolean iceOnly) { this.iceOnly = iceOnly; } + @Override public boolean isEnabled() { return getConfig().getBoolean("Abilities.Water.WaterSpout.Wave.Enabled"); } public boolean isMoving() { - return moving; + return this.moving; } - public void setMoving(boolean moving) { + public void setMoving(final boolean moving) { this.moving = moving; } public int getProgressCounter() { - return progressCounter; + return this.progressCounter; } - public void setProgressCounter(int progressCounter) { + public void setProgressCounter(final int progressCounter) { this.progressCounter = progressCounter; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getSelectRange() { - return selectRange; + return this.selectRange; } - public void setSelectRange(double selectRange) { + public void setSelectRange(final double selectRange) { this.selectRange = selectRange; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getChargeTime() { - return chargeTime; + return this.chargeTime; } - public void setChargeTime(double chargeTime) { + public void setChargeTime(final double chargeTime) { this.chargeTime = chargeTime; } public double getFlightTime() { - return flightTime; + return this.flightTime; } - public void setFlightTime(double flightTime) { + public void setFlightTime(final double flightTime) { this.flightTime = flightTime; } public double getWaveRadius() { - return waveRadius; + return this.waveRadius; } - public void setWaveRadius(double waveRadius) { + public void setWaveRadius(final double waveRadius) { this.waveRadius = waveRadius; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getAnimationSpeed() { - return animationSpeed; + return this.animationSpeed; } - public void setAnimationSpeed(double animationSpeed) { + public void setAnimationSpeed(final double animationSpeed) { this.animationSpeed = animationSpeed; } public AbilityType getType() { - return type; + return this.type; } - public void setType(AbilityType type) { + public void setType(final AbilityType type) { this.type = type; } public AnimateState getAnimation() { - return animation; + return this.animation; } - public void setAnimation(AnimateState animation) { + public void setAnimation(final AnimateState animation) { this.animation = animation; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } @@ -675,27 +676,27 @@ public static Map getFrozenBlocks() { } public ArrayList getAffectedEntities() { - return affectedEntities; + return this.affectedEntities; } public ArrayList getTasks() { - return tasks; + return this.tasks; } public ConcurrentHashMap getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - + @Override public boolean allowBreakPlants() { return false; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/blood/Bloodbending.java b/src/com/projectkorra/projectkorra/waterbending/blood/Bloodbending.java index c546f2013..fd66986ec 100644 --- a/src/com/projectkorra/projectkorra/waterbending/blood/Bloodbending.java +++ b/src/com/projectkorra/projectkorra/waterbending/blood/Bloodbending.java @@ -1,6 +1,7 @@ package com.projectkorra.projectkorra.waterbending.blood; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -40,10 +41,10 @@ public class Bloodbending extends BloodAbility { private Entity target; private Vector vector; - public Bloodbending(Player player) { + public Bloodbending(final Player player) { super(player); - Bloodbending ability = getAbility(player, Bloodbending.class); + final Bloodbending ability = getAbility(player, Bloodbending.class); if (ability != null) { ability.remove(); return; @@ -57,24 +58,24 @@ public Bloodbending(Player player) { this.holdTime = getConfig().getInt("Abilities.Water.Bloodbending.HoldTime"); this.cooldown = getConfig().getInt("Abilities.Water.Bloodbending.Cooldown"); this.throwFactor = getConfig().getDouble("Abilities.Water.Bloodbending.ThrowFactor"); - vector = new Vector(0, 0, 0); + this.vector = new Vector(0, 0, 0); - if (canOnlyBeUsedAtNight && !isNight(player.getWorld()) && !bPlayer.canBloodbendAtAnytime()) { + if (this.canOnlyBeUsedAtNight && !isNight(player.getWorld()) && !this.bPlayer.canBloodbendAtAnytime()) { return; - } else if (onlyUsableDuringMoon && !isFullMoon(player.getWorld()) && !bPlayer.canBloodbendAtAnytime()) { + } else if (this.onlyUsableDuringMoon && !isFullMoon(player.getWorld()) && !this.bPlayer.canBloodbendAtAnytime()) { return; - } else if (!bPlayer.canBend(this) && !bPlayer.isAvatarState()) { + } else if (!this.bPlayer.canBend(this) && !this.bPlayer.isAvatarState()) { return; } - range = (int) getNightFactor(range, player.getWorld()); - if (bPlayer.isAvatarState()) { - range += AvatarState.getValue(1.5); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), range)) { + this.range = (int) getNightFactor(this.range, player.getWorld()); + if (this.bPlayer.isAvatarState()) { + this.range += AvatarState.getValue(1.5); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), this.range)) { if (entity instanceof LivingEntity) { if (entity instanceof Player) { - Player enemyPlayer = (Player) entity; - BendingPlayer enemyBPlayer = BendingPlayer.getBendingPlayer(enemyPlayer); + final Player enemyPlayer = (Player) entity; + final BendingPlayer enemyBPlayer = BendingPlayer.getBendingPlayer(enemyPlayer); if (enemyBPlayer == null || GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation()) || enemyBPlayer.isAvatarState() || entity.getEntityId() == player.getEntityId() || enemyBPlayer.canBendIgnoreBindsCooldowns(this)) { continue; } @@ -85,17 +86,16 @@ public Bloodbending(Player player) { } } } else { - //Location location = GeneralMethods.getTargetedLocation(player, 6, getTransparentMaterial()); - //List entities = GeneralMethods.getEntitiesAroundPoint(location, 1.5); List entities = new CopyOnWriteArrayList(); - for (int i = 0; i < range; i++) { - Location location = GeneralMethods.getTargetedLocation(player, i, getTransparentMaterials()); + for (int i = 0; i < this.range; i++) { + final Location location = GeneralMethods.getTargetedLocation(player, i, getTransparentMaterials()); entities = GeneralMethods.getEntitiesAroundPoint(location, 1.7); - if (entities.contains(player)) + if (entities.contains(player)) { entities.remove(player); - for (Entity e : entities) { - if (!(e instanceof LivingEntity)) { - entities.remove(e); + } + for (final Iterator iterator = entities.iterator(); iterator.hasNext();) { + if (!(iterator.next() instanceof LivingEntity)) { + iterator.remove(); } } if (entities != null && !entities.isEmpty() && !entities.contains(player)) { @@ -105,102 +105,102 @@ public Bloodbending(Player player) { if (entities == null || entities.isEmpty()) { return; } - target = entities.get(0); + this.target = entities.get(0); - if (target == null || !(target instanceof LivingEntity) || GeneralMethods.isRegionProtectedFromBuild(this, target.getLocation()) || target.getEntityId() == player.getEntityId()) { + if (this.target == null || !(this.target instanceof LivingEntity) || GeneralMethods.isRegionProtectedFromBuild(this, this.target.getLocation()) || this.target.getEntityId() == player.getEntityId()) { return; - } else if (target instanceof Player) { - BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) target); + } else if (this.target instanceof Player) { + final BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) this.target); if (targetBPlayer != null) { - if (targetBPlayer.canBloodbend() && !canBloodbendOtherBloodbenders) { + if (targetBPlayer.canBloodbend() && !this.canBloodbendOtherBloodbenders) { return; } else if (targetBPlayer.isAvatarState()) { return; - } else if (targetBPlayer.canBloodbendAtAnytime() && !canBloodbendOtherBloodbenders) { + } else if (targetBPlayer.canBloodbendAtAnytime() && !this.canBloodbendOtherBloodbenders) { return; } } - } else if (!canBeUsedOnUndeadMobs && isUndead(target)) { + } else if (!this.canBeUsedOnUndeadMobs && isUndead(this.target)) { return; } - DamageHandler.damageEntity(target, 0, this); - HorizontalVelocityTracker.remove(target); - AirAbility.breakBreathbendingHold(target); - TARGETED_ENTITIES.put(target, player); + DamageHandler.damageEntity(this.target, 0, this); + HorizontalVelocityTracker.remove(this.target); + AirAbility.breakBreathbendingHold(this.target); + TARGETED_ENTITIES.put(this.target, player); } this.time = System.currentTimeMillis(); - start(); + this.start(); } - public static void launch(Player player) { - Bloodbending bloodbending = getAbility(player, Bloodbending.class); + public static void launch(final Player player) { + final Bloodbending bloodbending = getAbility(player, Bloodbending.class); if (bloodbending != null) { bloodbending.launch(); } } private void launch() { - Location location = player.getLocation(); - for (Entity entity : TARGETED_ENTITIES.keySet()) { - Location target = entity.getLocation().clone(); + final Location location = this.player.getLocation(); + for (final Entity entity : TARGETED_ENTITIES.keySet()) { + final Location target = entity.getLocation().clone(); Vector vector = new Vector(0, 0, 0); if (location.getWorld().equals(target.getWorld())) { - vector = GeneralMethods.getDirection(location, GeneralMethods.getTargetedLocation(player, location.distance(target))); + vector = GeneralMethods.getDirection(location, GeneralMethods.getTargetedLocation(this.player, location.distance(target))); } vector.normalize(); - entity.setVelocity(vector.multiply(throwFactor)); - new HorizontalVelocityTracker(entity, player, 200, this); + entity.setVelocity(vector.multiply(this.throwFactor)); + new HorizontalVelocityTracker(entity, this.player, 200, this); } - remove(); - bPlayer.addCooldown(this); + this.remove(); + this.bPlayer.addCooldown(this); } @Override public void progress() { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 60, 1); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 60, 1); - if (!player.isSneaking()) { - remove(); + if (!this.player.isSneaking()) { + this.remove(); return; - } else if (holdTime > 0 && System.currentTimeMillis() - this.time > holdTime) { - remove(); - bPlayer.addCooldown(this); + } else if (this.holdTime > 0 && System.currentTimeMillis() - this.time > this.holdTime) { + this.remove(); + this.bPlayer.addCooldown(this); return; } - if (!canBeUsedOnUndeadMobs) { - for (Entity entity : TARGETED_ENTITIES.keySet()) { + if (!this.canBeUsedOnUndeadMobs) { + for (final Entity entity : TARGETED_ENTITIES.keySet()) { if (isUndead(entity)) { TARGETED_ENTITIES.remove(entity); } } } - if (onlyUsableDuringMoon && !isFullMoon(player.getWorld()) && !bPlayer.canBloodbendAtAnytime()) { - remove(); + if (this.onlyUsableDuringMoon && !isFullMoon(this.player.getWorld()) && !this.bPlayer.canBloodbendAtAnytime()) { + this.remove(); return; - } else if (canOnlyBeUsedAtNight && !isNight(player.getWorld()) && !bPlayer.canBloodbendAtAnytime()) { - remove(); + } else if (this.canOnlyBeUsedAtNight && !isNight(this.player.getWorld()) && !this.bPlayer.canBloodbendAtAnytime()) { + this.remove(); return; - } else if (!bPlayer.canBendIgnoreCooldowns(this)) { - remove(); + } else if (!this.bPlayer.canBendIgnoreCooldowns(this)) { + this.remove(); return; } - if (bPlayer.isAvatarState()) { - ArrayList entities = new ArrayList<>(); + if (this.bPlayer.isAvatarState()) { + final ArrayList entities = new ArrayList<>(); - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), range)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.player.getLocation(), this.range)) { if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } else if (!(entity instanceof LivingEntity)) { continue; } else if (entity instanceof Player) { - BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); + final BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); if (targetBPlayer != null) { - if (!targetBPlayer.canBeBloodbent() || entity.getEntityId() == player.getEntityId()) { + if (!targetBPlayer.canBeBloodbent() || entity.getEntityId() == this.player.getEntityId()) { continue; } } @@ -209,15 +209,15 @@ public void progress() { entities.add(entity); if (!TARGETED_ENTITIES.containsKey(entity) && entity instanceof LivingEntity) { DamageHandler.damageEntity(entity, 0, this); - TARGETED_ENTITIES.put(entity, player); + TARGETED_ENTITIES.put(entity, this.player); } - if (player.getWorld() != entity.getLocation().getWorld()) { + if (this.player.getWorld() != entity.getLocation().getWorld()) { TARGETED_ENTITIES.remove(entity); continue; } if (entity instanceof LivingEntity) { - entity.setVelocity(vector); + entity.setVelocity(this.vector); new TempPotionEffect((LivingEntity) entity, effect); entity.setFallDistance(0); if (entity instanceof Creature) { @@ -227,15 +227,15 @@ public void progress() { } } - for (Entity entity : TARGETED_ENTITIES.keySet()) { - if (!entities.contains(entity) && TARGETED_ENTITIES.get(entity) == player) { + for (final Entity entity : TARGETED_ENTITIES.keySet()) { + if (!entities.contains(entity) && TARGETED_ENTITIES.get(entity) == this.player) { TARGETED_ENTITIES.remove(entity); } } } else { - for (Entity entity : TARGETED_ENTITIES.keySet()) { + for (final Entity entity : TARGETED_ENTITIES.keySet()) { if (entity instanceof Player) { - BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); + final BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); if (targetBPlayer != null && !targetBPlayer.canBeBloodbent()) { TARGETED_ENTITIES.remove(entity); continue; @@ -245,59 +245,59 @@ public void progress() { } } - Location newLocation = entity.getLocation(); - if (player.getWorld() != newLocation.getWorld()) { + final Location newLocation = entity.getLocation(); + if (this.player.getWorld() != newLocation.getWorld()) { TARGETED_ENTITIES.remove(entity); continue; } } - - if (!TARGETED_ENTITIES.containsKey(target)) { - remove(); + + if (!TARGETED_ENTITIES.containsKey(this.target)) { + this.remove(); return; } - - if (TARGETED_ENTITIES.get(target) != player) { - remove(); + + if (TARGETED_ENTITIES.get(this.target) != this.player) { + this.remove(); return; } - Location location = GeneralMethods.getTargetedLocation(player, 6, getTransparentMaterials()); + final Location location = GeneralMethods.getTargetedLocation(this.player, 6, getTransparentMaterials()); double distance = 0; - if (location.getWorld().equals(target.getWorld())) { - distance = location.distance(target.getLocation()); + if (location.getWorld().equals(this.target.getWorld())) { + distance = location.distance(this.target.getLocation()); } double dx, dy, dz; - dx = location.getX() - target.getLocation().getX(); - dy = location.getY() - target.getLocation().getY(); - dz = location.getZ() - target.getLocation().getZ(); - vector = new Vector(dx, dy, dz); - vector.normalize().multiply(.5); + dx = location.getX() - this.target.getLocation().getX(); + dy = location.getY() - this.target.getLocation().getY(); + dz = location.getZ() - this.target.getLocation().getZ(); + this.vector = new Vector(dx, dy, dz); + this.vector.normalize().multiply(.5); if (distance < .6) { - vector = new Vector(0, 0, 0); + this.vector = new Vector(0, 0, 0); } - - target.setVelocity(vector); - new TempPotionEffect((LivingEntity) target, effect); - target.setFallDistance(0); - if (target instanceof Creature) { - ((Creature) target).setTarget(null); + this.target.setVelocity(this.vector); + + new TempPotionEffect((LivingEntity) this.target, effect); + this.target.setFallDistance(0); + if (this.target instanceof Creature) { + ((Creature) this.target).setTarget(null); } - AirAbility.breakBreathbendingHold(target); + AirAbility.breakBreathbendingHold(this.target); } } @Override public void remove() { - if (!bPlayer.isAvatarState() && target != null) { - if (System.currentTimeMillis() < getStartTime() + 1200) { - bPlayer.addCooldown(this); //Prevents spamming + if (!this.bPlayer.isAvatarState() && this.target != null) { + if (System.currentTimeMillis() < this.getStartTime() + 1200) { + this.bPlayer.addCooldown(this); // Prevents spamming. } } - for (Entity e : TARGETED_ENTITIES.keySet()) { - if (TARGETED_ENTITIES.get(e) == player) { + for (final Entity e : TARGETED_ENTITIES.keySet()) { + if (TARGETED_ENTITIES.get(e) == this.player) { TARGETED_ENTITIES.remove(e); } } @@ -305,29 +305,29 @@ public void remove() { super.remove(); } - public static boolean isBloodbent(Entity entity) { + public static boolean isBloodbent(final Entity entity) { return entity != null ? TARGETED_ENTITIES.containsKey(entity) : null; } - public static Location getBloodbendingLocation(Entity entity) { + public static Location getBloodbendingLocation(final Entity entity) { return entity != null ? TARGETED_ENTITIES.get(entity).getLocation() : null; } - - public static Vector getBloodbendingVector(Entity entity) { + + public static Vector getBloodbendingVector(final Entity entity) { if (!TARGETED_ENTITIES.containsKey(entity)) { return null; } - - Bloodbending bb = getAbility(TARGETED_ENTITIES.get(entity), Bloodbending.class); + + final Bloodbending bb = getAbility(TARGETED_ENTITIES.get(entity), Bloodbending.class); return bb.vector; } - - public static BendingPlayer getBloodbender(Entity entity) { + + public static BendingPlayer getBloodbender(final Entity entity) { if (!TARGETED_ENTITIES.containsKey(entity)) { return null; } - - Bloodbending bb = getAbility(TARGETED_ENTITIES.get(entity), Bloodbending.class); + + final Bloodbending bb = getAbility(TARGETED_ENTITIES.get(entity), Bloodbending.class); return bb.getBendingPlayer(); } @@ -338,15 +338,15 @@ public String getName() { @Override public Location getLocation() { - if (target != null) { - return target.getLocation(); + if (this.target != null) { + return this.target.getLocation(); } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -361,83 +361,83 @@ public boolean isHarmlessAbility() { @Override public List getLocations() { - // for collision purposes we only care about the player's location - ArrayList locations = new ArrayList<>(); - if (player != null) { - locations.add(player.getLocation()); + // for collision purposes we only care about the player's location. + final ArrayList locations = new ArrayList<>(); + if (this.player != null) { + locations.add(this.player.getLocation()); } return locations; } public boolean isCanOnlyBeUsedAtNight() { - return canOnlyBeUsedAtNight; + return this.canOnlyBeUsedAtNight; } - public void setCanOnlyBeUsedAtNight(boolean canOnlyBeUsedAtNight) { + public void setCanOnlyBeUsedAtNight(final boolean canOnlyBeUsedAtNight) { this.canOnlyBeUsedAtNight = canOnlyBeUsedAtNight; } public boolean isCanBeUsedOnUndeadMobs() { - return canBeUsedOnUndeadMobs; + return this.canBeUsedOnUndeadMobs; } - public void setCanBeUsedOnUndeadMobs(boolean canBeUsedOnUndeadMobs) { + public void setCanBeUsedOnUndeadMobs(final boolean canBeUsedOnUndeadMobs) { this.canBeUsedOnUndeadMobs = canBeUsedOnUndeadMobs; } public boolean isOnlyUsableDuringMoon() { - return onlyUsableDuringMoon; + return this.onlyUsableDuringMoon; } - public void setOnlyUsableDuringMoon(boolean onlyUsableDuringMoon) { + public void setOnlyUsableDuringMoon(final boolean onlyUsableDuringMoon) { this.onlyUsableDuringMoon = onlyUsableDuringMoon; } public boolean isCanBloodbendOtherBloodbenders() { - return canBloodbendOtherBloodbenders; + return this.canBloodbendOtherBloodbenders; } - public void setCanBloodbendOtherBloodbenders(boolean canBloodbendOtherBloodbenders) { + public void setCanBloodbendOtherBloodbenders(final boolean canBloodbendOtherBloodbenders) { this.canBloodbendOtherBloodbenders = canBloodbendOtherBloodbenders; } public int getRange() { - return range; + return this.range; } - public void setRange(int range) { + public void setRange(final int range) { this.range = range; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getHoldTime() { - return holdTime; + return this.holdTime; } - public void setHoldTime(long holdTime) { + public void setHoldTime(final long holdTime) { this.holdTime = holdTime; } public double getThrowFactor() { - return throwFactor; + return this.throwFactor; } - public void setThrowFactor(double throwFactor) { + public void setThrowFactor(final double throwFactor) { this.throwFactor = throwFactor; } public Entity getTarget() { - return target; + return this.target; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } diff --git a/src/com/projectkorra/projectkorra/waterbending/combo/IceBullet.java b/src/com/projectkorra/projectkorra/waterbending/combo/IceBullet.java index e1e72a759..a219266f6 100644 --- a/src/com/projectkorra/projectkorra/waterbending/combo/IceBullet.java +++ b/src/com/projectkorra/projectkorra/waterbending/combo/IceBullet.java @@ -37,7 +37,7 @@ public class IceBullet extends IceAbility implements ComboAbility { public static enum AbilityState { ICE_PILLAR_RISING, ICE_BULLET_FORMING } - + private int leftClicks; private int rightClicks; private double damage; @@ -58,18 +58,18 @@ public static enum AbilityState { private WaterSourceGrabber waterGrabber; private ArrayList tasks; private ConcurrentHashMap affectedBlocks; - - public IceBullet(Player player) { + + public IceBullet(final Player player) { super(player); - + this.time = System.currentTimeMillis(); this.tasks = new ArrayList<>(); this.affectedBlocks = new ConcurrentHashMap<>(); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - + this.damage = getConfig().getDouble("Abilities.Water.IceBullet.Damage"); this.range = getConfig().getDouble("Abilities.Water.IceBullet.Range"); this.radius = getConfig().getDouble("Abilities.Water.IceBullet.Radius"); @@ -78,8 +78,8 @@ public IceBullet(Player player) { this.maxShots = getConfig().getInt("Abilities.Water.IceBullet.MaxShots"); this.animationSpeed = getConfig().getDouble("Abilities.Water.IceBullet.AnimationSpeed"); this.speed = 1; - this.name = getName(); - + this.name = this.getName(); + double aug = getNightFactor(player.getWorld()); if (aug > 1) { aug = 1 + (aug - 1) / 3; @@ -91,15 +91,15 @@ public IceBullet(Player player) { this.maxShots *= aug; this.radius *= aug; - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; - this.damage = AvatarState.getValue(damage); - this.range = AvatarState.getValue(range); - this.shootTime = AvatarState.getValue(shootTime); - this.maxShots = AvatarState.getValue(maxShots); + this.damage = AvatarState.getValue(this.damage); + this.range = AvatarState.getValue(this.range); + this.shootTime = AvatarState.getValue(this.shootTime); + this.maxShots = AvatarState.getValue(this.maxShots); } - start(); + this.start(); } @Override @@ -113,16 +113,15 @@ public boolean isCollidable() { } @Override - public void handleCollision(Collision collision) { + public void handleCollision(final Collision collision) { if (collision.isRemovingFirst()) { - ArrayList newTasks = new ArrayList<>(); - double collisionDistanceSquared = Math.pow(getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); + final ArrayList newTasks = new ArrayList<>(); + final double collisionDistanceSquared = Math.pow(this.getCollisionRadius() + collision.getAbilitySecond().getCollisionRadius(), 2); // Remove all of the streams that are by this specific ourLocation. - // Don't just do a single stream at a time or this algorithm becomes O(n^2) with - // Collision's detection algorithm. - for (BukkitRunnable task : getTasks()) { + // Don't just do a single stream at a time or this algorithm becomes O(n^2) with Collision's detection algorithm. + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; if (stream.getLocation().distanceSquared(collision.getLocationSecond()) > collisionDistanceSquared) { newTasks.add(stream); } else { @@ -132,16 +131,16 @@ public void handleCollision(Collision collision) { newTasks.add(task); } } - setTasks(newTasks); + this.setTasks(newTasks); } } @Override public List getLocations() { - ArrayList locations = new ArrayList<>(); - for (BukkitRunnable task : getTasks()) { + final ArrayList locations = new ArrayList<>(); + for (final BukkitRunnable task : this.getTasks()) { if (task instanceof FireComboStream) { - FireComboStream stream = (FireComboStream) task; + final FireComboStream stream = (FireComboStream) task; locations.add(stream.getLocation()); } } @@ -150,9 +149,9 @@ public List getLocations() { public static class IceBulletLeftClick extends IceBullet { - public IceBulletLeftClick(Player player) { + public IceBulletLeftClick(final Player player) { super(player); - setName("IceBulletLeftClick"); + this.setName("IceBulletLeftClick"); } @Override @@ -164,9 +163,9 @@ public String getName() { public static class IceBulletRightClick extends IceBullet { - public IceBulletRightClick(Player player) { + public IceBulletRightClick(final Player player) { super(player); - setName("IceBulletRightClick"); + this.setName("IceBulletRightClick"); } @Override @@ -177,32 +176,32 @@ public String getName() { } public void manageShots() { - for (int i = 0; i < tasks.size(); i++) { - if (((FireComboStream) tasks.get(i)).isCancelled()) { - tasks.remove(i); + for (int i = 0; i < this.tasks.size(); i++) { + if (((FireComboStream) this.tasks.get(i)).isCancelled()) { + this.tasks.remove(i); i--; } } - for (int i = 0; i < tasks.size(); i++) { - FireComboStream fstream = (FireComboStream) tasks.get(i); - Location loc = fstream.getLocation(); + for (int i = 0; i < this.tasks.size(); i++) { + final FireComboStream fstream = (FireComboStream) this.tasks.get(i); + final Location loc = fstream.getLocation(); - if (!isTransparent(player, loc.clone().add(0, 0.2, 0).getBlock())) { + if (!isTransparent(this.player, loc.clone().add(0, 0.2, 0).getBlock())) { fstream.remove(); return; } if (i % 2 == 0) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 1.5)) { - if (GeneralMethods.isRegionProtectedFromBuild(player, "WaterManipulation", entity.getLocation())) { - remove(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(loc, 1.5)) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, "WaterManipulation", entity.getLocation())) { + this.remove(); return; } - if (!entity.equals(player)) { - if (damage != 0) { + if (!entity.equals(this.player)) { + if (this.damage != 0) { if (entity instanceof LivingEntity) { - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } } } @@ -210,54 +209,54 @@ public void manageShots() { } } } - - public void createBlock(Block block, Material mat) { - createBlock(block, mat, (byte) 0); + + public void createBlock(final Block block, final Material mat) { + this.createBlock(block, mat, (byte) 0); } - public void createBlock(Block block, Material mat, byte data) { - affectedBlocks.put(block, new TempBlock(block, mat, data)); + public void createBlock(final Block block, final Material mat, final byte data) { + this.affectedBlocks.put(block, new TempBlock(block, mat, data)); } - - public void drawWaterCircle(Location loc, double theta, double increment, double radius) { - drawWaterCircle(loc, theta, increment, radius, Material.STATIONARY_WATER, (byte) 0); + + public void drawWaterCircle(final Location loc, final double theta, final double increment, final double radius) { + this.drawWaterCircle(loc, theta, increment, radius, Material.STATIONARY_WATER, (byte) 0); } - public void drawWaterCircle(Location loc, double theta, double increment, double radius, Material mat, byte data) { - double rotateSpeed = theta; - direction = GeneralMethods.rotateXZ(direction, rotateSpeed); + public void drawWaterCircle(final Location loc, final double theta, final double increment, final double radius, final Material mat, final byte data) { + final double rotateSpeed = theta; + this.direction = GeneralMethods.rotateXZ(this.direction, rotateSpeed); for (double i = 0; i < theta; i += increment) { - Vector dir = GeneralMethods.rotateXZ(direction, i - theta / 2).normalize().multiply(radius); + final Vector dir = GeneralMethods.rotateXZ(this.direction, i - theta / 2).normalize().multiply(radius); dir.setY(0); - Block block = loc.clone().add(dir).getBlock(); - location = block.getLocation(); + final Block block = loc.clone().add(dir).getBlock(); + this.location = block.getLocation(); - if (block.getType() == Material.AIR && !GeneralMethods.isRegionProtectedFromBuild(player, "WaterManipulation", block.getLocation())) { - createBlock(block, mat, data); + if (block.getType() == Material.AIR && !GeneralMethods.isRegionProtectedFromBuild(this.player, "WaterManipulation", block.getLocation())) { + this.createBlock(block, mat, data); } } } - + @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } - - if (shots > maxShots || !player.isSneaking()) { - remove(); + } + + if (this.shots > this.maxShots || !this.player.isSneaking()) { + this.remove(); return; } - - if (name.equalsIgnoreCase("IceBulletLeftClick") || name.equalsIgnoreCase("IceBulletRightClick")) { - Collection bullets = CoreAbility.getAbilities(player, IceBullet.class); + + if (this.name.equalsIgnoreCase("IceBulletLeftClick") || this.name.equalsIgnoreCase("IceBulletRightClick")) { + final Collection bullets = CoreAbility.getAbilities(this.player, IceBullet.class); if (bullets.size() == 0) { return; } - for (IceBullet bullet : bullets) { - if (name.equalsIgnoreCase("IceBulletLeftClick")) { + for (final IceBullet bullet : bullets) { + if (this.name.equalsIgnoreCase("IceBulletLeftClick")) { if (bullet.leftClicks <= bullet.rightClicks) { bullet.leftClicks += 1; } @@ -268,57 +267,56 @@ public void progress() { return; } - - if (origin == null) { - if (bPlayer.isOnCooldown("IceBullet") && !bPlayer.isAvatarState()) { - remove(); + if (this.origin == null) { + if (this.bPlayer.isOnCooldown("IceBullet") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } - Block waterBlock = BlockSource.getWaterSourceBlock(player, range, ClickType.LEFT_CLICK, true, true, bPlayer.canPlantbend()); + final Block waterBlock = BlockSource.getWaterSourceBlock(this.player, this.range, ClickType.LEFT_CLICK, true, true, this.bPlayer.canPlantbend()); if (waterBlock == null) { - remove(); + this.remove(); return; } - time = 0; - origin = waterBlock.getLocation(); - location = origin.clone(); - state = AbilityState.ICE_BULLET_FORMING; - bPlayer.addCooldown("IceBullet", cooldown); - direction = new Vector(1, 0, 1); - waterGrabber = new WaterSourceGrabber(player, origin.clone()); - } else if (waterGrabber.getState() == WaterSourceGrabber.AnimationState.FAILED) { - remove(); + this.time = 0; + this.origin = waterBlock.getLocation(); + this.location = this.origin.clone(); + this.state = AbilityState.ICE_BULLET_FORMING; + this.bPlayer.addCooldown("IceBullet", this.cooldown); + this.direction = new Vector(1, 0, 1); + this.waterGrabber = new WaterSourceGrabber(this.player, this.origin.clone()); + } else if (this.waterGrabber.getState() == WaterSourceGrabber.AnimationState.FAILED) { + this.remove(); return; - } else if (waterGrabber.getState() == WaterSourceGrabber.AnimationState.FINISHED) { + } else if (this.waterGrabber.getState() == WaterSourceGrabber.AnimationState.FINISHED) { if (this.time == 0) { this.time = System.currentTimeMillis(); } - long timeDiff = System.currentTimeMillis() - this.time; + final long timeDiff = System.currentTimeMillis() - this.time; if (this.state == AbilityState.ICE_BULLET_FORMING) { - if (timeDiff < 1000 * animationSpeed) { - double steps = radius * ((timeDiff + 100) / (1000.0 * animationSpeed)); - revertBlocks(); + if (timeDiff < 1000 * this.animationSpeed) { + final double steps = this.radius * ((timeDiff + 100) / (1000.0 * this.animationSpeed)); + this.revertBlocks(); for (double i = 0; i < steps; i++) { - drawWaterCircle(player.getEyeLocation().clone().add(0, i, 0), 360, 5, radius - i); - drawWaterCircle(player.getEyeLocation().clone().add(0, -i, 0), 360, 5, radius - i); + this.drawWaterCircle(this.player.getEyeLocation().clone().add(0, i, 0), 360, 5, this.radius - i); + this.drawWaterCircle(this.player.getEyeLocation().clone().add(0, -i, 0), 360, 5, this.radius - i); } - } else if (timeDiff < 2500 * animationSpeed) { - revertBlocks(); - for (double i = 0; i < radius; i++) { - drawWaterCircle(player.getEyeLocation().clone().add(0, i, 0), 360, 5, radius - i, Material.ICE, (byte) 0); - drawWaterCircle(player.getEyeLocation().clone().add(0, -i, 0), 360, 5, radius - i, Material.ICE, (byte) 0); + } else if (timeDiff < 2500 * this.animationSpeed) { + this.revertBlocks(); + for (double i = 0; i < this.radius; i++) { + this.drawWaterCircle(this.player.getEyeLocation().clone().add(0, i, 0), 360, 5, this.radius - i, Material.ICE, (byte) 0); + this.drawWaterCircle(this.player.getEyeLocation().clone().add(0, -i, 0), 360, 5, this.radius - i, Material.ICE, (byte) 0); } } - if (timeDiff < shootTime) { - if (shots < rightClicks + leftClicks) { - shots++; - Vector vec = player.getEyeLocation().getDirection().normalize(); - Location loc = player.getEyeLocation().add(vec.clone().multiply(radius + 1.3)); - FireComboStream fs = new FireComboStream(player, this, vec, loc, range, speed); + if (timeDiff < this.shootTime) { + if (this.shots < this.rightClicks + this.leftClicks) { + this.shots++; + final Vector vec = this.player.getEyeLocation().getDirection().normalize(); + final Location loc = this.player.getEyeLocation().add(vec.clone().multiply(this.radius + 1.3)); + final FireComboStream fs = new FireComboStream(this.player, this, vec, loc, this.range, this.speed); fs.setDensity(10); fs.setSpread(0.1F); @@ -326,16 +324,16 @@ public void progress() { fs.setParticleEffect(ParticleEffect.SNOW_SHOVEL); fs.setCollides(false); fs.runTaskTimer(ProjectKorra.plugin, (0), 1L); - tasks.add(fs); + this.tasks.add(fs); } - manageShots(); + this.manageShots(); } else { - remove(); + this.remove(); return; } } } else { - waterGrabber.progress(); + this.waterGrabber.progress(); } } @@ -351,189 +349,198 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override public Location getLocation() { - return location; + return this.location; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new IceBullet(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList iceBullet = new ArrayList<>(); + iceBullet.add(new AbilityInformation("WaterBubble", ClickType.SHIFT_DOWN)); + iceBullet.add(new AbilityInformation("WaterBubble", ClickType.SHIFT_UP)); + iceBullet.add(new AbilityInformation("IceBlast", ClickType.SHIFT_DOWN)); + return iceBullet; } - + @Override public void remove() { super.remove(); - for (BukkitRunnable task : tasks) { + for (final BukkitRunnable task : this.tasks) { task.cancel(); } - revertBlocks(); - if (waterGrabber != null) { - waterGrabber.remove(); + this.revertBlocks(); + if (this.waterGrabber != null) { + this.waterGrabber.remove(); } - bPlayer.addCooldown(this); + this.bPlayer.addCooldown(this); } - + public void revertBlocks() { - Enumeration keys = affectedBlocks.keys(); + final Enumeration keys = this.affectedBlocks.keys(); while (keys.hasMoreElements()) { - Block block = keys.nextElement(); - affectedBlocks.get(block).revertBlock(); - affectedBlocks.remove(block); + final Block block = keys.nextElement(); + this.affectedBlocks.get(block).revertBlock(); + this.affectedBlocks.remove(block); } } - + public int getLeftClicks() { - return leftClicks; + return this.leftClicks; } - public void setLeftClicks(int leftClicks) { + public void setLeftClicks(final int leftClicks) { this.leftClicks = leftClicks; } public int getRightClicks() { - return rightClicks; + return this.rightClicks; } - public void setRightClicks(int rightClicks) { + public void setRightClicks(final int rightClicks) { this.rightClicks = rightClicks; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public double getShootTime() { - return shootTime; + return this.shootTime; } - public void setShootTime(double shootTime) { + public void setShootTime(final double shootTime) { this.shootTime = shootTime; } public double getShots() { - return shots; + return this.shots; } - public void setShots(double shots) { + public void setShots(final double shots) { this.shots = shots; } public double getMaxShots() { - return maxShots; + return this.maxShots; } - public void setMaxShots(double maxShots) { + public void setMaxShots(final double maxShots) { this.maxShots = maxShots; } public double getAnimationSpeed() { - return animationSpeed; + return this.animationSpeed; } - public void setAnimationSpeed(double animationSpeed) { + public void setAnimationSpeed(final double animationSpeed) { this.animationSpeed = animationSpeed; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public AbilityState getState() { - return state; + return this.state; } - public void setState(AbilityState state) { + public void setState(final AbilityState state) { this.state = state; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public WaterSourceGrabber getWaterGrabber() { - return waterGrabber; + return this.waterGrabber; } - public void setWaterGrabber(WaterSourceGrabber waterGrabber) { + public void setWaterGrabber(final WaterSourceGrabber waterGrabber) { this.waterGrabber = waterGrabber; } public ArrayList getTasks() { - return tasks; + return this.tasks; } - public void setTasks(ArrayList tasks) { + public void setTasks(final ArrayList tasks) { this.tasks = tasks; } public Map getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } - - public void setName(String name) { + + public void setName(final String name) { this.name = name; } -} \ No newline at end of file + + @Override + public String getInstructions() { + return "WaterBubble (Tap Shift) > IceBlast (Hold Shift) > Wait for ice to Form > Then alternate between Left and Right click with IceBlast"; + } +} diff --git a/src/com/projectkorra/projectkorra/waterbending/combo/IceWave.java b/src/com/projectkorra/projectkorra/waterbending/combo/IceWave.java index 8e0aeb720..9a4d245d5 100644 --- a/src/com/projectkorra/projectkorra/waterbending/combo/IceWave.java +++ b/src/com/projectkorra/projectkorra/waterbending/combo/IceWave.java @@ -11,35 +11,36 @@ import com.projectkorra.projectkorra.ability.ComboAbility; import com.projectkorra.projectkorra.ability.IceAbility; import com.projectkorra.projectkorra.ability.util.ComboManager.AbilityInformation; +import com.projectkorra.projectkorra.util.ClickType; import com.projectkorra.projectkorra.util.TempBlock; import com.projectkorra.projectkorra.waterbending.WaterSpoutWave; public class IceWave extends IceAbility implements ComboAbility { private static final Map FROZEN_BLOCKS = new ConcurrentHashMap<>(); - + private long cooldown; private Location origin; - - public IceWave(Player player) { + + public IceWave(final Player player) { super(player); - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { return; } - if (bPlayer.isOnCooldown("IceWave") && !bPlayer.isAvatarState()) { - remove(); + if (this.bPlayer.isOnCooldown("IceWave") && !this.bPlayer.isAvatarState()) { + this.remove(); return; } this.cooldown = getConfig().getLong("Abilities.Water.IceWave.Cooldown"); - if (bPlayer.isAvatarState()) { + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; } - start(); + this.start(); } @Override @@ -49,37 +50,37 @@ public String getName() { @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; } - - if (origin == null && WaterSpoutWave.containsType(player, WaterSpoutWave.AbilityType.RELEASE)) { - bPlayer.addCooldown("IceWave", cooldown); - origin = player.getLocation(); - WaterSpoutWave wave = WaterSpoutWave.getType(player, WaterSpoutWave.AbilityType.RELEASE).get(0); + if (this.origin == null && WaterSpoutWave.containsType(this.player, WaterSpoutWave.AbilityType.RELEASE)) { + this.bPlayer.addCooldown("IceWave", this.cooldown); + this.origin = this.player.getLocation(); + + final WaterSpoutWave wave = WaterSpoutWave.getType(this.player, WaterSpoutWave.AbilityType.RELEASE).get(0); wave.setIceWave(true); - } else if (!WaterSpoutWave.containsType(player, WaterSpoutWave.AbilityType.RELEASE)) { - remove(); + } else if (!WaterSpoutWave.containsType(this.player, WaterSpoutWave.AbilityType.RELEASE)) { + this.remove(); return; - } + } } - - public static boolean canThaw(Block block) { + + public static boolean canThaw(final Block block) { return FROZEN_BLOCKS.containsKey(block); } - public static void thaw(Block block) { + public static void thaw(final Block block) { if (FROZEN_BLOCKS.containsKey(block)) { FROZEN_BLOCKS.get(block).revertBlock(); FROZEN_BLOCKS.remove(block); } } - + @Override public void remove() { - bPlayer.addCooldown("WaterWave", cooldown); + this.bPlayer.addCooldown("WaterWave", this.cooldown); } @Override @@ -94,29 +95,37 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } - - public void setCooldown(long cooldown) { + + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } @Override public Location getLocation() { - return origin; + return this.origin; } - - public void setLocation(Location location) { + + public void setLocation(final Location location) { this.origin = location; } @Override - public Object createNewComboInstance(Player player) { - return null; + public Object createNewComboInstance(final Player player) { + return new IceWave(player); } @Override public ArrayList getCombination() { - return null; + final ArrayList iceWave = new ArrayList<>(); + iceWave.add(new AbilityInformation("WaterSpout", ClickType.SHIFT_UP)); + iceWave.add(new AbilityInformation("PhaseChange", ClickType.LEFT_CLICK)); + return iceWave; + } + + @Override + public String getInstructions() { + return "Create a WaterSpout Wave > PhaseChange (Left Click)"; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/healing/HealingWaters.java b/src/com/projectkorra/projectkorra/waterbending/healing/HealingWaters.java index 3cb0d20c4..d819e2210 100644 --- a/src/com/projectkorra/projectkorra/waterbending/healing/HealingWaters.java +++ b/src/com/projectkorra/projectkorra/waterbending/healing/HealingWaters.java @@ -16,26 +16,25 @@ import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.HealingAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.chiblocking.Smokescreen; import com.projectkorra.projectkorra.util.TempBlock; import com.projectkorra.projectkorra.waterbending.util.WaterReturn; public class HealingWaters extends HealingAbility { - // Configurable Variables - + // Configurable Variables. private long cooldown; private double range; private long interval; private long chargeTime; private int power; - private int duration; + private int potDuration; + private long duration; private boolean enableParticles; // Instance related and predefined variables. - private Player player; private LivingEntity target; private Location origin; @@ -51,132 +50,141 @@ public class HealingWaters extends HealingAbility { private boolean hasReached = false; private String hex; - public HealingWaters(Player player) { + public HealingWaters(final Player player) { super(player); - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } - setFields(); + this.setFields(); this.player = player; this.origin = player.getLocation().clone().add(player.getLocation().getDirection()).add(0, 1.5, 0); - this.location = origin.clone(); + this.location = this.origin.clone(); this.currTime = System.currentTimeMillis(); this.pstage = 0; this.tstage1 = 0; this.tstage2 = 18; - start(); + this.start(); } public void setFields() { - cooldown = getConfig().getLong("Abilities.Water.HealingWaters.Cooldown"); - range = getConfig().getDouble("Abilities.Water.HealingWaters.Range"); - interval = getConfig().getLong("Abilities.Water.HealingWaters.Interval"); - chargeTime = getConfig().getLong("Abilities.Water.HealingWaters.ChargeTime"); - power = getConfig().getInt("Abilities.Water.HealingWaters.Power"); - duration = getConfig().getInt("Abilities.Water.HealingWaters.Duration"); - enableParticles = getConfig().getBoolean("Abilities.Water.HealingWaters.EnableParticles"); - hex = "00ffff"; + this.cooldown = getConfig().getLong("Abilities.Water.HealingWaters.Cooldown"); + this.range = getConfig().getDouble("Abilities.Water.HealingWaters.Range"); + this.interval = getConfig().getLong("Abilities.Water.HealingWaters.Interval"); + this.chargeTime = getConfig().getLong("Abilities.Water.HealingWaters.ChargeTime"); + this.power = getConfig().getInt("Abilities.Water.HealingWaters.Power"); + this.potDuration = getConfig().getInt("Abilities.Water.HealingWaters.HealingDuration"); + this.duration = getConfig().getLong("Abilities.Water.HealingWaters.Duration"); + this.enableParticles = getConfig().getBoolean("Abilities.Water.HealingWaters.EnableParticles"); + this.hex = "00ffff"; } @Override public void progress() { - if (!bPlayer.canBend(this)) { - remove(); + if (!this.bPlayer.canBend(this)) { + this.remove(); return; } - if (!player.isSneaking()) { - bPlayer.addCooldown(this); - remove(); + if (this.duration != 0) { + if (System.currentTimeMillis() >= this.getStartTime() + this.duration) { + this.bPlayer.addCooldown(this); + this.remove(); + return; + } + } + + if (!this.player.isSneaking()) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - if (!inWater(player) && !WaterReturn.hasWaterBottle(player) && !charged) { - bPlayer.addCooldown(this); - remove(); + if (!this.inWater(this.player) && !WaterReturn.hasWaterBottle(this.player) && !this.charged) { + this.bPlayer.addCooldown(this); + this.remove(); return; } - if (WaterReturn.hasWaterBottle(player)) { - bottle = true; + if (WaterReturn.hasWaterBottle(this.player)) { + this.bottle = true; } // If ability is is charged, set charged = true. If not, play charging particles. - if (System.currentTimeMillis() >= getStartTime() + chargeTime) { - if (!charged) { + if (System.currentTimeMillis() >= this.getStartTime() + this.chargeTime) { + if (!this.charged) { this.charged = true; - WaterReturn.emptyWaterBottle(player); + WaterReturn.emptyWaterBottle(this.player); } } else { - GeneralMethods.displayColoredParticle(origin, hex); + GeneralMethods.displayColoredParticle(this.origin, this.hex); } // If the ability is charged, try healing. - if (charged) { + if (this.charged) { - if (target != null) { - displayHealingWater(target); + if (this.target != null) { + this.displayHealingWater(this.target); } else { - displayHealingWater((LivingEntity) player); + this.displayHealingWater(this.player); } // Try to heal themselves/target with 'interval' millisecond intervals. - if (System.currentTimeMillis() - currTime >= interval) { + if (System.currentTimeMillis() - this.currTime >= this.interval) { - heal(player); - currTime = System.currentTimeMillis(); + this.heal(this.player); + this.currTime = System.currentTimeMillis(); } // Display healing particles. - if (healing && enableParticles) { - if (healingSelf) { - displayHealingParticlesSelf(); + if (this.healing && this.enableParticles) { + if (this.healingSelf) { + this.displayHealingParticlesSelf(); } else { - displayHealingParticlesOther(); + this.displayHealingParticlesOther(); } } } } public void click() { - Entity target = GeneralMethods.getTargetedEntity(player, range); + final Entity target = GeneralMethods.getTargetedEntity(this.player, this.range); if (target != null && !target.equals(this.target) && target instanceof LivingEntity) { - hasReached = false; + this.hasReached = false; this.target = (LivingEntity) target; } else if (target != null && target.equals(this.target) && target instanceof LivingEntity) { - hasReached = false; + this.hasReached = false; this.target = null; } } - private void heal(Player player) { - Entity target = GeneralMethods.getTargetedEntity(player, range); + private void heal(final Player player) { + final Entity target = GeneralMethods.getTargetedEntity(player, this.range); if (target != null && this.target != null && target instanceof LivingEntity) { - if (this.target.getEntityId() == target.getEntityId() && hasReached) { - giveHP((LivingEntity) this.target); + if (this.target.getEntityId() == target.getEntityId() && this.hasReached) { + this.giveHP(this.target); } } else { - if (hasReached) { - giveHP(player); + if (this.hasReached) { + this.giveHP(player); this.target = null; } } } - private void giveHP(Player player) { + private void giveHP(final Player player) { if (!player.isDead() && player.getHealth() < player.getMaxHealth()) { - applyHealing(player); + this.applyHealing(player); } else { - healing = false; + this.healing = false; } - for (PotionEffect effect : player.getActivePotionEffects()) { + for (final PotionEffect effect : player.getActivePotionEffects()) { if (isNegativeEffect(effect.getType())) { if ((effect.getType() == PotionEffectType.BLINDNESS) && Smokescreen.getBlindedTimes().containsKey(player.getName())) { return; @@ -186,124 +194,124 @@ private void giveHP(Player player) { } } - private void giveHP(LivingEntity livingEntity) { + private void giveHP(final LivingEntity livingEntity) { if (!livingEntity.isDead() && livingEntity.getHealth() < livingEntity.getMaxHealth()) { - applyHealing(livingEntity); + this.applyHealing(livingEntity); } else { - healing = false; + this.healing = false; } - for (PotionEffect effect : livingEntity.getActivePotionEffects()) { - if (WaterAbility.isNegativeEffect(effect.getType())) { + for (final PotionEffect effect : livingEntity.getActivePotionEffects()) { + if (ElementalAbility.isNegativeEffect(effect.getType())) { livingEntity.removePotionEffect(effect.getType()); } } } - private void applyHealing(Player player) { + private void applyHealing(final Player player) { if (!GeneralMethods.isRegionProtectedFromBuild(player, "HealingWaters", player.getLocation())) { - player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, duration, power)); + player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, this.potDuration, this.power)); AirAbility.breakBreathbendingHold(player); - healing = true; - healingSelf = true; + this.healing = true; + this.healingSelf = true; } } - private void applyHealing(LivingEntity livingEntity) { + private void applyHealing(final LivingEntity livingEntity) { if (livingEntity.getHealth() < livingEntity.getMaxHealth()) { - livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, duration, power)); + livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, this.potDuration, this.power)); AirAbility.breakBreathbendingHold(livingEntity); - healing = true; - healingSelf = false; + this.healing = true; + this.healingSelf = false; } } - private boolean inWater(Player player) { - Block block = player.getLocation().getBlock(); + private boolean inWater(final Player player) { + final Block block = player.getLocation().getBlock(); return isWater(block) && !TempBlock.isTempBlock(block); } public void displayHealingParticlesSelf() { - if (hasReached) { - Location centre = player.getLocation().clone().add(0, 1, 0); - double increment = (2 * Math.PI) / 36; - double angle = pstage * increment; - double x = centre.getX() + (0.75 * Math.cos(angle)); - double z = centre.getZ() + (0.75 * Math.sin(angle)); - GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x, centre.getY(), z), hex); - - if (pstage >= 36) { - pstage = 0; + if (this.hasReached) { + final Location centre = this.player.getLocation().clone().add(0, 1, 0); + final double increment = (2 * Math.PI) / 36; + final double angle = this.pstage * increment; + final double x = centre.getX() + (0.75 * Math.cos(angle)); + final double z = centre.getZ() + (0.75 * Math.sin(angle)); + GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x, centre.getY(), z), this.hex); + + if (this.pstage >= 36) { + this.pstage = 0; } - pstage++; + this.pstage++; } } public void displayHealingParticlesOther() { - if (target != null) { - if (hasReached) { - Location centre = target.getLocation().clone().add(0, 1, 0); - double increment = (2 * Math.PI) / 36; - double angle1 = tstage1 * increment; - double angle2 = tstage2 * increment; - double x1 = centre.getX() + (0.75 * Math.cos(angle1)); - double z1 = centre.getZ() + (0.75 * Math.sin(angle1)); - double x2 = centre.getX() + (0.75 * Math.cos(angle2)); - double z2 = centre.getZ() + (0.75 * Math.sin(angle2)); - - GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x1, centre.getY() + (0.75 * Math.cos(angle1)), z1), hex); - GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x2, centre.getY() + (0.75 * -Math.cos(angle2)), z2), hex); - - if (tstage1 >= 36) { - tstage1 = 0; + if (this.target != null) { + if (this.hasReached) { + final Location centre = this.target.getLocation().clone().add(0, 1, 0); + final double increment = (2 * Math.PI) / 36; + final double angle1 = this.tstage1 * increment; + final double angle2 = this.tstage2 * increment; + final double x1 = centre.getX() + (0.75 * Math.cos(angle1)); + final double z1 = centre.getZ() + (0.75 * Math.sin(angle1)); + final double x2 = centre.getX() + (0.75 * Math.cos(angle2)); + final double z2 = centre.getZ() + (0.75 * Math.sin(angle2)); + + GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x1, centre.getY() + (0.75 * Math.cos(angle1)), z1), this.hex); + GeneralMethods.displayColoredParticle(new Location(centre.getWorld(), x2, centre.getY() + (0.75 * -Math.cos(angle2)), z2), this.hex); + + if (this.tstage1 >= 36) { + this.tstage1 = 0; } - tstage1++; + this.tstage1++; - if (tstage2 >= 36) { - tstage2 = 0; + if (this.tstage2 >= 36) { + this.tstage2 = 0; } - tstage2++; + this.tstage2++; } } } - public void displayHealingWater(LivingEntity target) { - double factor = 0.2; + public void displayHealingWater(final LivingEntity target) { + final double factor = 0.2; - Location targetLoc = target.getLocation().clone().add(0, 1, 0); + final Location targetLoc = target.getLocation().clone().add(0, 1, 0); double distance = 0; - if (location.getWorld().equals(targetLoc.getWorld())) { - distance = location.distance(targetLoc); + if (this.location.getWorld().equals(targetLoc.getWorld())) { + distance = this.location.distance(targetLoc); } - Vector vec = new Vector(targetLoc.getX() - location.getX(), targetLoc.getY() - location.getY(), targetLoc.getZ() - location.getZ()).normalize(); + final Vector vec = new Vector(targetLoc.getX() - this.location.getX(), targetLoc.getY() - this.location.getY(), targetLoc.getZ() - this.location.getZ()).normalize(); - if (location.getWorld().equals(targetLoc.getWorld()) && location.distance(targetLoc) <= distance) { - location = location.clone().add(vec.clone().multiply(factor)); - if (location.distance(targetLoc) <= 0.5) { - hasReached = true; + if (this.location.getWorld().equals(targetLoc.getWorld()) && this.location.distance(targetLoc) <= distance) { + this.location = this.location.clone().add(vec.clone().multiply(factor)); + if (this.location.distance(targetLoc) <= 0.5) { + this.hasReached = true; } else { - hasReached = false; + this.hasReached = false; } } - GeneralMethods.displayColoredParticle(location, hex); + GeneralMethods.displayColoredParticle(this.location, this.hex); } private void fillBottle() { - PlayerInventory inventory = player.getInventory(); + final PlayerInventory inventory = this.player.getInventory(); if (inventory.contains(Material.GLASS_BOTTLE)) { - int index = inventory.first(Material.GLASS_BOTTLE); - ItemStack item = inventory.getItem(index); + final int index = inventory.first(Material.GLASS_BOTTLE); + final ItemStack item = inventory.getItem(index); if (item.getAmount() == 1) { inventory.setItem(index, new ItemStack(Material.POTION)); } else { item.setAmount(item.getAmount() - 1); inventory.setItem(index, item); - HashMap leftover = inventory.addItem(new ItemStack(Material.POTION)); - for (int left : leftover.keySet()) { - player.getWorld().dropItemNaturally(player.getLocation(), leftover.get(left)); + final HashMap leftover = inventory.addItem(new ItemStack(Material.POTION)); + for (final int left : leftover.keySet()) { + this.player.getWorld().dropItemNaturally(this.player.getLocation(), leftover.get(left)); } } } @@ -311,8 +319,8 @@ private void fillBottle() { @Override public void remove() { - if (bottle && charged) { - fillBottle(); + if (this.bottle && this.charged) { + this.fillBottle(); } super.remove(); } @@ -329,7 +337,7 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -339,7 +347,7 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } } diff --git a/src/com/projectkorra/projectkorra/waterbending/ice/IceBlast.java b/src/com/projectkorra/projectkorra/waterbending/ice/IceBlast.java index ce417cd96..202781596 100644 --- a/src/com/projectkorra/projectkorra/waterbending/ice/IceBlast.java +++ b/src/com/projectkorra/projectkorra/waterbending/ice/IceBlast.java @@ -1,16 +1,7 @@ package com.projectkorra.projectkorra.waterbending.ice; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.ability.IceAbility; -import com.projectkorra.projectkorra.util.BlockSource; -import com.projectkorra.projectkorra.util.ClickType; -import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.ParticleEffect; -import com.projectkorra.projectkorra.util.TempBlock; -import com.projectkorra.projectkorra.util.TempPotionEffect; -import com.projectkorra.projectkorra.waterbending.util.WaterReturn; +import java.util.ArrayList; +import java.util.Random; import org.bukkit.Location; import org.bukkit.Material; @@ -23,8 +14,17 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; -import java.util.ArrayList; -import java.util.Random; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.ability.IceAbility; +import com.projectkorra.projectkorra.util.BlockSource; +import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.TempBlock; +import com.projectkorra.projectkorra.util.TempPotionEffect; +import com.projectkorra.projectkorra.waterbending.util.WaterReturn; public class IceBlast extends IceAbility { @@ -45,7 +45,7 @@ public class IceBlast extends IceAbility { private Location destination; public TempBlock source; - public IceBlast(Player player) { + public IceBlast(final Player player) { super(player); this.data = 0; @@ -56,49 +56,54 @@ public IceBlast(Player player) { this.damage = getConfig().getInt("Abilities.Water.IceBlast.Damage"); this.cooldown = getConfig().getInt("Abilities.Water.IceBlast.Cooldown"); - this.damage = getNightFactor(damage, player.getWorld()); + this.damage = getNightFactor(this.damage, player.getWorld()); - if (!bPlayer.canBend(this) || !bPlayer.canIcebend()) { + if (!this.bPlayer.canBend(this) || !this.bPlayer.canIcebend()) { return; } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceBlast.Range"); this.damage = getConfig().getInt("Abilities.Avatar.AvatarState.Water.IceBlast.Damage"); } block(player); - range = getNightFactor(range, player.getWorld()); - Block sourceBlock = BlockSource.getWaterSourceBlock(player, range, ClickType.SHIFT_DOWN, false, true, false, false, false); + this.range = getNightFactor(this.range, player.getWorld()); + final Block sourceBlock = BlockSource.getWaterSourceBlock(player, this.range, ClickType.SHIFT_DOWN, false, true, false, false, false); + final IceBlast oldAbil = getAbility(player, IceBlast.class); + if (oldAbil != null) { + oldAbil.setSourceBlock(sourceBlock == null ? oldAbil.getSourceBlock() : sourceBlock); + return; + } if (sourceBlock == null) { return; } else if (GeneralMethods.isRegionProtectedFromBuild(this, sourceBlock.getLocation())) { return; } else { - prepare(sourceBlock); + this.prepare(sourceBlock); } } - private void prepare(Block block) { - for (IceBlast iceBlast : getAbilities(player, IceBlast.class)) { + private void prepare(final Block block) { + for (final IceBlast iceBlast : getAbilities(this.player, IceBlast.class)) { if (iceBlast.prepared) { iceBlast.remove(); } } - sourceBlock = block; - location = sourceBlock.getLocation(); - prepared = true; + this.sourceBlock = block; + this.location = this.sourceBlock.getLocation(); + this.prepared = true; - if (getAbilities(player, IceBlast.class).isEmpty()) { - start(); + if (getAbilities(this.player, IceBlast.class).isEmpty()) { + this.start(); } } - private static void block(Player player) { - for (IceBlast iceBlast : getAbilities(IceBlast.class)) { + private static void block(final Player player) { + for (final IceBlast iceBlast : getAbilities(IceBlast.class)) { if (!iceBlast.location.getWorld().equals(player.getWorld())) { continue; } else if (!iceBlast.progressing) { @@ -109,9 +114,9 @@ private static void block(Player player) { continue; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = iceBlast.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = iceBlast.location; if (mloc.distanceSquared(location) <= iceBlast.range * iceBlast.range && GeneralMethods.getDistanceFromLine(vector, location, iceBlast.location) < iceBlast.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { iceBlast.remove(); @@ -119,13 +124,13 @@ private static void block(Player player) { } } - public static void activate(Player player) { - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + public static void activate(final Player player) { + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer != null && bPlayer.isOnCooldown("IceBlast")) { return; } - for (IceBlast ice : getAbilities(IceBlast.class)) { + for (final IceBlast ice : getAbilities(IceBlast.class)) { if (ice.prepared) { ice.throwIce(); } @@ -135,193 +140,193 @@ public static void activate(Player player) { @Override public void remove() { super.remove(); - if (progressing) { - if (source != null) { - source.revertBlock(); + if (this.progressing) { + if (this.source != null) { + this.source.revertBlock(); } - progressing = false; + this.progressing = false; } - if (player.isOnline()) { - if (bPlayer != null) { - bPlayer.addCooldown(this); + if (this.player.isOnline()) { + if (this.bPlayer != null) { + this.bPlayer.addCooldown(this); } } } private void returnWater() { - new WaterReturn(player, sourceBlock); + new WaterReturn(this.player, this.sourceBlock); } - private void affect(LivingEntity entity) { + private void affect(final LivingEntity entity) { if (entity instanceof Player) { - if (bPlayer.canBeSlowed()) { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 70, 2); + if (this.bPlayer.canBeSlowed()) { + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 70, 2); new TempPotionEffect(entity, effect); - bPlayer.slow(10); - DamageHandler.damageEntity(entity, damage, this); + this.bPlayer.slow(10); + DamageHandler.damageEntity(entity, this.damage, this); } } else { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 70, 2); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 70, 2); new TempPotionEffect(entity, effect); - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } AirAbility.breakBreathbendingHold(entity); for (int x = 0; x < 30; x++) { - ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), .3f, location, 255.0); + ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), .3f, this.location, 255.0); } } private void throwIce() { - if (!prepared) { + if (!this.prepared) { return; } - LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(player, range, new ArrayList()); + final LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(this.player, this.range, new ArrayList()); if (target == null) { - destination = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterials()); + this.destination = GeneralMethods.getTargetedLocation(this.player, this.range, getTransparentMaterials()); } else { - destination = target.getEyeLocation(); + this.destination = target.getEyeLocation(); } - location = sourceBlock.getLocation(); - if (destination.distanceSquared(location) < 1) { + this.location = this.sourceBlock.getLocation(); + if (this.destination.distanceSquared(this.location) < 1) { return; } - firstDestination = location.clone(); - if (destination.getY() - location.getY() > 2) { - firstDestination.setY(destination.getY() - 1); + this.firstDestination = this.location.clone(); + if (this.destination.getY() - this.location.getY() > 2) { + this.firstDestination.setY(this.destination.getY() - 1); } else { - firstDestination.add(0, 2, 0); + this.firstDestination.add(0, 2, 0); } - destination = GeneralMethods.getPointOnLine(firstDestination, destination, range); - progressing = true; - settingUp = true; - prepared = false; - - if (TempBlock.isTempBlock(sourceBlock)) { - TempBlock.get(sourceBlock).setType(Material.PACKED_ICE, data); - source = TempBlock.get(sourceBlock); + this.destination = GeneralMethods.getPointOnLine(this.firstDestination, this.destination, this.range); + this.progressing = true; + this.settingUp = true; + this.prepared = false; + + if (TempBlock.isTempBlock(this.sourceBlock)) { + TempBlock.get(this.sourceBlock).setType(Material.PACKED_ICE, this.data); + this.source = TempBlock.get(this.sourceBlock); } else { - new TempBlock(sourceBlock, Material.AIR, (byte) 0); - source = new TempBlock(sourceBlock, Material.PACKED_ICE, data); + new TempBlock(this.sourceBlock, Material.AIR, (byte) 0); + this.source = new TempBlock(this.sourceBlock, Material.PACKED_ICE, this.data); } } @Override public void progress() { - if (!bPlayer.canBendIgnoreBinds(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBinds(this)) { + this.remove(); return; } - if (player.getEyeLocation().distanceSquared(location) >= range * range) { - if (progressing) { - breakParticles(20); - remove(); - returnWater(); + if (this.player.getEyeLocation().distanceSquared(this.location) >= this.range * this.range) { + if (this.progressing) { + this.breakParticles(20); + this.remove(); + this.returnWater(); } else { - breakParticles(20); - remove(); + this.breakParticles(20); + this.remove(); } return; } - if (!bPlayer.getBoundAbilityName().equalsIgnoreCase(getName()) && prepared) { - remove(); + if (!this.bPlayer.getBoundAbilityName().equalsIgnoreCase(this.getName()) && this.prepared) { + this.remove(); return; } - if (System.currentTimeMillis() < time + interval) { + if (System.currentTimeMillis() < this.time + this.interval) { return; } - time = System.currentTimeMillis(); - if (progressing) { + this.time = System.currentTimeMillis(); + if (this.progressing) { Vector direction; - if (location.getBlockY() == firstDestination.getBlockY()) { - settingUp = false; + if (this.location.getBlockY() == this.firstDestination.getBlockY()) { + this.settingUp = false; } - if (location.distanceSquared(destination) <= 4) { - remove(); - returnWater(); + if (this.location.distanceSquared(this.destination) <= 4) { + this.remove(); + this.returnWater(); return; } - if (settingUp) { - direction = GeneralMethods.getDirection(location, firstDestination).normalize(); + if (this.settingUp) { + direction = GeneralMethods.getDirection(this.location, this.firstDestination).normalize(); } else { - direction = GeneralMethods.getDirection(location, destination).normalize(); + direction = GeneralMethods.getDirection(this.location, this.destination).normalize(); } - location.add(direction); - Block block = location.getBlock(); - if (block.equals(sourceBlock)) { + this.location.add(direction); + final Block block = this.location.getBlock(); + if (block.equals(this.sourceBlock)) { return; } - source.revertBlock(); - source = null; + this.source.revertBlock(); + this.source = null; - if (isTransparent(player, block) && !block.isLiquid()) { + if (isTransparent(this.player, block) && !block.isLiquid()) { GeneralMethods.breakBlock(block); } else if (!isWater(block)) { - breakParticles(20); - remove(); - returnWater(); + this.breakParticles(20); + this.remove(); + this.returnWater(); return; } - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); - returnWater(); + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); + this.returnWater(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { - if (entity.getEntityId() != player.getEntityId() && entity instanceof LivingEntity) { - affect((LivingEntity) entity); - progressing = false; - returnWater(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { + if (entity.getEntityId() != this.player.getEntityId() && entity instanceof LivingEntity) { + this.affect((LivingEntity) entity); + this.progressing = false; + this.returnWater(); } } - if (!progressing) { - remove(); + if (!this.progressing) { + this.remove(); return; } - sourceBlock = block; - if (TempBlock.isTempBlock(sourceBlock)) { - TempBlock.get(sourceBlock).setType(Material.PACKED_ICE, data); - source = TempBlock.get(sourceBlock); + this.sourceBlock = block; + if (TempBlock.isTempBlock(this.sourceBlock)) { + TempBlock.get(this.sourceBlock).setType(Material.PACKED_ICE, this.data); + this.source = TempBlock.get(this.sourceBlock); } else { - source = new TempBlock(sourceBlock, Material.PACKED_ICE, data); + this.source = new TempBlock(this.sourceBlock, Material.PACKED_ICE, this.data); } for (int x = 0; x < 10; x++) { - ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), .5f, location, 255.0); - ParticleEffect.SNOW_SHOVEL.display(location, (float) (Math.random() - 0.5), (float) (Math.random() - 0.5), (float) (Math.random() - 0.5), 0, 5); + ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), .5f, this.location, 255.0); + ParticleEffect.SNOW_SHOVEL.display(this.location, (float) (Math.random() - 0.5), (float) (Math.random() - 0.5), (float) (Math.random() - 0.5), 0, 5); } if ((new Random()).nextInt(4) == 0) { - playIcebendingSound(location); + playIcebendingSound(this.location); } - location = location.add(direction.clone()); - } else if (prepared) { - playFocusWaterEffect(sourceBlock); + this.location = this.location.add(direction.clone()); + } else if (this.prepared) { + playFocusWaterEffect(this.sourceBlock); } } - public void breakParticles(int amount) { + public void breakParticles(final int amount) { for (int x = 0; x < amount; x++) { - ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), 2f, location, 255.0); - ParticleEffect.SNOW_SHOVEL.display(location, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 2); + ParticleEffect.ITEM_CRACK.display(new ParticleEffect.ItemData(Material.ICE, (byte) 0), new Vector(((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5), ((Math.random() - 0.5) * .5)), 2f, this.location, 255.0); + ParticleEffect.SNOW_SHOVEL.display(this.location, (float) Math.random(), (float) Math.random(), (float) Math.random(), 0, 2); } - location.getWorld().playSound(location, Sound.BLOCK_GLASS_BREAK, 5, 1.3f); + this.location.getWorld().playSound(this.location, Sound.BLOCK_GLASS_BREAK, 5, 1.3f); } @Override @@ -331,17 +336,17 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; - } else if (sourceBlock != null) { - return sourceBlock.getLocation(); + if (this.location != null) { + return this.location; + } else if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -356,127 +361,127 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return progressing; + return this.progressing; } @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } public boolean isPrepared() { - return prepared; + return this.prepared; } - public void setPrepared(boolean prepared) { + public void setPrepared(final boolean prepared) { this.prepared = prepared; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public byte getData() { - return data; + return this.data; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } public double getDeflectRange() { - return deflectRange; + return this.deflectRange; } - public void setDeflectRange(double deflectRange) { + public void setDeflectRange(final double deflectRange) { this.deflectRange = deflectRange; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public TempBlock getSource() { - return source; + return this.source; } - public void setSource(TempBlock source) { + public void setSource(final TempBlock source) { this.source = source; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikeBlast.java b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikeBlast.java index e7ceb6aff..74afcecf7 100644 --- a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikeBlast.java +++ b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikeBlast.java @@ -1,14 +1,6 @@ package com.projectkorra.projectkorra.waterbending.ice; -import com.projectkorra.projectkorra.BendingPlayer; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.AirAbility; -import com.projectkorra.projectkorra.ability.IceAbility; -import com.projectkorra.projectkorra.util.DamageHandler; -import com.projectkorra.projectkorra.util.TempBlock; -import com.projectkorra.projectkorra.util.TempPotionEffect; -import com.projectkorra.projectkorra.waterbending.plant.PlantRegrowth; -import com.projectkorra.projectkorra.waterbending.util.WaterReturn; +import java.util.Random; import org.bukkit.Location; import org.bukkit.Material; @@ -21,7 +13,15 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; -import java.util.Random; +import com.projectkorra.projectkorra.BendingPlayer; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.AirAbility; +import com.projectkorra.projectkorra.ability.IceAbility; +import com.projectkorra.projectkorra.util.DamageHandler; +import com.projectkorra.projectkorra.util.TempBlock; +import com.projectkorra.projectkorra.util.TempPotionEffect; +import com.projectkorra.projectkorra.waterbending.plant.PlantRegrowth; +import com.projectkorra.projectkorra.waterbending.util.WaterReturn; public class IceSpikeBlast extends IceAbility { @@ -45,10 +45,10 @@ public class IceSpikeBlast extends IceAbility { private Location destination; private TempBlock source; - public IceSpikeBlast(Player player) { + public IceSpikeBlast(final Player player) { super(player); - if (bPlayer.isOnCooldown("IceSpikeBlast")) { + if (this.bPlayer.isOnCooldown("IceSpikeBlast")) { return; } @@ -63,11 +63,11 @@ public IceSpikeBlast(Player player) { this.slowPower = getConfig().getInt("Abilities.Water.IceSpike.Blast.SlowPower"); this.slowDuration = getConfig().getInt("Abilities.Water.IceSpike.Blast.SlowDuration"); - if (!bPlayer.canBend(this) || !bPlayer.canIcebend()) { + if (!this.bPlayer.canBend(this) || !this.bPlayer.canIcebend()) { return; } - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.cooldown = 0; this.slowCooldown = 0; this.range = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceSpike.Blast.Range"); @@ -77,149 +77,148 @@ public IceSpikeBlast(Player player) { } block(player); - this.range = getNightFactor(range); - this.damage = getNightFactor(damage); - this.slowPower = (int) getNightFactor(slowPower); - sourceBlock = getWaterSourceBlock(player, range, bPlayer.canPlantbend()); - if (sourceBlock == null) { - sourceBlock = getIceSourceBlock(player, range); + this.range = this.getNightFactor(this.range); + this.damage = this.getNightFactor(this.damage); + this.slowPower = (int) this.getNightFactor(this.slowPower); + this.sourceBlock = getWaterSourceBlock(player, this.range, this.bPlayer.canPlantbend()); + if (this.sourceBlock == null) { + this.sourceBlock = getIceSourceBlock(player, this.range); } - if (sourceBlock == null) { + if (this.sourceBlock == null) { new IceSpikePillarField(player); - } else if (GeneralMethods.isRegionProtectedFromBuild(this, sourceBlock.getLocation())) { + } else if (GeneralMethods.isRegionProtectedFromBuild(this, this.sourceBlock.getLocation())) { return; } else { - prepare(sourceBlock); + this.prepare(this.sourceBlock); } } - private void affect(LivingEntity entity) { + private void affect(final LivingEntity entity) { if (entity instanceof Player) { - BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); + final BendingPlayer targetBPlayer = BendingPlayer.getBendingPlayer((Player) entity); if (targetBPlayer == null) { return; } if (targetBPlayer.canBeSlowed()) { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, slowDuration, slowPower); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, this.slowDuration, this.slowPower); new TempPotionEffect(entity, effect); - targetBPlayer.slow(slowCooldown); - DamageHandler.damageEntity(entity, damage, this); + targetBPlayer.slow(this.slowCooldown); + DamageHandler.damageEntity(entity, this.damage, this); } } else { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, slowDuration, slowPower); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, this.slowDuration, this.slowPower); new TempPotionEffect(entity, effect); - DamageHandler.damageEntity(entity, damage, this); + DamageHandler.damageEntity(entity, this.damage, this); } AirAbility.breakBreathbendingHold(entity); } - private void prepare(Block block) { - for (IceSpikeBlast iceSpike : getAbilities(player, IceSpikeBlast.class)) { + private void prepare(final Block block) { + for (final IceSpikeBlast iceSpike : getAbilities(this.player, IceSpikeBlast.class)) { if (iceSpike.prepared) { iceSpike.remove(); } } - sourceBlock = block; - location = sourceBlock.getLocation(); - prepared = true; - start(); + this.sourceBlock = block; + this.location = this.sourceBlock.getLocation(); + this.prepared = true; + this.start(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; - } else if (player.getEyeLocation().distanceSquared(location) >= range * range) { - if (progressing) { - remove(); - returnWater(); + } else if (this.player.getEyeLocation().distanceSquared(this.location) >= this.range * this.range) { + if (this.progressing) { + this.remove(); + this.returnWater(); } else { - remove(); + this.remove(); } return; - } else if (!bPlayer.getBoundAbilityName().equals(getName()) && prepared) { - remove(); + } else if (!this.bPlayer.getBoundAbilityName().equals(this.getName()) && this.prepared) { + this.remove(); return; } - if (System.currentTimeMillis() < time + interval) { + if (System.currentTimeMillis() < this.time + this.interval) { return; } - time = System.currentTimeMillis(); + this.time = System.currentTimeMillis(); - if (progressing) { + if (this.progressing) { Vector direction; - if (location.getBlockY() == firstDestination.getBlockY()) { - settingUp = false; + if (this.location.getBlockY() == this.firstDestination.getBlockY()) { + this.settingUp = false; } - if (location.distanceSquared(destination) <= 4) { - remove(); - returnWater(); + if (this.location.distanceSquared(this.destination) <= 4) { + this.remove(); + this.returnWater(); return; } - if (settingUp) { - direction = GeneralMethods.getDirection(location, firstDestination).normalize(); + if (this.settingUp) { + direction = GeneralMethods.getDirection(this.location, this.firstDestination).normalize(); } else { - direction = GeneralMethods.getDirection(location, destination).normalize(); + direction = GeneralMethods.getDirection(this.location, this.destination).normalize(); } - location.add(direction); - Block block = location.getBlock(); - if (block.equals(sourceBlock)) { + this.location.add(direction); + final Block block = this.location.getBlock(); + if (block.equals(this.sourceBlock)) { return; } - if (source != null) { - source.revertBlock(); - } - source = null; + this.source = null; - if (isTransparent(player, block) && !block.isLiquid()) { + if (isTransparent(this.player, block) && !block.isLiquid()) { GeneralMethods.breakBlock(block); } else if (!isWater(block)) { - remove(); - returnWater(); + this.remove(); + this.returnWater(); return; } - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { - remove(); - returnWater(); + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { + this.remove(); + this.returnWater(); return; } - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, collisionRadius)) { - if (entity.getEntityId() != player.getEntityId() && entity instanceof LivingEntity) { - affect((LivingEntity) entity); - progressing = false; - returnWater(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { + if (entity.getEntityId() != this.player.getEntityId() && entity instanceof LivingEntity) { + this.affect((LivingEntity) entity); + this.progressing = false; + this.returnWater(); } } if ((new Random()).nextInt(4) == 0) { - playIcebendingSound(location); + playIcebendingSound(this.location); } - if (!progressing) { - remove(); + if (!this.progressing) { + this.remove(); return; } - sourceBlock = block; - source = new TempBlock(sourceBlock, Material.ICE, data); - } else if (prepared) { - if (sourceBlock != null) - playFocusWaterEffect(sourceBlock); + this.sourceBlock = block; + this.source = new TempBlock(this.sourceBlock, Material.ICE, this.data); + this.source.setRevertTime(140); + } else if (this.prepared) { + if (this.sourceBlock != null) { + playFocusWaterEffect(this.sourceBlock); + } } } - private void redirect(Location destination, Player player) { + private void redirect(final Location destination, final Player player) { this.destination = destination; this.setPlayer(player); } @@ -227,61 +226,61 @@ private void redirect(Location destination, Player player) { @Override public void remove() { super.remove(); - if (progressing) { - if (source != null) { - source.revertBlock(); + if (this.progressing) { + if (this.source != null) { + this.source.revertBlock(); } - progressing = false; + this.progressing = false; } } private void returnWater() { - new WaterReturn(player, location.getBlock()); + new WaterReturn(this.player, this.location.getBlock()); } private void throwIce() { - if (!prepared) { + if (!this.prepared) { return; } - LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(player, range); + final LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(this.player, this.range); if (target == null) { - destination = GeneralMethods.getTargetedLocation(player, range, getTransparentMaterials()); + this.destination = GeneralMethods.getTargetedLocation(this.player, this.range, getTransparentMaterials()); } else { - destination = target.getEyeLocation(); + this.destination = target.getEyeLocation(); } - if (sourceBlock == null) { + if (this.sourceBlock == null) { return; } - location = sourceBlock.getLocation(); - if (destination.distanceSquared(location) < 1) { + this.location = this.sourceBlock.getLocation(); + if (this.destination.distanceSquared(this.location) < 1) { return; } - firstDestination = location.clone(); - if (destination.getY() - location.getY() > 2) { - firstDestination.setY(destination.getY() - 1); + this.firstDestination = this.location.clone(); + if (this.destination.getY() - this.location.getY() > 2) { + this.firstDestination.setY(this.destination.getY() - 1); } else { - firstDestination.add(0, 2, 0); + this.firstDestination.add(0, 2, 0); } - destination = GeneralMethods.getPointOnLine(firstDestination, destination, range); - progressing = true; - settingUp = true; - prepared = false; + this.destination = GeneralMethods.getPointOnLine(this.firstDestination, this.destination, this.range); + this.progressing = true; + this.settingUp = true; + this.prepared = false; - if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); - sourceBlock.setType(Material.AIR); + if (isPlant(this.sourceBlock) || isSnow(this.sourceBlock)) { + new PlantRegrowth(this.player, this.sourceBlock); + this.sourceBlock.setType(Material.AIR); } } - public static void activate(Player player) { + public static void activate(final Player player) { redirect(player); boolean activate = false; - BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); + final BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if (bPlayer == null) { return; @@ -291,7 +290,7 @@ public static void activate(Player player) { return; } - for (IceSpikeBlast ice : getAbilities(player, IceSpikeBlast.class)) { + for (final IceSpikeBlast ice : getAbilities(player, IceSpikeBlast.class)) { if (ice.prepared) { ice.throwIce(); bPlayer.addCooldown("IceSpikeBlast", ice.getCooldown()); @@ -300,15 +299,15 @@ public static void activate(Player player) { } if (!activate && !getPlayers(IceSpikeBlast.class).contains(player)) { - IceSpikePillar spike = new IceSpikePillar(player); + final IceSpikePillar spike = new IceSpikePillar(player); if (!spike.isStarted()) { waterBottle(player); } } } - private static void block(Player player) { - for (IceSpikeBlast iceSpike : getAbilities(IceSpikeBlast.class)) { + private static void block(final Player player) { + for (final IceSpikeBlast iceSpike : getAbilities(IceSpikeBlast.class)) { if (iceSpike.player.equals(player)) { continue; } else if (!iceSpike.location.getWorld().equals(player.getWorld())) { @@ -320,17 +319,17 @@ private static void block(Player player) { continue; } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = iceSpike.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = iceSpike.location; if (mloc.distanceSquared(location) <= iceSpike.range * iceSpike.range && GeneralMethods.getDistanceFromLine(vector, location, iceSpike.location) < iceSpike.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { iceSpike.remove(); } } } - private static void redirect(Player player) { - for (IceSpikeBlast iceSpike : getAbilities(IceSpikeBlast.class)) { + private static void redirect(final Player player) { + for (final IceSpikeBlast iceSpike : getAbilities(IceSpikeBlast.class)) { if (!iceSpike.progressing) { continue; } else if (!iceSpike.location.getWorld().equals(player.getWorld())) { @@ -339,7 +338,7 @@ private static void redirect(Player player) { if (iceSpike.player.equals(player)) { Location location; - Entity target = GeneralMethods.getTargetedEntity(player, iceSpike.range); + final Entity target = GeneralMethods.getTargetedEntity(player, iceSpike.range); if (target == null) { location = GeneralMethods.getTargetedLocation(player, iceSpike.range); } else { @@ -349,15 +348,15 @@ private static void redirect(Player player) { iceSpike.redirect(location, player); } - Location location = player.getEyeLocation(); - Vector vector = location.getDirection(); - Location mloc = iceSpike.location; + final Location location = player.getEyeLocation(); + final Vector vector = location.getDirection(); + final Location mloc = iceSpike.location; if (GeneralMethods.isRegionProtectedFromBuild(iceSpike, mloc)) { continue; } else if (mloc.distanceSquared(location) <= iceSpike.range * iceSpike.range && GeneralMethods.getDistanceFromLine(vector, location, iceSpike.location) < iceSpike.deflectRange && mloc.distanceSquared(location.clone().add(vector)) < mloc.distanceSquared(location.clone().add(vector.clone().multiply(-1)))) { Location loc; - Entity target = GeneralMethods.getTargetedEntity(player, iceSpike.range); + final Entity target = GeneralMethods.getTargetedEntity(player, iceSpike.range); if (target == null) { loc = GeneralMethods.getTargetedLocation(player, iceSpike.range); } else { @@ -370,15 +369,15 @@ private static void redirect(Player player) { } } - private static void waterBottle(Player player) { - long range = getConfig().getLong("Abilities.Water.IceSpike.Projectile.Range"); + private static void waterBottle(final Player player) { + final long range = getConfig().getLong("Abilities.Water.IceSpike.Projectile.Range"); if (WaterReturn.hasWaterBottle(player)) { - Location eyeLoc = player.getEyeLocation(); - Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); + final Location eyeLoc = player.getEyeLocation(); + final Block block = eyeLoc.add(eyeLoc.getDirection().normalize()).getBlock(); if (isTransparent(player, block) && isTransparent(player, eyeLoc.getBlock())) { - LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(player, range); + final LivingEntity target = (LivingEntity) GeneralMethods.getTargetedEntity(player, range); Location destination; if (target == null) { @@ -391,10 +390,10 @@ private static void waterBottle(Player player) { return; } - MaterialData data = block.getState().getData(); + final MaterialData data = block.getState().getData(); block.setType(Material.WATER); block.setData((byte) 0); - IceSpikeBlast iceSpike = new IceSpikeBlast(player); + final IceSpikeBlast iceSpike = new IceSpikeBlast(player); iceSpike.throwIce(); iceSpike.sourceBlock = null; @@ -415,17 +414,17 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; - } else if (sourceBlock != null) { - return sourceBlock.getLocation(); + if (this.location != null) { + return this.location; + } else if (this.sourceBlock != null) { + return this.sourceBlock.getLocation(); } - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -440,151 +439,151 @@ public boolean isHarmlessAbility() { @Override public boolean isCollidable() { - return progressing; + return this.progressing; } @Override public double getCollisionRadius() { - return collisionRadius; + return this.collisionRadius; } public boolean isPrepared() { - return prepared; + return this.prepared; } - public void setPrepared(boolean prepared) { + public void setPrepared(final boolean prepared) { this.prepared = prepared; } public boolean isSettingUp() { - return settingUp; + return this.settingUp; } - public void setSettingUp(boolean settingUp) { + public void setSettingUp(final boolean settingUp) { this.settingUp = settingUp; } public boolean isProgressing() { - return progressing; + return this.progressing; } - public void setProgressing(boolean progressing) { + public void setProgressing(final boolean progressing) { this.progressing = progressing; } public byte getData() { - return data; + return this.data; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } public int getSlowPower() { - return slowPower; + return this.slowPower; } - public void setSlowPower(int slowPower) { + public void setSlowPower(final int slowPower) { this.slowPower = slowPower; } public int getSlowDuration() { - return slowDuration; + return this.slowDuration; } - public void setSlowDuration(int slowDuration) { + public void setSlowDuration(final int slowDuration) { this.slowDuration = slowDuration; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public long getSlowCooldown() { - return slowCooldown; + return this.slowCooldown; } - public void setSlowCooldown(long slowCooldown) { + public void setSlowCooldown(final long slowCooldown) { this.slowCooldown = slowCooldown; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } - public void setCollisionRadius(double collisionRadius) { + public void setCollisionRadius(final double collisionRadius) { this.collisionRadius = collisionRadius; } public double getDeflectRange() { - return deflectRange; + return this.deflectRange; } - public void setDeflectRange(double deflectRange) { + public void setDeflectRange(final double deflectRange) { this.deflectRange = deflectRange; } public Block getSourceBlock() { - return sourceBlock; + return this.sourceBlock; } - public void setSourceBlock(Block sourceBlock) { + public void setSourceBlock(final Block sourceBlock) { this.sourceBlock = sourceBlock; } public Location getFirstDestination() { - return firstDestination; + return this.firstDestination; } - public void setFirstDestination(Location firstDestination) { + public void setFirstDestination(final Location firstDestination) { this.firstDestination = firstDestination; } public Location getDestination() { - return destination; + return this.destination; } - public void setDestination(Location destination) { + public void setDestination(final Location destination) { this.destination = destination; } public TempBlock getSource() { - return source; + return this.source; } - public void setSource(TempBlock source) { + public void setSource(final TempBlock source) { this.source = source; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillar.java b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillar.java index e5337b8b5..4ba2a2571 100644 --- a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillar.java +++ b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillar.java @@ -27,7 +27,7 @@ public class IceSpikePillar extends IceAbility { /** The list of blocks IceSpike uses */ - private Map ice_blocks = new HashMap(); + private final Map ice_blocks = new HashMap(); private int height; private int progress; @@ -42,27 +42,27 @@ public class IceSpikePillar extends IceAbility { private double damage; private double range; private double speed; - private Block source_block; //The block clicked on - private Block base_block; //The block at the bottom of the pillar + private Block source_block; // The block clicked on. + private Block base_block; // The block at the bottom of the pillar. private Location origin; private Location location; private Vector thrownForce; private Vector direction; private ArrayList damaged; - protected boolean inField = false; //If it's part of a field or not. + protected boolean inField = false; // If it's part of a field or not. - public IceSpikePillar(Player player) { + public IceSpikePillar(final Player player) { super(player); - setFields(); + this.setFields(); - if (bPlayer.isOnCooldown("IceSpikePillar")) { + if (this.bPlayer.isOnCooldown("IceSpikePillar")) { return; } try { - double lowestDistance = range + 1; + double lowestDistance = this.range + 1; Entity closestEntity = null; - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), range)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(player.getLocation(), this.range)) { if (GeneralMethods.getDistanceFromLine(player.getLocation().getDirection(), player.getLocation(), entity.getLocation()) <= 2 && (entity instanceof LivingEntity) && (entity.getEntityId() != player.getEntityId())) { double distance = 0; if (player.getWorld().equals(entity.getWorld())) { @@ -76,33 +76,33 @@ public IceSpikePillar(Player player) { } if (closestEntity != null) { - Block tempTestingBlock = closestEntity.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); + final Block tempTestingBlock = closestEntity.getLocation().getBlock().getRelative(BlockFace.DOWN, 1); this.source_block = tempTestingBlock; } else { - this.source_block = WaterAbility.getIceSourceBlock(player, range); + this.source_block = WaterAbility.getIceSourceBlock(player, this.range); if (this.source_block == null) { return; } } - origin = source_block.getLocation(); - location = origin.clone(); + this.origin = this.source_block.getLocation(); + this.location = this.origin.clone(); } - catch (IllegalStateException e) { + catch (final IllegalStateException e) { return; } - if (height != 0) { - if (canInstantiate()) { - start(); - time = System.currentTimeMillis() - interval; - bPlayer.addCooldown("IceSpikePillar", cooldown); + if (this.height != 0) { + if (this.canInstantiate()) { + this.start(); + this.time = System.currentTimeMillis() - this.interval; + this.bPlayer.addCooldown("IceSpikePillar", this.cooldown); } } } - public IceSpikePillar(Player player, Location origin, int damage, Vector throwing, long aoecooldown) { + public IceSpikePillar(final Player player, final Location origin, final int damage, final Vector throwing, final long aoecooldown) { super(player); - setFields(); + this.setFields(); this.cooldown = aoecooldown; this.player = player; @@ -110,12 +110,12 @@ public IceSpikePillar(Player player, Location origin, int damage, Vector throwin this.damage = damage; this.thrownForce = throwing; this.location = origin.clone(); - this.source_block = location.getBlock(); + this.source_block = this.location.getBlock(); - if (isIcebendable(source_block)) { - if (canInstantiate()) { - start(); - time = System.currentTimeMillis() - interval; + if (this.isIcebendable(this.source_block)) { + if (this.canInstantiate()) { + this.start(); + this.time = System.currentTimeMillis() - this.interval; } } } @@ -133,9 +133,9 @@ private void setFields() { this.thrownForce = new Vector(0, getConfig().getDouble("Abilities.Water.IceSpike.Push"), 0); this.damaged = new ArrayList<>(); - this.interval = (long) (1000. / speed); - - if (bPlayer.isAvatarState()) { + this.interval = (long) (1000. / this.speed); + + if (this.bPlayer.isAvatarState()) { this.slowPower = getConfig().getInt("Abilities.Avatar.AvatarState.Water.IceSpike.SlowPower"); this.slowDuration = getConfig().getInt("Abilities.Avatar.AvatarState.Water.IceSpike.SlowDuration"); this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceSpike.Damage"); @@ -147,12 +147,12 @@ private void setFields() { /** * Reverts the block if it's part of IceSpike - * + * * @param block The Block * @return If the block was removed or not */ - public static boolean revertBlock(Block block) { - for (IceSpikePillar iceSpike : getAbilities(IceSpikePillar.class)) { + public static boolean revertBlock(final Block block) { + for (final IceSpikePillar iceSpike : getAbilities(IceSpikePillar.class)) { if (iceSpike.ice_blocks.containsKey(block)) { iceSpike.ice_blocks.get(block).revertBlock(); iceSpike.ice_blocks.remove(block); @@ -167,18 +167,18 @@ public static boolean revertBlock(Block block) { * enough space to form, if the source isn't a TempBlock, etc. */ private boolean canInstantiate() { - if (!isIcebendable(source_block.getType())) { + if (!this.isIcebendable(this.source_block.getType())) { return false; } Block b; - for (int i = 1; i <= height; i++) { - b = source_block.getWorld().getBlockAt(location.clone().add(direction.clone().multiply(i))); + for (int i = 1; i <= this.height; i++) { + b = this.source_block.getWorld().getBlockAt(this.location.clone().add(this.direction.clone().multiply(i))); if (b.getType() != Material.AIR) { return false; } - if (b.getX() == player.getEyeLocation().getBlock().getX() && b.getZ() == player.getEyeLocation().getBlock().getZ()) { + if (b.getX() == this.player.getEyeLocation().getBlock().getX() && b.getZ() == this.player.getEyeLocation().getBlock().getZ()) { return false; } } @@ -187,16 +187,16 @@ private boolean canInstantiate() { @Override public void progress() { - if (System.currentTimeMillis() - time >= interval) { - time = System.currentTimeMillis(); - if (progress < height) { - risePillar(); - removeTimestamp = System.currentTimeMillis(); + if (System.currentTimeMillis() - this.time >= this.interval) { + this.time = System.currentTimeMillis(); + if (this.progress < this.height) { + this.risePillar(); + this.removeTimestamp = System.currentTimeMillis(); } else { - //If it's time to remove - if (removeTimestamp != 0 && removeTimestamp + removeTimer <= System.currentTimeMillis()) { - if (!sinkPillar()) { - remove(); + // If it's time to remove. + if (this.removeTimestamp != 0 && this.removeTimestamp + this.removeTimer <= System.currentTimeMillis()) { + if (!this.sinkPillar()) { + this.remove(); return; } } @@ -206,48 +206,48 @@ public void progress() { /** * Makes the pillar rise by 1 block. - * + * * @return If the block was placed successfully. */ private boolean risePillar() { - progress++; - Block affectedBlock = location.clone().add(direction).getBlock(); - location = location.add(direction); + this.progress++; + final Block affectedBlock = this.location.clone().add(this.direction).getBlock(); + this.location = this.location.add(this.direction); - if (GeneralMethods.isRegionProtectedFromBuild(this, location)) { + if (GeneralMethods.isRegionProtectedFromBuild(this, this.location)) { return false; } - for (Entity en : GeneralMethods.getEntitiesAroundPoint(location, 1.4)) { - if (en instanceof LivingEntity && en != player && !damaged.contains((en))) { - LivingEntity le = (LivingEntity) en; - affect(le); + for (final Entity en : GeneralMethods.getEntitiesAroundPoint(this.location, 1.4)) { + if (en instanceof LivingEntity && en != this.player && !this.damaged.contains((en))) { + final LivingEntity le = (LivingEntity) en; + this.affect(le); } } - TempBlock b = new TempBlock(affectedBlock, Material.ICE, (byte) 0); - ice_blocks.put(affectedBlock, b); + final TempBlock b = new TempBlock(affectedBlock, Material.ICE, (byte) 0); + this.ice_blocks.put(affectedBlock, b); - if (!inField || new Random().nextInt((int) ((height + 1) * 1.5)) == 0) { - playIcebendingSound(source_block.getLocation()); + if (!this.inField || new Random().nextInt((int) ((this.height + 1) * 1.5)) == 0) { + playIcebendingSound(this.source_block.getLocation()); } return true; } - private void affect(LivingEntity entity) { - entity.setVelocity(thrownForce); - DamageHandler.damageEntity(entity, damage, this); - damaged.add(entity); + private void affect(final LivingEntity entity) { + entity.setVelocity(this.thrownForce); + DamageHandler.damageEntity(entity, this.damage, this); + this.damaged.add(entity); if (entity instanceof Player) { - if (bPlayer.canBeSlowed()) { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, slowDuration, slowPower); + if (this.bPlayer.canBeSlowed()) { + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, this.slowDuration, this.slowPower); new TempPotionEffect(entity, effect); - bPlayer.slow(slowCooldown); + this.bPlayer.slow(this.slowCooldown); } } else { - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, slowDuration, slowPower); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, this.slowDuration, this.slowPower); new TempPotionEffect(entity, effect); } AirAbility.breakBreathbendingHold(entity); @@ -255,17 +255,17 @@ private void affect(LivingEntity entity) { /** * The reverse of risePillar(). Makes the pillar sink - * + * * @return If the move should continue progressing. */ public boolean sinkPillar() { - Vector direction = this.direction.clone().multiply(-1); - if (ice_blocks.containsKey(location.getBlock())) { - ice_blocks.get(location.getBlock()).revertBlock(); - ice_blocks.remove(location.getBlock()); - location.add(direction); + final Vector direction = this.direction.clone().multiply(-1); + if (this.ice_blocks.containsKey(this.location.getBlock())) { + this.ice_blocks.get(this.location.getBlock()).revertBlock(); + this.ice_blocks.remove(this.location.getBlock()); + this.location.add(direction); - if (source_block.equals(location.getBlock())) { + if (this.source_block.equals(this.location.getBlock())) { return false; } } @@ -288,157 +288,157 @@ public boolean isHarmlessAbility() { } public int getHeight() { - return height; + return this.height; } - public void setHeight(int height) { + public void setHeight(final int height) { this.height = height; } public int getProgress() { - return progress; + return this.progress; } - public void setProgress(int progress) { + public void setProgress(final int progress) { this.progress = progress; } public int getSlowPower() { - return slowPower; + return this.slowPower; } - public void setSlowPower(int slowPower) { + public void setSlowPower(final int slowPower) { this.slowPower = slowPower; } public int getSlowDuration() { - return slowDuration; + return this.slowDuration; } - public void setSlowDuration(int slowDuration) { + public void setSlowDuration(final int slowDuration) { this.slowDuration = slowDuration; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getRemoveTimestamp() { - return removeTimestamp; + return this.removeTimestamp; } - public void setRemoveTimestamp(long removeTimestamp) { + public void setRemoveTimestamp(final long removeTimestamp) { this.removeTimestamp = removeTimestamp; } public long getRemoveTimer() { - return removeTimer; + return this.removeTimer; } - public void setRemoveTimer(long removeTimer) { + public void setRemoveTimer(final long removeTimer) { this.removeTimer = removeTimer; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public long getSlowCooldown() { - return slowCooldown; + return this.slowCooldown; } - public void setSlowCooldown(long slowCooldown) { + public void setSlowCooldown(final long slowCooldown) { this.slowCooldown = slowCooldown; } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } public double getSpeed() { - return speed; + return this.speed; } - public void setSpeed(double speed) { + public void setSpeed(final double speed) { this.speed = speed; } public Block getBlock() { - return source_block; + return this.source_block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.source_block = block; } public Location getOrigin() { - return origin; + return this.origin; } - public void setOrigin(Location origin) { + public void setOrigin(final Location origin) { this.origin = origin; } @Override public Location getLocation() { - return location; + return this.location; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public Vector getThrownForce() { - return thrownForce; + return this.thrownForce; } - public void setThrownForce(Vector thrownForce) { + public void setThrownForce(final Vector thrownForce) { this.thrownForce = thrownForce; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public Map getIceBlocks() { - return ice_blocks; + return this.ice_blocks; } public Block getBaseBlock() { - return base_block; + return this.base_block; } } diff --git a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillarField.java b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillarField.java index f9fa07f13..62275845a 100644 --- a/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillarField.java +++ b/src/com/projectkorra/projectkorra/waterbending/ice/IceSpikePillarField.java @@ -26,10 +26,10 @@ public class IceSpikePillarField extends IceAbility { private long cooldown; private Vector thrownForce; - public IceSpikePillarField(Player player) { + public IceSpikePillarField(final Player player) { super(player); - if (bPlayer.isOnCooldown("IceSpikePillarField")) { + if (this.bPlayer.isOnCooldown("IceSpikePillarField")) { return; } @@ -37,32 +37,30 @@ public IceSpikePillarField(Player player) { this.radius = getConfig().getDouble("Abilities.Water.IceSpike.Field.Radius"); this.cooldown = getConfig().getLong("Abilities.Water.IceSpike.Field.Cooldown"); this.thrownForce = new Vector(0, getConfig().getDouble("Abilities.Water.IceSpike.Field.Push"), 0); - - if (bPlayer.isAvatarState()) { + + if (this.bPlayer.isAvatarState()) { this.damage = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceSpike.Field.Damage"); this.radius = getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceSpike.Field.Radius"); this.thrownForce = new Vector(0, getConfig().getDouble("Abilities.Avatar.AvatarState.Water.IceSpike.Field.Push"), 0); } - - this.numberOfSpikes = (int) (((radius * 2) * (radius * 2)) / 16); - Random random = new Random(); - int locX = player.getLocation().getBlockX(); - int locY = player.getLocation().getBlockY(); - int locZ = player.getLocation().getBlockZ(); - List iceBlocks = new ArrayList(); + this.numberOfSpikes = (int) (((this.radius * 2) * (this.radius * 2)) / 16); + + final Random random = new Random(); + final int locX = player.getLocation().getBlockX(); + final int locY = player.getLocation().getBlockY(); + final int locZ = player.getLocation().getBlockZ(); + final List iceBlocks = new ArrayList(); - for (int x = (int) -(radius - 1); x <= (radius - 1); x++) { - for (int z = (int) -(radius - 1); z <= (radius - 1); z++) { + for (int x = (int) -(this.radius - 1); x <= (this.radius - 1); x++) { + for (int z = (int) -(this.radius - 1); z <= (this.radius - 1); z++) { for (int y = -1; y <= 1; y++) { - Block testBlock = player.getWorld().getBlockAt(locX + x, locY + y, locZ + z); + final Block testBlock = player.getWorld().getBlockAt(locX + x, locY + y, locZ + z); - if (WaterAbility.isIcebendable(player, testBlock.getType(), false) && testBlock.getRelative(BlockFace.UP).getType() == Material.AIR - && !(testBlock.getX() == player.getEyeLocation().getBlock().getX() && testBlock.getZ() == player.getEyeLocation().getBlock().getZ()) - || (TempBlock.isTempBlock(testBlock) && WaterAbility.isBendableWaterTempBlock(testBlock))) { + if (WaterAbility.isIcebendable(player, testBlock.getType(), false) && testBlock.getRelative(BlockFace.UP).getType() == Material.AIR && !(testBlock.getX() == player.getEyeLocation().getBlock().getX() && testBlock.getZ() == player.getEyeLocation().getBlock().getZ()) || (TempBlock.isTempBlock(testBlock) && WaterAbility.isBendableWaterTempBlock(testBlock))) { iceBlocks.add(testBlock); for (int i = 0; i < iceBlocks.size() / 2 + 1; i++) { - Random rand = new Random(); + final Random rand = new Random(); if (rand.nextInt(5) == 0) { playIcebendingSound(iceBlocks.get(i).getLocation()); } @@ -72,17 +70,17 @@ public IceSpikePillarField(Player player) { } } - List entities = GeneralMethods.getEntitiesAroundPoint(player.getLocation(), radius); - for (int i = 0; i < numberOfSpikes; i++) { + final List entities = GeneralMethods.getEntitiesAroundPoint(player.getLocation(), this.radius); + for (int i = 0; i < this.numberOfSpikes; i++) { if (iceBlocks.isEmpty()) { return; } Entity target = null; Block targetBlock = null; - for (Entity entity : entities) { + for (final Entity entity : entities) { if (entity instanceof LivingEntity && entity.getEntityId() != player.getEntityId()) { - for (Block block : iceBlocks) { + for (final Block block : iceBlocks) { if (block.getX() == entity.getLocation().getBlockX() && block.getZ() == entity.getLocation().getBlockZ()) { target = entity; targetBlock = block; @@ -101,10 +99,10 @@ public IceSpikePillarField(Player player) { } if (targetBlock.getRelative(BlockFace.UP).getType() != Material.ICE) { - - IceSpikePillar pillar = new IceSpikePillar(player, targetBlock.getLocation(), (int) damage, thrownForce, cooldown); + + final IceSpikePillar pillar = new IceSpikePillar(player, targetBlock.getLocation(), (int) this.damage, this.thrownForce, this.cooldown); pillar.inField = true; - bPlayer.addCooldown("IceSpikePillarField", cooldown); + this.bPlayer.addCooldown("IceSpikePillarField", this.cooldown); iceBlocks.remove(targetBlock); } } @@ -121,12 +119,12 @@ public void progress() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -140,39 +138,39 @@ public boolean isHarmlessAbility() { } public double getDamage() { - return damage; + return this.damage; } - public void setDamage(double damage) { + public void setDamage(final double damage) { this.damage = damage; } public double getRadius() { - return radius; + return this.radius; } - public void setRadius(double radius) { + public void setRadius(final double radius) { this.radius = radius; } public int getNumberOfSpikes() { - return numberOfSpikes; + return this.numberOfSpikes; } - public void setNumberOfSpikes(int numberOfSpikes) { + public void setNumberOfSpikes(final int numberOfSpikes) { this.numberOfSpikes = numberOfSpikes; } public Vector getThrownForce() { - return thrownForce; + return this.thrownForce; } - public void setThrownForce(Vector thrownForce) { + public void setThrownForce(final Vector thrownForce) { this.thrownForce = thrownForce; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/ice/PhaseChange.java b/src/com/projectkorra/projectkorra/waterbending/ice/PhaseChange.java index 5bb98d9b7..b17d074f0 100644 --- a/src/com/projectkorra/projectkorra/waterbending/ice/PhaseChange.java +++ b/src/com/projectkorra/projectkorra/waterbending/ice/PhaseChange.java @@ -41,20 +41,20 @@ public String toString() { } } - private List active_types = new ArrayList<>(); + private final List active_types = new ArrayList<>(); private static Map PLAYER_BY_BLOCK = new HashMap<>(); - private CopyOnWriteArrayList blocks = new CopyOnWriteArrayList<>(); - private Random r = new Random(); + private final CopyOnWriteArrayList blocks = new CopyOnWriteArrayList<>(); + private final Random r = new Random(); private int sourceRange = 8; - //Freeze Variables + // Freeze Variables. private long freezeCooldown = 500; private int freezeRadius = 3; private int depth = 1; private double controlRadius = 25; - //Melt Variables + // Melt Variables. private Location meltLoc; private long meltCooldown = 7000; private int meltRadius; @@ -62,144 +62,144 @@ public String toString() { private double meltSpeed = 8; private double meltTicks = 0; private boolean allowMeltFlow; - private CopyOnWriteArrayList melted_blocks = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList melted_blocks = new CopyOnWriteArrayList<>(); - public PhaseChange(Player player, PhaseChangeType type) { + public PhaseChange(final Player player, final PhaseChangeType type) { super(player); - startNewType(type); - start(); + this.startNewType(type); + this.start(); } @Override public void progress() { - if (!player.isOnline() || player.isDead()) { - remove(); + if (!this.player.isOnline() || this.player.isDead()) { + this.remove(); return; } - if (active_types.contains(PhaseChangeType.FREEZE)) { - if (blocks.isEmpty()) { - active_types.remove(PhaseChangeType.FREEZE); + if (this.active_types.contains(PhaseChangeType.FREEZE)) { + if (this.blocks.isEmpty()) { + this.active_types.remove(PhaseChangeType.FREEZE); return; } - for (TempBlock tb : blocks) { - if (tb.getLocation().getWorld() != player.getWorld()) { + for (final TempBlock tb : this.blocks) { + if (tb.getLocation().getWorld() != this.player.getWorld()) { tb.revertBlock(); - blocks.remove(tb); + this.blocks.remove(tb); PLAYER_BY_BLOCK.remove(tb); - } else if (tb.getLocation().distanceSquared(player.getLocation()) > (controlRadius * controlRadius)) { + } else if (tb.getLocation().distanceSquared(this.player.getLocation()) > (this.controlRadius * this.controlRadius)) { tb.revertBlock(); - blocks.remove(tb); + this.blocks.remove(tb); PLAYER_BY_BLOCK.remove(tb); } } } - if (active_types.contains(PhaseChangeType.MELT)) { - if (!player.isSneaking() || !bPlayer.canBend(this)) { - active_types.remove(PhaseChangeType.MELT); - bPlayer.addCooldown("PhaseChangeMelt", meltCooldown); - meltRadius = 1; - meltTicks = 0; + if (this.active_types.contains(PhaseChangeType.MELT)) { + if (!this.player.isSneaking() || !this.bPlayer.canBend(this)) { + this.active_types.remove(PhaseChangeType.MELT); + this.bPlayer.addCooldown("PhaseChangeMelt", this.meltCooldown); + this.meltRadius = 1; + this.meltTicks = 0; return; } - if (meltRadius >= meltMaxRadius) { - meltRadius = 1; + if (this.meltRadius >= this.meltMaxRadius) { + this.meltRadius = 1; } - Location l = GeneralMethods.getTargetedLocation(player, sourceRange); - resetMeltLocation(l); - meltArea(l, meltRadius); - } - - if (active_types.contains(PhaseChangeType.CUSTOM)) { - for (TempBlock tb : blocks) { - if (tb.getLocation().getWorld() != player.getWorld()) { + final Location l = GeneralMethods.getTargetedLocation(this.player, this.sourceRange); + this.resetMeltLocation(l); + this.meltArea(l, this.meltRadius); + } + + if (this.active_types.contains(PhaseChangeType.CUSTOM)) { + for (final TempBlock tb : this.blocks) { + if (tb.getLocation().getWorld() != this.player.getWorld()) { tb.revertBlock(); - blocks.remove(tb); + this.blocks.remove(tb); PLAYER_BY_BLOCK.remove(tb); - } else if (tb.getLocation().distanceSquared(player.getLocation()) > (controlRadius * controlRadius)) { + } else if (tb.getLocation().distanceSquared(this.player.getLocation()) > (this.controlRadius * this.controlRadius)) { tb.revertBlock(); - blocks.remove(tb); + this.blocks.remove(tb); PLAYER_BY_BLOCK.remove(tb); } } } - if (active_types.isEmpty()) { - remove(); + if (this.active_types.isEmpty()) { + this.remove(); } } - public void startNewType(PhaseChangeType type) { + public void startNewType(final PhaseChangeType type) { if (type == PhaseChangeType.MELT) { - if (bPlayer.isOnCooldown("PhaseChangeMelt")) { + if (this.bPlayer.isOnCooldown("PhaseChangeMelt")) { return; } } - active_types.add(type); - setFields(type); + this.active_types.add(type); + this.setFields(type); } - public void setFields(PhaseChangeType type) { + public void setFields(final PhaseChangeType type) { int night = 1; - if (isNight(player.getWorld())) { - night = (int) Math.round(getNightFactor()); + if (isNight(this.player.getWorld())) { + night = (int) Math.round(this.getNightFactor()); } - sourceRange = night * getConfig().getInt("Abilities.Water.PhaseChange.SourceRange"); - + this.sourceRange = night * getConfig().getInt("Abilities.Water.PhaseChange.SourceRange"); + switch (type) { case FREEZE: - depth = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Depth"); - controlRadius = night * getConfig().getDouble("Abilities.Water.PhaseChange.Freeze.ControlRadius"); - freezeCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Freeze.Cooldown"); - freezeRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Radius"); + this.depth = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Depth"); + this.controlRadius = night * getConfig().getDouble("Abilities.Water.PhaseChange.Freeze.ControlRadius"); + this.freezeCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Freeze.Cooldown"); + this.freezeRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Radius"); - freezeArea(GeneralMethods.getTargetedLocation(player, sourceRange)); + this.freezeArea(GeneralMethods.getTargetedLocation(this.player, this.sourceRange)); case MELT: - meltRadius = 1; - meltCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Melt.Cooldown"); - meltSpeed = getConfig().getDouble("Abilities.Water.PhaseChange.Melt.Speed") * night; - meltMaxRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Melt.Radius"); - allowMeltFlow = getConfig().getBoolean("Abilities.Water.PhaseChange.Melt.AllowFlow"); + this.meltRadius = 1; + this.meltCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Melt.Cooldown"); + this.meltSpeed = getConfig().getDouble("Abilities.Water.PhaseChange.Melt.Speed") * night; + this.meltMaxRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Melt.Radius"); + this.allowMeltFlow = getConfig().getBoolean("Abilities.Water.PhaseChange.Melt.AllowFlow"); case CUSTOM: - depth = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Depth"); - controlRadius = night * getConfig().getDouble("Abilities.Water.PhaseChange.Freeze.ControlRadius"); - freezeCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Freeze.Cooldown"); - freezeRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Radius"); - - meltRadius = 1; - meltCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Melt.Cooldown"); - meltSpeed = getConfig().getDouble("Abilities.Water.PhaseChange.Melt.Speed") * night; - meltMaxRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Melt.Radius"); - allowMeltFlow = getConfig().getBoolean("Abilities.Water.PhaseChange.Melt.AllowFlow"); - } - } - - public void resetMeltLocation(Location loc) { - if (meltLoc == null) { - meltLoc = loc; + this.depth = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Depth"); + this.controlRadius = night * getConfig().getDouble("Abilities.Water.PhaseChange.Freeze.ControlRadius"); + this.freezeCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Freeze.Cooldown"); + this.freezeRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Freeze.Radius"); + + this.meltRadius = 1; + this.meltCooldown = getConfig().getLong("Abilities.Water.PhaseChange.Melt.Cooldown"); + this.meltSpeed = getConfig().getDouble("Abilities.Water.PhaseChange.Melt.Speed") * night; + this.meltMaxRadius = night * getConfig().getInt("Abilities.Water.PhaseChange.Melt.Radius"); + this.allowMeltFlow = getConfig().getBoolean("Abilities.Water.PhaseChange.Melt.AllowFlow"); + } + } + + public void resetMeltLocation(final Location loc) { + if (this.meltLoc == null) { + this.meltLoc = loc; return; } - if (meltLoc.distance(loc) < 1) { + if (this.meltLoc.distance(loc) < 1) { return; } - if (!loc.equals(meltLoc)) { - meltLoc = loc; - meltRadius = 1; + if (!loc.equals(this.meltLoc)) { + this.meltLoc = loc; + this.meltRadius = 1; } } - public ArrayList getBlockFacesTowardsPlayer(Location center) { - ArrayList faces = new ArrayList<>(); - Vector toPlayer = GeneralMethods.getDirection(center, player.getEyeLocation()); - double[] vars = { toPlayer.getX(), toPlayer.getY(), toPlayer.getZ() }; + public ArrayList getBlockFacesTowardsPlayer(final Location center) { + final ArrayList faces = new ArrayList<>(); + final Vector toPlayer = GeneralMethods.getDirection(center, this.player.getEyeLocation()); + final double[] vars = { toPlayer.getX(), toPlayer.getY(), toPlayer.getZ() }; for (int i = 0; i < 3; i++) { if (vars[i] != 0) { - faces.add(getBlockFaceFromValue(i, vars[i])); + faces.add(GeneralMethods.getBlockFaceFromValue(i, vars[i])); } else { continue; } @@ -207,37 +207,12 @@ public ArrayList getBlockFacesTowardsPlayer(Location center) { return faces; } - private BlockFace getBlockFaceFromValue(int xyz, double value) { - switch (xyz) { - case 0: - if (value > 0) { - return BlockFace.EAST; - } else if (value < 0) { - return BlockFace.WEST; - } - case 1: - if (value > 0) { - return BlockFace.UP; - } else if (value < 0) { - return BlockFace.DOWN; - } - case 2: - if (value > 0) { - return BlockFace.SOUTH; - } else if (value < 0) { - return BlockFace.NORTH; - } - default: - return null; - } - } - - public ArrayList getBlocksToFreeze(Location center, int radius) { - ArrayList blocks = new ArrayList<>(); - for (Location l : GeneralMethods.getCircle(center, radius, depth, false, true, 0)) { - Block b = l.getBlock(); - loop: for (int i = 1; i <= depth; i++) { - for (BlockFace face : getBlockFacesTowardsPlayer(center)) { + public ArrayList getBlocksToFreeze(final Location center, final int radius) { + final ArrayList blocks = new ArrayList<>(); + for (final Location l : GeneralMethods.getCircle(center, radius, this.depth, false, true, 0)) { + final Block b = l.getBlock(); + loop: for (int i = 1; i <= this.depth; i++) { + for (final BlockFace face : this.getBlockFacesTowardsPlayer(center)) { if (b.getRelative(face, i).getType() == Material.AIR) { blocks.add(b); break loop; @@ -248,51 +223,51 @@ public ArrayList getBlocksToFreeze(Location center, int radius) { return blocks; } - public void freezeArea(Location center, int radius, PhaseChangeType type) { + public void freezeArea(final Location center, final int radius, final PhaseChangeType type) { if (type == PhaseChangeType.FREEZE) { - if (bPlayer.isOnCooldown("PhaseChangeFreeze")) { + if (this.bPlayer.isOnCooldown("PhaseChangeFreeze")) { return; } } - if (depth > 1) { - center.subtract(0, depth - 1, 0); + if (this.depth > 1) { + center.subtract(0, this.depth - 1, 0); } - ArrayList toFreeze = getBlocksToFreeze(center, radius); - for (Block b : toFreeze) { - freeze(b); + final ArrayList toFreeze = this.getBlocksToFreeze(center, radius); + for (final Block b : toFreeze) { + this.freeze(b); } - if (!blocks.isEmpty()) { + if (!this.blocks.isEmpty()) { if (type == PhaseChangeType.FREEZE) { - bPlayer.addCooldown("PhaseChangeFreeze", freezeCooldown); + this.bPlayer.addCooldown("PhaseChangeFreeze", this.freezeCooldown); } } } - public void freezeArea(Location center, int radius) { - freezeArea(center, radius, PhaseChangeType.FREEZE); + public void freezeArea(final Location center, final int radius) { + this.freezeArea(center, radius, PhaseChangeType.FREEZE); } - public void freezeArea(Location center, PhaseChangeType type) { - freezeArea(center, freezeRadius, type); + public void freezeArea(final Location center, final PhaseChangeType type) { + this.freezeArea(center, this.freezeRadius, type); } - public void freezeArea(Location center) { - freezeArea(center, freezeRadius); + public void freezeArea(final Location center) { + this.freezeArea(center, this.freezeRadius); } - public void freeze(Block b) { - if (b.getWorld() != player.getWorld()) { + public void freeze(final Block b) { + if (b.getWorld() != this.player.getWorld()) { return; } - if (b.getLocation().distanceSquared(player.getLocation()) > controlRadius * controlRadius) { + if (b.getLocation().distanceSquared(this.player.getLocation()) > this.controlRadius * this.controlRadius) { return; } - if (GeneralMethods.isRegionProtectedFromBuild(player, b.getLocation())) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, b.getLocation())) { return; } @@ -304,8 +279,8 @@ public void freeze(Block b) { if (TempBlock.isTempBlock(b)) { tb = TempBlock.get(b); - if (melted_blocks.contains(tb.getBlock())) { - melted_blocks.remove(tb.getBlock()); + if (this.melted_blocks.contains(tb.getBlock())) { + this.melted_blocks.remove(tb.getBlock()); tb.revertBlock(); tb.setType(Material.ICE); } @@ -313,47 +288,46 @@ public void freeze(Block b) { if (tb == null) { tb = new TempBlock(b, Material.ICE, (byte) 0); } - blocks.add(tb); - PLAYER_BY_BLOCK.put(tb, player); + this.blocks.add(tb); + PLAYER_BY_BLOCK.put(tb, this.player); playIcebendingSound(b.getLocation()); } - public void meltArea(Location center, int radius) { - List ice = new ArrayList(); - for (Location l : GeneralMethods.getCircle(center, radius, 3, true, true, 0)) { + public void meltArea(final Location center, final int radius) { + final List ice = new ArrayList(); + for (final Location l : GeneralMethods.getCircle(center, radius, 3, true, true, 0)) { if (isIce(l.getBlock()) || isSnow(l.getBlock())) { ice.add(l.getBlock()); - + } } - - meltTicks += meltSpeed / 20; - for (int i = 0; i < meltTicks % (meltSpeed); i++) { + this.meltTicks += this.meltSpeed / 20; + + for (int i = 0; i < this.meltTicks % (this.meltSpeed); i++) { if (ice.size() == 0) { - meltRadius++; + this.meltRadius++; return; } - - Block b = ice.get(r.nextInt(ice.size())); - melt(b); + + final Block b = ice.get(this.r.nextInt(ice.size())); + this.melt(b); ice.remove(b); } } - public void meltArea(Location center) { - meltArea(center, meltRadius); + public void meltArea(final Location center) { + this.meltArea(center, this.meltRadius); } - @SuppressWarnings("deprecation") - public void melt(Block b) { - if (b.getWorld() != player.getWorld()) { + public void melt(final Block b) { + if (b.getWorld() != this.player.getWorld()) { return; } - if (b.getLocation().distanceSquared(player.getLocation()) > controlRadius * controlRadius) { + if (b.getLocation().distanceSquared(this.player.getLocation()) > this.controlRadius * this.controlRadius) { return; } - if (GeneralMethods.isRegionProtectedFromBuild(player, b.getLocation())) { + if (GeneralMethods.isRegionProtectedFromBuild(this.player, b.getLocation())) { return; } if (SurgeWall.getWallBlocks().containsKey(b)) { @@ -379,7 +353,7 @@ public void melt(Block b) { return; } if (TempBlock.isTempBlock(b)) { - TempBlock tb = TempBlock.get(b); + final TempBlock tb = TempBlock.get(b); if (!isIce(tb.getBlock()) && !isSnow(tb.getBlock())) { return; @@ -388,47 +362,47 @@ public void melt(Block b) { if (PLAYER_BY_BLOCK.containsKey(tb)) { thaw(tb); } - + if (b.getType() == Material.SNOW) { if (b.getData() == 0) { tb.revertBlock(); new TempBlock(b, Material.AIR, (byte) 0).setRevertTime(120 * 1000L); } else { - byte data = b.getData(); + final byte data = b.getData(); tb.revertBlock(); new TempBlock(b, Material.SNOW, (byte) (data - 1)).setRevertTime(120 * 1000L); } } } else if (isWater(b)) { - //Figure out what to do here also + // Figure out what to do here also. } else if (isIce(b)) { - Material m = allowMeltFlow ? Material.WATER : Material.STATIONARY_WATER; + final Material m = this.allowMeltFlow ? Material.WATER : Material.STATIONARY_WATER; b.setType(m); - melted_blocks.add(b); + this.melted_blocks.add(b); } else if (b.getType() == Material.SNOW_BLOCK || b.getType() == Material.SNOW) { if (b.getData() == 0) { new TempBlock(b, Material.AIR, (byte) 0).setRevertTime(120 * 1000L); } else { new TempBlock(b, Material.SNOW, (byte) (b.getData() - 1)).setRevertTime(120 * 1000L); } - - melted_blocks.add(b); + + this.melted_blocks.add(b); } playWaterbendingSound(b.getLocation()); } /** * Only works with PhaseChange frozen blocks! - * + * * @param tb TempBlock being thawed * @return true when it is thawed successfully */ - public static boolean thaw(TempBlock tb) { + public static boolean thaw(final TempBlock tb) { if (!PLAYER_BY_BLOCK.containsKey(tb)) { return false; } else { - Player p = PLAYER_BY_BLOCK.get(tb); - PhaseChange pc = getAbility(p, PhaseChange.class); + final Player p = PLAYER_BY_BLOCK.get(tb); + final PhaseChange pc = getAbility(p, PhaseChange.class); if (pc == null) { return false; } @@ -444,15 +418,15 @@ public static boolean thaw(TempBlock tb) { /** * Only works if the block is a {@link TempBlock} and PhaseChange frozen! - * + * * @param b Block being thawed * @return false if not a {@link TempBlock} */ - public static boolean thaw(Block b) { + public static boolean thaw(final Block b) { if (!TempBlock.isTempBlock(b)) { return false; } - TempBlock tb = TempBlock.get(b); + final TempBlock tb = TempBlock.get(b); return thaw(tb); } @@ -461,48 +435,48 @@ public static Map getFrozenBlocksMap() { } public static List getFrozenBlocksAsTempBlock() { - List list = new ArrayList<>(); + final List list = new ArrayList<>(); list.addAll(PLAYER_BY_BLOCK.keySet()); return list; } public static List getFrozenBlocksAsBlock() { - List list = new ArrayList<>(); - for (TempBlock tb : PLAYER_BY_BLOCK.keySet()) { - Block b = tb.getBlock(); + final List list = new ArrayList<>(); + for (final TempBlock tb : PLAYER_BY_BLOCK.keySet()) { + final Block b = tb.getBlock(); list.add(b); } return list; } public void revertFrozenBlocks() { - if (active_types.contains(PhaseChangeType.FREEZE)) { - for (TempBlock tb : blocks) { + if (this.active_types.contains(PhaseChangeType.FREEZE)) { + for (final TempBlock tb : this.blocks) { PLAYER_BY_BLOCK.remove(tb); tb.revertBlock(); } - blocks.clear(); + this.blocks.clear(); } } public void revertMeltedBlocks() { - if (active_types.contains(PhaseChangeType.MELT)) { - for (Block b : melted_blocks) { + if (this.active_types.contains(PhaseChangeType.MELT)) { + for (final Block b : this.melted_blocks) { if (TempBlock.isTempBlock(b)) { TempBlock.get(b).revertBlock(); } else { b.setType(Material.ICE); } } - melted_blocks.clear(); + this.melted_blocks.clear(); } } @Override public void remove() { super.remove(); - revertFrozenBlocks(); - revertMeltedBlocks(); + this.revertFrozenBlocks(); + this.revertMeltedBlocks(); } @Override @@ -531,42 +505,42 @@ public Location getLocation() { } public int getDepth() { - return depth; + return this.depth; } - public void setDepth(int value) { - depth = value; + public void setDepth(final int value) { + this.depth = value; } public int getSourceRange() { - return sourceRange; + return this.sourceRange; } - public void setSourceRange(int value) { - sourceRange = value; + public void setSourceRange(final int value) { + this.sourceRange = value; } public double getFreezeControlRadius() { - return controlRadius; + return this.controlRadius; } public int getMeltRadius() { - return meltRadius; + return this.meltRadius; } - public void setFreezeControlRadius(int value) { - controlRadius = value; + public void setFreezeControlRadius(final int value) { + this.controlRadius = value; } public CopyOnWriteArrayList getFrozenBlocks() { - return blocks; + return this.blocks; } public CopyOnWriteArrayList getMeltedBlocks() { - return melted_blocks; + return this.melted_blocks; } public List getActiveTypes() { - return active_types; + return this.active_types; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArms.java b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArms.java index 03556757a..b78554933 100644 --- a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArms.java +++ b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArms.java @@ -2,9 +2,9 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import java.util.Set; import org.bukkit.ChatColor; import org.bukkit.Location; @@ -36,12 +36,11 @@ public static enum Arm { RIGHT, LEFT; } - private static final Map BLOCK_REVERT_TIMES = new ConcurrentHashMap(); private static final Integer[] UNBREAKABLES = { 7, 10, 11, 49, 54, 90, 119, 120, 130, 146 }; private boolean cooldownLeft; private boolean cooldownRight; - private boolean fullSource; // used to determine whip length in WhaterArmsWhip + private boolean fullSource; // used to determine whip length in WaterArmsWhip. private boolean leftArmConsumed; private boolean rightArmConsumed; private boolean canUsePlantSource; @@ -61,8 +60,10 @@ public static enum Arm { private World world; private String sneakMsg; private Arm activeArm; + private List right, left; + private Set external; - public WaterArms(Player player) { + public WaterArms(final Player player) { super(player); this.fullSource = true; @@ -85,8 +86,11 @@ public WaterArms(Player player) { this.lastClickTime = 0; this.world = player.getWorld(); this.activeArm = Arm.RIGHT; + this.right = new ArrayList<>(); + this.left = new ArrayList<>(); + this.external = new HashSet<>(); - WaterArms oldArms = getAbility(player, WaterArms.class); + final WaterArms oldArms = getAbility(player, WaterArms.class); if (oldArms != null) { if (player.isSneaking()) { @@ -114,13 +118,13 @@ public WaterArms(Player player) { } break; case 4: - if (player.hasPermission("bending.ability.WaterArms.Freeze") && bPlayer.canIcebend()) { + if (player.hasPermission("bending.ability.WaterArms.Freeze") && this.bPlayer.canIcebend()) { new WaterArmsFreeze(player); } break; case 5: if (player.hasPermission("bending.ability.WaterArms.Spear")) { - if (bPlayer.canIcebend()) { + if (this.bPlayer.canIcebend()) { new WaterArmsSpear(player, true); } else { new WaterArmsSpear(player, false); @@ -134,32 +138,32 @@ public WaterArms(Player player) { return; } - if (bPlayer.canBend(this) && prepare()) { - start(); + if (this.bPlayer.canBend(this) && this.prepare()) { + this.start(); MultiAbilityManager.bindMultiAbility(player, "WaterArms"); - if (ChatColor.stripColor(bPlayer.getBoundAbilityName()) == null) { - remove(); + if (ChatColor.stripColor(this.bPlayer.getBoundAbilityName()) == null) { + this.remove(); return; } } } private boolean prepare() { - Block sourceBlock = getWaterSourceBlock(player, sourceGrabRange, canUsePlantSource); + final Block sourceBlock = getWaterSourceBlock(this.player, this.sourceGrabRange, this.canUsePlantSource); if (sourceBlock != null) { - + if (isPlant(sourceBlock) || isSnow(sourceBlock)) { - new PlantRegrowth(player, sourceBlock); + new PlantRegrowth(this.player, sourceBlock); sourceBlock.setType(Material.AIR); - fullSource = false; - } - + this.fullSource = false; + } + ParticleEffect.LARGE_SMOKE.display(sourceBlock.getLocation().clone().add(0.5, 0.5, 0.5), 0, 0, 0, 0F, 4); return true; - } else if (WaterReturn.hasWaterBottle(player)) { - WaterReturn.emptyWaterBottle(player); - fullSource = false; + } else if (WaterReturn.hasWaterBottle(this.player)) { + WaterReturn.emptyWaterBottle(this.player); + this.fullSource = false; return true; } return false; @@ -167,189 +171,207 @@ private boolean prepare() { @Override public void progress() { - if (!world.equals(player.getWorld()) || !bPlayer.canBendIgnoreBindsCooldowns(this) || !bPlayer.hasElement(Element.WATER)) { - remove(); + if (!this.world.equals(this.player.getWorld()) || !this.bPlayer.canBendIgnoreBindsCooldowns(this) || !this.bPlayer.hasElement(Element.WATER)) { + this.remove(); return; - } else if (!bPlayer.isToggled()) { - remove(); + } else if (!this.bPlayer.isToggled()) { + this.remove(); return; - } else if (!MultiAbilityManager.hasMultiAbilityBound(player, "WaterArms")) { - remove(); + } else if (!MultiAbilityManager.hasMultiAbilityBound(this.player, "WaterArms")) { + this.remove(); return; - } else if (maxPunches == 0 || maxUses == 0 || maxIceBlasts == 0 || (leftArmConsumed && rightArmConsumed)) { - remove(); + } else if (this.maxPunches == 0 || this.maxUses == 0 || this.maxIceBlasts == 0 || (this.leftArmConsumed && this.rightArmConsumed)) { + this.remove(); return; } - selectedSlot = player.getInventory().getHeldItemSlot(); - displayRightArm(); - displayLeftArm(); + this.selectedSlot = this.player.getInventory().getHeldItemSlot(); + this.displayRightArm(); + this.displayLeftArm(); - if (lightningEnabled) { - checkIfZapped(); + if (this.lightningEnabled) { + this.checkIfZapped(); } } - private boolean canPlaceBlock(Block block) { - if (!isTransparent(player, block) && !(isWater(block) && TempBlock.isTempBlock(block))) { - return false; + private boolean canPlaceBlock(final Block block) { + if (TempBlock.isTempBlock(block)) { + if (this.external.contains(TempBlock.get(block))) { + return false; + } } - return true; + + return isWaterbendable(block.getType()) || isIce(block) || isWater(block) || block.getType() == Material.AIR; } /** * Displays the right arm. Returns false if the arm cannot be fully * displayed. - * + * * @return false If arm cannot be fully displayed */ public boolean displayRightArm() { - if (rightArmConsumed) { + final List newBlocks = new ArrayList<>(); + if (this.rightArmConsumed) { return false; } - Location r1 = GeneralMethods.getRightSide(player.getLocation(), 1).add(0, 1.5, 0); - if (!canPlaceBlock(r1.getBlock())) { + final Location r1 = GeneralMethods.getRightSide(this.player.getLocation(), 1).add(0, 1.5, 0); + if (!this.canPlaceBlock(r1.getBlock())) { + this.right.clear(); return false; } - if (!(getRightHandPos().getBlock().getLocation().equals(r1.getBlock().getLocation()))) { - new TempBlock(r1.getBlock(), Material.STATIONARY_WATER, (byte) 5); - BLOCK_REVERT_TIMES.put(r1.getBlock(), System.currentTimeMillis() + 1); + if (!(this.getRightHandPos().getBlock().getLocation().equals(r1.getBlock().getLocation()))) { + this.addBlock(r1.getBlock(), Material.STATIONARY_WATER, (byte) 5, 100); + newBlocks.add(r1.getBlock()); } - Location r2 = GeneralMethods.getRightSide(player.getLocation(), 2).add(0, 1.5, 0); - if (!canPlaceBlock(r2.getBlock())) { + final Location r2 = GeneralMethods.getRightSide(this.player.getLocation(), 2).add(0, 1.5, 0); + if (!this.canPlaceBlock(r2.getBlock()) || !this.canPlaceBlock(r1.getBlock())) { + this.right.clear(); + this.right.addAll(newBlocks); return false; } - new TempBlock(r2.getBlock(), Material.STATIONARY_WATER, (byte) 8); - BLOCK_REVERT_TIMES.put(r2.getBlock(), 0L); + this.addBlock(r2.getBlock(), Material.STATIONARY_WATER, (byte) 8, 100); + newBlocks.add(r2.getBlock()); - for (int j = 0; j <= initLength; j++) { - Location r3 = r2.clone().toVector().add(player.getLocation().clone().getDirection().multiply(j)).toLocation(player.getWorld()); - if (!canPlaceBlock(r3.getBlock())) { - if (selectedSlot == freezeSlot && r3.getBlock().getType().equals(Material.ICE)) { - continue; - } + for (int j = 1; j <= this.initLength; j++) { + final Location r3 = r2.clone().toVector().add(this.player.getLocation().clone().getDirection().multiply(j)).toLocation(this.player.getWorld()); + if (!this.canPlaceBlock(r3.getBlock()) || !this.canPlaceBlock(r2.getBlock()) || !this.canPlaceBlock(r1.getBlock())) { + this.right.clear(); + this.right.addAll(newBlocks); return false; } - if (j >= 1 && selectedSlot == freezeSlot && bPlayer.canIcebend()) { - new TempBlock(r3.getBlock(), Material.ICE, (byte) 0); - BLOCK_REVERT_TIMES.put(r3.getBlock(), 0L); + newBlocks.add(r3.getBlock()); + if (j >= 1 && this.selectedSlot == this.freezeSlot && this.bPlayer.canIcebend()) { + this.addBlock(r3.getBlock(), Material.ICE, (byte) 0, 100); } else { - new TempBlock(r3.getBlock(), Material.STATIONARY_WATER, (byte) 8); - BLOCK_REVERT_TIMES.put(r3.getBlock(), 0L); + this.addBlock(r3.getBlock(), Material.STATIONARY_WATER, (byte) 8, 100); } } + this.right.clear(); + this.right.addAll(newBlocks); + return true; } /** * Displays the left arm. Returns false if the arm cannot be fully * displayed. - * + * * @return false If the arm cannot be fully displayed. */ public boolean displayLeftArm() { - if (leftArmConsumed) { + final List newBlocks = new ArrayList<>(); + if (this.leftArmConsumed) { return false; } - Location l1 = GeneralMethods.getLeftSide(player.getLocation(), 1).add(0, 1.5, 0); - if (!canPlaceBlock(l1.getBlock())) { + final Location l1 = GeneralMethods.getLeftSide(this.player.getLocation(), 1).add(0, 1.5, 0); + if (!this.canPlaceBlock(l1.getBlock())) { + this.left.clear(); return false; } - if (!(getLeftHandPos().getBlock().getLocation().equals(l1.getBlock().getLocation()))) { - new TempBlock(l1.getBlock(), Material.STATIONARY_WATER, (byte) 5); - BLOCK_REVERT_TIMES.put(l1.getBlock(), 0L); + if (!(this.getLeftHandPos().getBlock().getLocation().equals(l1.getBlock().getLocation()))) { + this.addBlock(l1.getBlock(), Material.STATIONARY_WATER, (byte) 5, 100); + newBlocks.add(l1.getBlock()); } - Location l2 = GeneralMethods.getLeftSide(player.getLocation(), 2).add(0, 1.5, 0); - if (!canPlaceBlock(l2.getBlock())) { + final Location l2 = GeneralMethods.getLeftSide(this.player.getLocation(), 2).add(0, 1.5, 0); + if (!this.canPlaceBlock(l2.getBlock()) || !this.canPlaceBlock(l1.getBlock())) { + this.left.clear(); + this.left.addAll(newBlocks); return false; } - new TempBlock(l2.getBlock(), Material.STATIONARY_WATER, (byte) 8); - BLOCK_REVERT_TIMES.put(l2.getBlock(), System.currentTimeMillis() + 1); + this.addBlock(l2.getBlock(), Material.STATIONARY_WATER, (byte) 8, 100); + newBlocks.add(l2.getBlock()); - for (int j = 0; j <= initLength; j++) { - Location l3 = l2.clone().toVector().add(player.getLocation().clone().getDirection().multiply(j)).toLocation(player.getWorld()); - if (!canPlaceBlock(l3.getBlock())) { - if (selectedSlot == freezeSlot && l3.getBlock().getType().equals(Material.ICE)) { - continue; - } + for (int j = 1; j <= this.initLength; j++) { + final Location l3 = l2.clone().toVector().add(this.player.getLocation().clone().getDirection().multiply(j)).toLocation(this.player.getWorld()); + if (!this.canPlaceBlock(l3.getBlock()) || !this.canPlaceBlock(l2.getBlock()) || !this.canPlaceBlock(l1.getBlock())) { + this.left.clear(); + this.left.addAll(newBlocks); return false; } - if (j >= 1 && selectedSlot == freezeSlot && bPlayer.canIcebend()) { - new TempBlock(l3.getBlock(), Material.ICE, (byte) 0); - BLOCK_REVERT_TIMES.put(l3.getBlock(), System.currentTimeMillis() + 1); + newBlocks.add(l3.getBlock()); + if (j >= 1 && this.selectedSlot == this.freezeSlot && this.bPlayer.canIcebend()) { + this.addBlock(l3.getBlock(), Material.ICE, (byte) 0, 100); } else { - new TempBlock(l3.getBlock(), Material.STATIONARY_WATER, (byte) 8); - BLOCK_REVERT_TIMES.put(l3.getBlock(), System.currentTimeMillis() + 1); + this.addBlock(l3.getBlock(), Material.STATIONARY_WATER, (byte) 8, 100); } } + this.left.clear(); + this.left.addAll(newBlocks); + return true; } + public void addBlock(final Block b, final Material m, final byte i, final long revertTime) { + if (TempBlock.isTempBlock(b)) { + final TempBlock tb = TempBlock.get(b); + + if (this.right.contains(b) || this.left.contains(b)) { + tb.setType(m, i); + tb.setRevertTime(revertTime); + } else { + this.external.add(tb); + } + } else { + new TempBlock(b, m, i).setRevertTime(revertTime); + } + } + /** * Calculate roughly where the player's right hand is. - * + * * @return location of right hand */ private Location getRightHandPos() { - return GeneralMethods.getRightSide(player.getLocation(), .34).add(0, 1.5, 0); + return GeneralMethods.getRightSide(this.player.getLocation(), .34).add(0, 1.5, 0); } /** * Calculate roughly where the player's left hand is. - * + * * @return location of left hand */ private Location getLeftHandPos() { - return GeneralMethods.getLeftSide(player.getLocation(), .34).add(0, 1.5, 0); + return GeneralMethods.getLeftSide(this.player.getLocation(), .34).add(0, 1.5, 0); } /** * Returns the location of the tip of the right arm, assuming it is fully * extended. Use the displayRightArm() check to see if it is fully extended. - * + * * @return location of the tip of the right arm */ public Location getRightArmEnd() { - Location r1 = GeneralMethods.getRightSide(player.getLocation(), 2).add(0, 1.5, 0); - return r1.clone().add(player.getLocation().getDirection().normalize().multiply(initLength)); + final Location r1 = GeneralMethods.getRightSide(this.player.getLocation(), 2).add(0, 1.5, 0); + return r1.clone().add(this.player.getLocation().getDirection().normalize().multiply(this.initLength)); } /** * Returns the location of the tip of the left arm assuming it is fully * extended. Use the displayLeftArm() check to see if it is fully extended. - * + * * @return location of the tip of the left arm */ public Location getLeftArmEnd() { - Location l1 = GeneralMethods.getLeftSide(player.getLocation(), 2).add(0, 1.5, 0); - return l1.clone().add(player.getLocation().getDirection().normalize().multiply(initLength)); + final Location l1 = GeneralMethods.getLeftSide(this.player.getLocation(), 2).add(0, 1.5, 0); + return l1.clone().add(this.player.getLocation().getDirection().normalize().multiply(this.initLength)); } - private static void progressRevert(boolean ignoreTime) { - for (Block block : BLOCK_REVERT_TIMES.keySet()) { - long time = BLOCK_REVERT_TIMES.get(block); - if (System.currentTimeMillis() > time || ignoreTime) { - if (TempBlock.isTempBlock(block)) { - TempBlock.revertBlock(block, Material.AIR); - } - BLOCK_REVERT_TIMES.remove(block); - } - } - - for (Block block : WaterArmsSpear.getIceBlocks().keySet()) { - long time = WaterArmsSpear.getIceBlocks().get(block); + private static void progressRevert(final boolean ignoreTime) { + for (final Block block : WaterArmsSpear.getIceBlocks().keySet()) { + final long time = WaterArmsSpear.getIceBlocks().get(block); if (System.currentTimeMillis() > time || ignoreTime) { if (TempBlock.isTempBlock(block)) { TempBlock.revertBlock(block, Material.AIR); @@ -360,18 +382,20 @@ private static void progressRevert(boolean ignoreTime) { } private void checkIfZapped() { - for (Lightning lightning : getAbilities(Lightning.class)) { - for (Lightning.Arc arc : lightning.getArcs()) { - for (Block arm : BLOCK_REVERT_TIMES.keySet()) { - for (Location loc : arc.getPoints()) { + final List blocks = new ArrayList<>(this.right); + blocks.addAll(this.left); + for (final Lightning lightning : getAbilities(Lightning.class)) { + for (final Lightning.Arc arc : lightning.getArcs()) { + for (final Block arm : blocks) { + for (final Location loc : arc.getPoints()) { if (arm.getLocation().getWorld().equals(loc.getWorld()) && loc.distance(arm.getLocation()) <= 2.5) { - for (Location l1 : getOffsetLocations(4, arm.getLocation(), 1.25)) { + for (final Location l1 : getOffsetLocations(4, arm.getLocation(), 1.25)) { FireAbility.playLightningbendingParticle(l1); } - if (lightningKill) { - DamageHandler.damageEntity(player, 60D, lightning); + if (this.lightningKill) { + DamageHandler.damageEntity(this.player, 60D, lightning); } else { - DamageHandler.damageEntity(player, lightningDamage, lightning); + DamageHandler.damageEntity(this.player, this.lightningDamage, lightning); } } } @@ -380,8 +404,8 @@ private void checkIfZapped() { } } - private static List getOffsetLocations(int amount, Location location, double offset) { - List locations = new ArrayList(); + private static List getOffsetLocations(final int amount, final Location location, final double offset) { + final List locations = new ArrayList(); for (int i = 0; i < amount; i++) { locations.add(location.clone().add((float) (Math.random() * offset), (float) (Math.random() * offset), (float) (Math.random() * offset))); } @@ -391,18 +415,18 @@ private static List getOffsetLocations(int amount, Location location, @Override public void remove() { super.remove(); - MultiAbilityManager.unbindMultiAbility(player); - if (player.isOnline()) { - bPlayer.addCooldown("WaterArms", cooldown); + MultiAbilityManager.unbindMultiAbility(this.player); + if (this.player.isOnline()) { + this.bPlayer.addCooldown("WaterArms", this.cooldown); } - new WaterReturn(player, player.getLocation().getBlock()); + new WaterReturn(this.player, this.player.getLocation().getBlock()); } public void prepareCancel() { - if (System.currentTimeMillis() < lastClickTime + 500L) { - remove(); + if (System.currentTimeMillis() < this.lastClickTime + 500L) { + this.remove(); } else { - lastClickTime = System.currentTimeMillis(); + this.lastClickTime = System.currentTimeMillis(); } } @@ -414,7 +438,7 @@ public static void progressAllCleanup() { * before the user is able to see them, thus causing invisible arms. * Simple fix is just to display the arms again. */ - for (WaterArms waterArms : getAbilities(WaterArms.class)) { + for (final WaterArms waterArms : getAbilities(WaterArms.class)) { waterArms.displayLeftArm(); waterArms.displayRightArm(); } @@ -423,179 +447,177 @@ public static void progressAllCleanup() { public static void removeAllCleanup() { progressRevert(true); - BLOCK_REVERT_TIMES.clear(); WaterArmsSpear.getIceBlocks().clear(); WaterArmsWhip.removeAllCleanup(); } - @SuppressWarnings("deprecation") - public static boolean isUnbreakable(Block block) { + public static boolean isUnbreakable(final Block block) { if (Arrays.asList(UNBREAKABLES).contains(block.getTypeId())) { return true; } return false; } - public void displayBoundMsg(int slot) { - String name = bPlayer.getAbilities().get(slot); + public void displayBoundMsg(final int slot) { + final String name = this.bPlayer.getAbilities().get(slot); if (name != null) { - player.sendMessage(getElement().getColor() + sneakMsg + " " + name); + this.player.sendMessage(this.getElement().getColor() + this.sneakMsg + " " + name); } } /** * Returns the active arm of the player. - * + * * @return {@link Arm} of the player */ public Arm getActiveArm() { - return activeArm; + return this.activeArm; } /** * Switches the active arm of a player. */ public void switchActiveArm() { - if (activeArm.equals(Arm.RIGHT)) { - activeArm = Arm.LEFT; + if (this.activeArm.equals(Arm.RIGHT)) { + this.activeArm = Arm.LEFT; } else { - activeArm = Arm.RIGHT; + this.activeArm = Arm.RIGHT; } } /** * Switches to the most suitable arm for the player. - * + * * @return the {@link Arm} that was swapped to */ public Arm switchPreferredArm() { - switchActiveArm(); - if (activeArm.equals(Arm.LEFT)) { - if (!displayLeftArm()) { - switchActiveArm(); + this.switchActiveArm(); + if (this.activeArm.equals(Arm.LEFT)) { + if (!this.displayLeftArm()) { + this.switchActiveArm(); } } - if (activeArm.equals(Arm.RIGHT)) { - if (!displayRightArm()) { - switchActiveArm(); + if (this.activeArm.equals(Arm.RIGHT)) { + if (!this.displayRightArm()) { + this.switchActiveArm(); } } - return getActiveArm(); + return this.getActiveArm(); } public boolean canDisplayActiveArm() { - switch (activeArm) { + switch (this.activeArm) { case LEFT: - return displayLeftArm(); + return this.displayLeftArm(); case RIGHT: - return displayRightArm(); + return this.displayRightArm(); default: return false; } } public Location getActiveArmEnd() { - switch (activeArm) { + switch (this.activeArm) { case LEFT: - return getLeftArmEnd(); + return this.getLeftArmEnd(); case RIGHT: - return getRightArmEnd(); + return this.getRightArmEnd(); default: return null; } } public Boolean isFullSource() { - return fullSource; + return this.fullSource; } public boolean getLeftArmConsumed() { - return leftArmConsumed; + return this.leftArmConsumed; } - public void setLeftArmConsumed(boolean consumed) { + public void setLeftArmConsumed(final boolean consumed) { this.leftArmConsumed = consumed; } public boolean getRightArmConsumed() { - return rightArmConsumed; + return this.rightArmConsumed; } - public void setRightArmConsumed(boolean consumed) { + public void setRightArmConsumed(final boolean consumed) { this.rightArmConsumed = consumed; } public Integer getLengthReduction() { - return lengthReduction; + return this.lengthReduction; } - public void setLengthReduction(int lengthReduction) { + public void setLengthReduction(final int lengthReduction) { this.lengthReduction = lengthReduction; } public Integer getMaxPunches() { - return maxPunches; + return this.maxPunches; } - public void setMaxPunches(int maxPunches) { + public void setMaxPunches(final int maxPunches) { this.maxPunches = maxPunches; } public Integer getMaxUses() { - return maxUses; + return this.maxUses; } - public void setMaxUses(int maxUses) { + public void setMaxUses(final int maxUses) { this.maxUses = maxUses; } public Integer getMaxIceBlasts() { - return maxIceBlasts; + return this.maxIceBlasts; } - public void setMaxIceBlasts(int maxIceBlasts) { + public void setMaxIceBlasts(final int maxIceBlasts) { this.maxIceBlasts = maxIceBlasts; } public boolean canLightningDamage() { - return lightningEnabled; + return this.lightningEnabled; } - public void setCanLightningDamage(boolean lightningEnabled) { + public void setCanLightningDamage(final boolean lightningEnabled) { this.lightningEnabled = lightningEnabled; } public double getLightningDamage() { - return lightningDamage; + return this.lightningDamage; } - public void setLightningDamage(double lightningDamage) { + public void setLightningDamage(final double lightningDamage) { this.lightningDamage = lightningDamage; } public boolean isLeftArmCooldown() { - return cooldownLeft; + return this.cooldownLeft; } - public void setLeftArmCooldown(boolean cooldown) { + public void setLeftArmCooldown(final boolean cooldown) { this.cooldownLeft = cooldown; } public boolean isRightArmCooldown() { - return cooldownRight; + return this.cooldownRight; } - public void setRightArmCooldown(boolean cooldown) { + public void setRightArmCooldown(final boolean cooldown) { this.cooldownRight = cooldown; } - public void setActiveArmCooldown(boolean cooldown) { - switch (activeArm) { + public void setActiveArmCooldown(final boolean cooldown) { + switch (this.activeArm) { case LEFT: - setLeftArmCooldown(cooldown); + this.setLeftArmCooldown(cooldown); return; case RIGHT: - setRightArmCooldown(cooldown); + this.setRightArmCooldown(cooldown); return; default: break; @@ -604,10 +626,10 @@ public void setActiveArmCooldown(boolean cooldown) { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } - public void setCooldown(long cooldown) { + public void setCooldown(final long cooldown) { this.cooldown = cooldown; } @@ -618,7 +640,7 @@ public String getName() { @Override public Location getLocation() { - return player != null ? player.getLocation() : null; + return this.player != null ? this.player.getLocation() : null; } @Override @@ -632,115 +654,118 @@ public boolean isHarmlessAbility() { } public boolean isCooldownLeft() { - return cooldownLeft; + return this.cooldownLeft; } - public void setCooldownLeft(boolean cooldownLeft) { + public void setCooldownLeft(final boolean cooldownLeft) { this.cooldownLeft = cooldownLeft; } public boolean isCooldownRight() { - return cooldownRight; + return this.cooldownRight; } - public void setCooldownRight(boolean cooldownRight) { + public void setCooldownRight(final boolean cooldownRight) { this.cooldownRight = cooldownRight; } public boolean isCanUsePlantSource() { - return canUsePlantSource; + return this.canUsePlantSource; } - public void setCanUsePlantSource(boolean canUsePlantSource) { + public void setCanUsePlantSource(final boolean canUsePlantSource) { this.canUsePlantSource = canUsePlantSource; } public boolean isLightningEnabled() { - return lightningEnabled; + return this.lightningEnabled; } - public void setLightningEnabled(boolean lightningEnabled) { + public void setLightningEnabled(final boolean lightningEnabled) { this.lightningEnabled = lightningEnabled; } public boolean isLightningKill() { - return lightningKill; + return this.lightningKill; } - public void setLightningKill(boolean lightningKill) { + public void setLightningKill(final boolean lightningKill) { this.lightningKill = lightningKill; } public int getInitLength() { - return initLength; + return this.initLength; } - public void setInitLength(int initLength) { + public void setInitLength(final int initLength) { this.initLength = initLength; } public int getSourceGrabRange() { - return sourceGrabRange; + return this.sourceGrabRange; } - public void setSourceGrabRange(int sourceGrabRange) { + public void setSourceGrabRange(final int sourceGrabRange) { this.sourceGrabRange = sourceGrabRange; } public int getSelectedSlot() { - return selectedSlot; + return this.selectedSlot; } - public void setSelectedSlot(int selectedSlot) { + public void setSelectedSlot(final int selectedSlot) { this.selectedSlot = selectedSlot; } public int getFreezeSlot() { - return freezeSlot; + return this.freezeSlot; } - public void setFreezeSlot(int freezeSlot) { + public void setFreezeSlot(final int freezeSlot) { this.freezeSlot = freezeSlot; } public long getLastClickTime() { - return lastClickTime; + return this.lastClickTime; } - public void setLastClickTime(long lastClickTime) { + public void setLastClickTime(final long lastClickTime) { this.lastClickTime = lastClickTime; } public World getWorld() { - return world; + return this.world; } - public void setWorld(World world) { + public void setWorld(final World world) { this.world = world; } public String getSneakMsg() { - return sneakMsg; + return this.sneakMsg; } - public void setSneakMsg(String sneakMsg) { + public void setSneakMsg(final String sneakMsg) { this.sneakMsg = sneakMsg; } - public static Map getBlockRevertTimes() { - return BLOCK_REVERT_TIMES; - } - public static Integer[] getUnbreakables() { return UNBREAKABLES; } - public void setFullSource(boolean fullSource) { + public void setFullSource(final boolean fullSource) { this.fullSource = fullSource; } - public void setActiveArm(Arm activeArm) { + public void setActiveArm(final Arm activeArm) { this.activeArm = activeArm; } -} \ No newline at end of file + public void addToArm(final Block block, final Arm arm) { + if (arm.equals(Arm.LEFT)) { + this.left.add(block); + } else { + this.right.add(block); + } + } +} diff --git a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsFreeze.java b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsFreeze.java index c00126ef9..cf6b46998 100644 --- a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsFreeze.java +++ b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsFreeze.java @@ -32,87 +32,87 @@ public class WaterArmsFreeze extends IceAbility { private Vector direction; private WaterArms waterArms; - public WaterArmsFreeze(Player player) { + public WaterArmsFreeze(final Player player) { super(player); - this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldownEnabled"); + this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Enabled"); this.iceRange = getConfig().getInt("Abilities.Water.WaterArms.Freeze.Range"); this.iceDamage = getConfig().getInt("Abilities.Water.WaterArms.Freeze.Damage"); - this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown"); + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Freeze"); this.direction = player.getEyeLocation().getDirection(); - createInstance(); + this.createInstance(); } private void createInstance() { - waterArms = getAbility(player, WaterArms.class); + this.waterArms = getAbility(this.player, WaterArms.class); - if (waterArms != null) { - waterArms.switchPreferredArm(); - arm = waterArms.getActiveArm(); + if (this.waterArms != null) { + this.waterArms.switchPreferredArm(); + this.arm = this.waterArms.getActiveArm(); - if (arm.equals(Arm.LEFT)) { - if (waterArms.isLeftArmCooldown() || bPlayer.isOnCooldown("WaterArms_LEFT")) { + if (this.arm.equals(Arm.LEFT)) { + if (this.waterArms.isLeftArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_LEFT")) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_LEFT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_LEFT", this.usageCooldown); } - waterArms.setLeftArmCooldown(true); + this.waterArms.setLeftArmCooldown(true); } } - if (arm.equals(Arm.RIGHT)) { - if (waterArms.isRightArmCooldown() || bPlayer.isOnCooldown("WaterArms_RIGHT")) { + if (this.arm.equals(Arm.RIGHT)) { + if (this.waterArms.isRightArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_RIGHT")) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_RIGHT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_RIGHT", this.usageCooldown); } - waterArms.setRightArmCooldown(true); + this.waterArms.setRightArmCooldown(true); } } - Vector dir = player.getLocation().getDirection(); - location = waterArms.getActiveArmEnd().add(dir.normalize().multiply(1)); - direction = GeneralMethods.getDirection(location, GeneralMethods.getTargetedLocation(player, iceRange, Material.WATER, Material.STATIONARY_WATER, Material.ICE, Material.PACKED_ICE)).normalize(); + final Vector dir = this.player.getLocation().getDirection(); + this.location = this.waterArms.getActiveArmEnd().add(dir.normalize().multiply(1)); + this.direction = GeneralMethods.getDirection(this.location, GeneralMethods.getTargetedLocation(this.player, this.iceRange, Material.WATER, Material.STATIONARY_WATER, Material.ICE, Material.PACKED_ICE)).normalize(); } else { return; } - start(); + this.start(); } @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (distanceTravelled > iceRange) { - remove(); + } else if (this.distanceTravelled > this.iceRange) { + this.remove(); return; } - if (distanceTravelled >= 5 && !cancelled) { - cancelled = true; - if (hasAbility(player, WaterArms.class)) { - if (arm.equals(Arm.LEFT)) { - waterArms.setLeftArmCooldown(false); + if (this.distanceTravelled >= 5 && !this.cancelled) { + this.cancelled = true; + if (hasAbility(this.player, WaterArms.class)) { + if (this.arm.equals(Arm.LEFT)) { + this.waterArms.setLeftArmCooldown(false); } else { - waterArms.setRightArmCooldown(false); + this.waterArms.setRightArmCooldown(false); } - waterArms.setMaxIceBlasts(waterArms.getMaxIceBlasts() - 1); + this.waterArms.setMaxIceBlasts(this.waterArms.getMaxIceBlasts() - 1); } } - if (!canPlaceBlock(location.getBlock())) { - remove(); + if (!this.canPlaceBlock(this.location.getBlock())) { + this.remove(); return; } - progressIce(); + this.progressIce(); } - private boolean canPlaceBlock(Block block) { - if (!isTransparent(player, block) && !((isWater(block)) && TempBlock.isTempBlock(block))) { + private boolean canPlaceBlock(final Block block) { + if (!isTransparent(this.player, block) && !((isWater(block)) && TempBlock.isTempBlock(block))) { return false; } else if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return false; @@ -121,40 +121,39 @@ private boolean canPlaceBlock(Block block) { } private void progressIce() { - ParticleEffect.SNOW_SHOVEL.display(location, (float) Math.random(), (float) Math.random(), (float) Math.random(), (float) 0.05, 5); - new TempBlock(location.getBlock(), Material.ICE, (byte) 0); - WaterArms.getBlockRevertTimes().put(location.getBlock(), System.currentTimeMillis() + 10L); - - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2.5)) { - if (entity instanceof LivingEntity && entity.getEntityId() != player.getEntityId() && !(entity instanceof ArmorStand)) { - DamageHandler.damageEntity(entity, iceDamage, this); - PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 40, 2); + ParticleEffect.SNOW_SHOVEL.display(this.location, (float) Math.random(), (float) Math.random(), (float) Math.random(), (float) 0.05, 5); + new TempBlock(this.location.getBlock(), Material.ICE, (byte) 0).setRevertTime(10); + + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2.5)) { + if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId() && !(entity instanceof ArmorStand)) { + DamageHandler.damageEntity(entity, this.iceDamage, this); + final PotionEffect effect = new PotionEffect(PotionEffectType.SLOW, 40, 2); new TempPotionEffect((LivingEntity) entity, effect); - remove(); + this.remove(); return; } } for (int i = 0; i < 2; i++) { - location = location.add(direction.clone().multiply(1)); - if (!canPlaceBlock(location.getBlock())) { + this.location = this.location.add(this.direction.clone().multiply(1)); + if (!this.canPlaceBlock(this.location.getBlock())) { return; } - distanceTravelled++; + this.distanceTravelled++; } } @Override public void remove() { super.remove(); - if (hasAbility(player, WaterArms.class)) { - if (!cancelled) { - if (arm.equals(Arm.LEFT)) { - waterArms.setLeftArmCooldown(false); + if (hasAbility(this.player, WaterArms.class)) { + if (!this.cancelled) { + if (this.arm.equals(Arm.LEFT)) { + this.waterArms.setLeftArmCooldown(false); } else { - waterArms.setRightArmCooldown(false); + this.waterArms.setRightArmCooldown(false); } - waterArms.setMaxIceBlasts(waterArms.getMaxIceBlasts() - 1); + this.waterArms.setMaxIceBlasts(this.waterArms.getMaxIceBlasts() - 1); } } } @@ -166,12 +165,12 @@ public String getName() { @Override public Location getLocation() { - return location; + return this.location; } @Override public long getCooldown() { - return usageCooldown; + return this.usageCooldown; } @Override @@ -185,78 +184,78 @@ public boolean isHarmlessAbility() { } public boolean isCancelled() { - return cancelled; + return this.cancelled; } - public void setCancelled(boolean cancelled) { + public void setCancelled(final boolean cancelled) { this.cancelled = cancelled; } public boolean isUsageCooldownEnabled() { - return usageCooldownEnabled; + return this.usageCooldownEnabled; } - public void setUsageCooldownEnabled(boolean usageCooldownEnabled) { + public void setUsageCooldownEnabled(final boolean usageCooldownEnabled) { this.usageCooldownEnabled = usageCooldownEnabled; } public int getIceRange() { - return iceRange; + return this.iceRange; } - public void setIceRange(int iceRange) { + public void setIceRange(final int iceRange) { this.iceRange = iceRange; } public int getDistanceTravelled() { - return distanceTravelled; + return this.distanceTravelled; } - public void setDistanceTravelled(int distanceTravelled) { + public void setDistanceTravelled(final int distanceTravelled) { this.distanceTravelled = distanceTravelled; } public double getIceDamage() { - return iceDamage; + return this.iceDamage; } - public void setIceDamage(double iceDamage) { + public void setIceDamage(final double iceDamage) { this.iceDamage = iceDamage; } public long getUsageCooldown() { - return usageCooldown; + return this.usageCooldown; } - public void setUsageCooldown(long usageCooldown) { + public void setUsageCooldown(final long usageCooldown) { this.usageCooldown = usageCooldown; } public Arm getArm() { - return arm; + return this.arm; } - public void setArm(Arm arm) { + public void setArm(final Arm arm) { this.arm = arm; } public Vector getDirection() { - return direction; + return this.direction; } - public void setDirection(Vector direction) { + public void setDirection(final Vector direction) { this.direction = direction; } public WaterArms getWaterArms() { - return waterArms; + return this.waterArms; } - public void setWaterArms(WaterArms waterArms) { + public void setWaterArms(final WaterArms waterArms) { this.waterArms = waterArms; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsSpear.java b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsSpear.java index 4414ad8b6..53e0d2c10 100644 --- a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsSpear.java +++ b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsSpear.java @@ -46,13 +46,13 @@ public class WaterArmsSpear extends WaterAbility { private Location location; private Location initLocation; private WaterArms waterArms; - private List spearLocations; + private final List spearLocations; - public WaterArmsSpear(Player player, boolean freeze) { + public WaterArmsSpear(final Player player, final boolean freeze) { super(player); this.canFreeze = freeze; - this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldownEnabled"); + this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Enabled"); this.spearDamageEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Spear.DamageEnabled"); this.spearLength = getConfig().getInt("Abilities.Water.WaterArms.Spear.Length"); this.spearRange = getConfig().getInt("Abilities.Water.WaterArms.Spear.Range"); @@ -64,189 +64,190 @@ public WaterArmsSpear(Player player, boolean freeze) { this.spearDuration = getConfig().getLong("Abilities.Water.WaterArms.Spear.Duration"); this.spearDurationNight = getConfig().getLong("Abilities.Water.WaterArms.Spear.NightAugments.Duration.Normal"); this.spearDurationFullMoon = getConfig().getLong("Abilities.Water.WaterArms.Spear.NightAugments.Duration.FullMoon"); - this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown"); + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Spear"); this.spearDamage = getConfig().getDouble("Abilities.Water.WaterArms.Spear.Damage"); this.spearLocations = new ArrayList<>(); - getNightAugments(); - createInstance(); + this.getNightAugments(); + this.createInstance(); } private void getNightAugments() { - World world = player.getWorld(); + final World world = this.player.getWorld(); if (isNight(world)) { if (GeneralMethods.hasRPG()) { if (isLunarEclipse(world)) { - spearRange = spearRangeFullMoon; - spearSphere = spearSphereFullMoon; - spearDuration = spearDurationFullMoon; + this.spearRange = this.spearRangeFullMoon; + this.spearSphere = this.spearSphereFullMoon; + this.spearDuration = this.spearDurationFullMoon; } else if (isFullMoon(world)) { - spearRange = spearRangeFullMoon; - spearSphere = spearSphereFullMoon; - spearDuration = spearDurationFullMoon; + this.spearRange = this.spearRangeFullMoon; + this.spearSphere = this.spearSphereFullMoon; + this.spearDuration = this.spearDurationFullMoon; } else { - spearRange = spearRangeNight; - spearSphere = spearSphereNight; - spearDuration = spearDurationNight; + this.spearRange = this.spearRangeNight; + this.spearSphere = this.spearSphereNight; + this.spearDuration = this.spearDurationNight; } } else { if (isFullMoon(world)) { - spearRange = spearRangeFullMoon; - spearSphere = spearSphereFullMoon; - spearDuration = spearDurationFullMoon; + this.spearRange = this.spearRangeFullMoon; + this.spearSphere = this.spearSphereFullMoon; + this.spearDuration = this.spearDurationFullMoon; } else { - spearRange = spearRangeNight; - spearSphere = spearSphereNight; - spearDuration = spearDurationNight; + this.spearRange = this.spearRangeNight; + this.spearSphere = this.spearSphereNight; + this.spearDuration = this.spearDurationNight; } } } } private void createInstance() { - waterArms = getAbility(player, WaterArms.class); - if (waterArms != null) { - waterArms.switchPreferredArm(); - arm = waterArms.getActiveArm(); + this.waterArms = getAbility(this.player, WaterArms.class); + if (this.waterArms != null) { + this.waterArms.switchPreferredArm(); + this.arm = this.waterArms.getActiveArm(); - if (arm.equals(Arm.LEFT)) { - if (waterArms.isLeftArmCooldown() || bPlayer.isOnCooldown("WaterArms_LEFT") || !waterArms.displayLeftArm()) { + if (this.arm.equals(Arm.LEFT)) { + if (this.waterArms.isLeftArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_LEFT") || !this.waterArms.displayLeftArm()) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_LEFT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_LEFT", this.usageCooldown); } - waterArms.setLeftArmConsumed(true); - waterArms.setLeftArmCooldown(true); + this.waterArms.setLeftArmConsumed(true); + this.waterArms.setLeftArmCooldown(true); } } - if (arm.equals(Arm.RIGHT)) { - if (waterArms.isRightArmCooldown() || bPlayer.isOnCooldown("WaterArms_RIGHT") || !waterArms.displayRightArm()) { + if (this.arm.equals(Arm.RIGHT)) { + if (this.waterArms.isRightArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_RIGHT") || !this.waterArms.displayRightArm()) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_RIGHT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_RIGHT", this.usageCooldown); } - waterArms.setRightArmConsumed(true); - waterArms.setRightArmCooldown(true); + this.waterArms.setRightArmConsumed(true); + this.waterArms.setRightArmCooldown(true); } } - Vector dir = player.getLocation().getDirection(); - location = waterArms.getActiveArmEnd().add(dir.normalize().multiply(1)); - initLocation = location.clone(); + final Vector dir = this.player.getLocation().getDirection(); + this.location = this.waterArms.getActiveArmEnd().add(dir.normalize().multiply(1)); + this.initLocation = this.location.clone(); } else { return; } - start(); + this.start(); } @Override public void progress() { - if (player.isDead() || !player.isOnline()) { - remove(); + if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; - } else if (distanceTravelled > spearRange) { - remove(); + } else if (this.distanceTravelled > this.spearRange) { + this.remove(); return; } - if (!hitEntity) { - progressSpear(); + if (!this.hitEntity) { + this.progressSpear(); } else { - createIceBall(); - remove(); + this.createIceBall(); + this.remove(); } - if (!canPlaceBlock(location.getBlock())) { - if (canFreeze) { - createSpear(); + if (!this.canPlaceBlock(this.location.getBlock())) { + if (this.canFreeze) { + this.createSpear(); } - remove(); + this.remove(); return; } } private void progressSpear() { for (int i = 0; i < 2; i++) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { - if (entity instanceof LivingEntity && entity.getEntityId() != player.getEntityId() && !(entity instanceof ArmorStand)) { - hitEntity = true; - location = entity.getLocation(); + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2)) { + if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId() && !(entity instanceof ArmorStand)) { + this.hitEntity = true; + this.location = entity.getLocation(); - if (spearDamageEnabled) { - DamageHandler.damageEntity(entity, spearDamage, this); + if (this.spearDamageEnabled) { + DamageHandler.damageEntity(entity, this.spearDamage, this); } return; } } - new TempBlock(location.getBlock(), Material.STATIONARY_WATER, (byte) 8); - getIceBlocks().put(location.getBlock(), System.currentTimeMillis() + 600L); - Vector direction = GeneralMethods.getDirection(initLocation, GeneralMethods.getTargetedLocation(player, spearRange, Material.WATER, Material.STATIONARY_WATER, Material.ICE, Material.PACKED_ICE)).normalize(); - - location = location.add(direction.clone().multiply(1)); - spearLocations.add(location.clone()); - - if (!canPlaceBlock(location.getBlock())) { + if (!this.canPlaceBlock(this.location.getBlock())) { return; } - distanceTravelled++; + + new TempBlock(this.location.getBlock(), Material.STATIONARY_WATER, (byte) 8); + getIceBlocks().put(this.location.getBlock(), System.currentTimeMillis() + 600L); + final Vector direction = GeneralMethods.getDirection(this.initLocation, GeneralMethods.getTargetedLocation(this.player, this.spearRange, getTransparentMaterials())).normalize(); + + this.location = this.location.add(direction.clone().multiply(1)); + this.spearLocations.add(this.location.clone()); + + this.distanceTravelled++; } } private void createSpear() { - for (int i = spearLocations.size() - spearLength; i < spearLocations.size(); i++) { + for (int i = this.spearLocations.size() - this.spearLength; i < this.spearLocations.size(); i++) { if (i >= 0) { - Block block = spearLocations.get(i).getBlock(); - if (canPlaceBlock(block)) { + final Block block = this.spearLocations.get(i).getBlock(); + if (this.canPlaceBlock(block)) { playIcebendingSound(block.getLocation()); if (getIceBlocks().containsKey(block)) { getIceBlocks().remove(block); } - TempBlock tempBlock = new TempBlock(block, Material.AIR, (byte) 0); + final TempBlock tempBlock = new TempBlock(block, Material.AIR, (byte) 0); tempBlock.setType(Material.ICE); - getIceBlocks().put(block, System.currentTimeMillis() + spearDuration + (long) (Math.random() * 500)); + getIceBlocks().put(block, System.currentTimeMillis() + this.spearDuration + (long) (Math.random() * 500)); } } } } - public static boolean canThaw(Block block) { + public static boolean canThaw(final Block block) { return getIceBlocks().containsKey(block) && block.getType() == Material.ICE; } - public static void thaw(Block block) { + public static void thaw(final Block block) { if (canThaw(block)) { getIceBlocks().remove(block); if (TempBlock.isTempBlock(block)) { TempBlock.get(block).revertBlock(); } else { - block.setType(Material.AIR); + block.setType(Material.AIR); } } } private void createIceBall() { - if (spearSphere <= 0) { - if (canFreeze) { - createSpear(); + if (this.spearSphere <= 0) { + if (this.canFreeze) { + this.createSpear(); } return; } - for (Block block : GeneralMethods.getBlocksAroundPoint(location, spearSphere)) { - if (isTransparent(player, block) && block.getType() != Material.ICE && !WaterArms.isUnbreakable(block)) { + for (final Block block : GeneralMethods.getBlocksAroundPoint(this.location, this.spearSphere)) { + if (isTransparent(this.player, block) && block.getType() != Material.ICE && !WaterArms.isUnbreakable(block)) { playIcebendingSound(block.getLocation()); new TempBlock(block, Material.ICE, (byte) 0); - getIceBlocks().put(block, System.currentTimeMillis() + spearDuration + (long) (Math.random() * 500)); + getIceBlocks().put(block, System.currentTimeMillis() + this.spearDuration + (long) (Math.random() * 500)); } } } - private boolean canPlaceBlock(Block block) { - if (!isTransparent(player, block) && !((isWater(block) || isIcebendable(block)) && (TempBlock.isTempBlock(block) && !getIceBlocks().containsKey(block)))) { + private boolean canPlaceBlock(final Block block) { + if (!isTransparent(this.player, block) && !((isWater(block) || this.isIcebendable(block)) && (TempBlock.isTempBlock(block) && !getIceBlocks().containsKey(block)))) { return false; } else if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return false; @@ -259,13 +260,13 @@ private boolean canPlaceBlock(Block block) { @Override public void remove() { super.remove(); - if (hasAbility(player, WaterArms.class)) { - if (arm.equals(Arm.LEFT)) { - waterArms.setLeftArmCooldown(false); + if (hasAbility(this.player, WaterArms.class)) { + if (this.arm.equals(Arm.LEFT)) { + this.waterArms.setLeftArmCooldown(false); } else { - waterArms.setRightArmCooldown(false); + this.waterArms.setRightArmCooldown(false); } - waterArms.setMaxUses(waterArms.getMaxUses() - 1); + this.waterArms.setMaxUses(this.waterArms.getMaxUses() - 1); } } @@ -276,16 +277,16 @@ public String getName() { @Override public Location getLocation() { - if (location != null) { - return location; + if (this.location != null) { + return this.location; } else { - return initLocation; + return this.initLocation; } } @Override public long getCooldown() { - return usageCooldown; + return this.usageCooldown; } @Override @@ -299,170 +300,170 @@ public boolean isHarmlessAbility() { } public boolean isHitEntity() { - return hitEntity; + return this.hitEntity; } - public void setHitEntity(boolean hitEntity) { + public void setHitEntity(final boolean hitEntity) { this.hitEntity = hitEntity; } public boolean isCanFreeze() { - return canFreeze; + return this.canFreeze; } - public void setCanFreeze(boolean canFreeze) { + public void setCanFreeze(final boolean canFreeze) { this.canFreeze = canFreeze; } public boolean isUsageCooldownEnabled() { - return usageCooldownEnabled; + return this.usageCooldownEnabled; } - public void setUsageCooldownEnabled(boolean usageCooldownEnabled) { + public void setUsageCooldownEnabled(final boolean usageCooldownEnabled) { this.usageCooldownEnabled = usageCooldownEnabled; } public boolean isSpearDamageEnabled() { - return spearDamageEnabled; + return this.spearDamageEnabled; } - public void setSpearDamageEnabled(boolean spearDamageEnabled) { + public void setSpearDamageEnabled(final boolean spearDamageEnabled) { this.spearDamageEnabled = spearDamageEnabled; } public int getSpearLength() { - return spearLength; + return this.spearLength; } - public void setSpearLength(int spearLength) { + public void setSpearLength(final int spearLength) { this.spearLength = spearLength; } public int getSpearRange() { - return spearRange; + return this.spearRange; } - public void setSpearRange(int spearRange) { + public void setSpearRange(final int spearRange) { this.spearRange = spearRange; } public int getSpearRangeNight() { - return spearRangeNight; + return this.spearRangeNight; } - public void setSpearRangeNight(int spearRangeNight) { + public void setSpearRangeNight(final int spearRangeNight) { this.spearRangeNight = spearRangeNight; } public int getSpearRangeFullMoon() { - return spearRangeFullMoon; + return this.spearRangeFullMoon; } - public void setSpearRangeFullMoon(int spearRangeFullMoon) { + public void setSpearRangeFullMoon(final int spearRangeFullMoon) { this.spearRangeFullMoon = spearRangeFullMoon; } public int getSpearSphere() { - return spearSphere; + return this.spearSphere; } - public void setSpearSphere(int spearSphere) { + public void setSpearSphere(final int spearSphere) { this.spearSphere = spearSphere; } public int getSpearSphereNight() { - return spearSphereNight; + return this.spearSphereNight; } - public void setSpearSphereNight(int spearSphereNight) { + public void setSpearSphereNight(final int spearSphereNight) { this.spearSphereNight = spearSphereNight; } public int getSpearSphereFullMoon() { - return spearSphereFullMoon; + return this.spearSphereFullMoon; } - public void setSpearSphereFullMoon(int spearSphereFullMoon) { + public void setSpearSphereFullMoon(final int spearSphereFullMoon) { this.spearSphereFullMoon = spearSphereFullMoon; } public int getDistanceTravelled() { - return distanceTravelled; + return this.distanceTravelled; } - public void setDistanceTravelled(int distanceTravelled) { + public void setDistanceTravelled(final int distanceTravelled) { this.distanceTravelled = distanceTravelled; } public long getSpearDuration() { - return spearDuration; + return this.spearDuration; } - public void setSpearDuration(long spearDuration) { + public void setSpearDuration(final long spearDuration) { this.spearDuration = spearDuration; } public long getSpearDurationNight() { - return spearDurationNight; + return this.spearDurationNight; } - public void setSpearDurationNight(long spearDurationNight) { + public void setSpearDurationNight(final long spearDurationNight) { this.spearDurationNight = spearDurationNight; } public long getSpearDurationFullMoon() { - return spearDurationFullMoon; + return this.spearDurationFullMoon; } - public void setSpearDurationFullMoon(long spearDurationFullMoon) { + public void setSpearDurationFullMoon(final long spearDurationFullMoon) { this.spearDurationFullMoon = spearDurationFullMoon; } public long getUsageCooldown() { - return usageCooldown; + return this.usageCooldown; } - public void setUsageCooldown(long usageCooldown) { + public void setUsageCooldown(final long usageCooldown) { this.usageCooldown = usageCooldown; } public double getSpearDamage() { - return spearDamage; + return this.spearDamage; } - public void setSpearDamage(double spearDamage) { + public void setSpearDamage(final double spearDamage) { this.spearDamage = spearDamage; } public Arm getArm() { - return arm; + return this.arm; } - public void setArm(Arm arm) { + public void setArm(final Arm arm) { this.arm = arm; } public Location getInitLocation() { - return initLocation; + return this.initLocation; } - public void setInitLocation(Location initLocation) { + public void setInitLocation(final Location initLocation) { this.initLocation = initLocation; } public WaterArms getWaterArms() { - return waterArms; + return this.waterArms; } - public void setWaterArms(WaterArms waterArms) { + public void setWaterArms(final WaterArms waterArms) { this.waterArms = waterArms; } public List getSpearLocations() { - return spearLocations; + return this.spearLocations; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } diff --git a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsWhip.java b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsWhip.java index b88ca9aac..b9dc8a7e6 100644 --- a/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsWhip.java +++ b/src/com/projectkorra/projectkorra/waterbending/multiabilities/WaterArmsWhip.java @@ -59,7 +59,7 @@ public static enum Whip { private Location end; private WaterArms waterArms; - public WaterArmsWhip(Player player, Whip ability) { + public WaterArmsWhip(final Player player, final Whip ability) { super(player); this.ability = ability; @@ -68,7 +68,7 @@ public WaterArmsWhip(Player player, Whip ability) { this.grappled = false; this.grabbed = false; this.grappleRespectRegions = getConfig().getBoolean("Abilities.Water.WaterArms.Whip.Grapple.RespectRegions"); - this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldownEnabled"); + this.usageCooldownEnabled = getConfig().getBoolean("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Enabled"); this.whipLength = getConfig().getInt("Abilities.Water.WaterArms.Whip.MaxLength"); this.whipLengthWeak = getConfig().getInt("Abilities.Water.WaterArms.Whip.MaxLengthWeak"); this.whipLengthNight = getConfig().getInt("Abilities.Water.WaterArms.Whip.NightAugments.MaxLength.Normal"); @@ -77,14 +77,31 @@ public WaterArmsWhip(Player player, Whip ability) { this.punchLength = getConfig().getInt("Abilities.Water.WaterArms.Whip.Punch.MaxLength"); this.punchLengthNight = getConfig().getInt("Abilities.Water.WaterArms.Whip.Punch.NightAugments.MaxLength.Normal"); this.punchLengthFullMoon = getConfig().getInt("Abilities.Water.WaterArms.Whip.Punch.NightAugments.MaxLength.FullMoon"); - this.activeLength = initLength; - this.whipSpeed = 2; + this.activeLength = this.initLength; + this.whipSpeed = 1; this.holdTime = getConfig().getLong("Abilities.Water.WaterArms.Whip.Grab.HoldTime"); - this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown"); this.pullMultiplier = getConfig().getDouble("Abilities.Water.WaterArms.Whip.Pull.Multiplier"); this.punchDamage = getConfig().getDouble("Abilities.Water.WaterArms.Whip.Punch.PunchDamage"); - WaterArmsWhip waw = getAbility(player, WaterArmsWhip.class); + switch (ability) { + + case PULL: + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Pull"); + break; + case PUNCH: + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Punch"); + break; + case GRAPPLE: + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Grapple"); + break; + case GRAB: + this.usageCooldown = getConfig().getLong("Abilities.Water.WaterArms.Arms.Cooldowns.UsageCooldown.Grab"); + break; + default: + this.usageCooldown = 200; + + } + final WaterArmsWhip waw = getAbility(player, WaterArmsWhip.class); if (waw != null) { if (waw.grabbed) { waw.grabbed = false; @@ -99,48 +116,48 @@ public WaterArmsWhip(Player player, Whip ability) { } } - getAugments(); - createInstance(); + this.getAugments(); + this.createInstance(); } private void getAugments() { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLength; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLength; } - World world = player.getWorld(); + final World world = this.player.getWorld(); if (isNight(world)) { if (GeneralMethods.hasRPG()) { if (isLunarEclipse(world)) { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLengthFullMoon; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLengthFullMoon; } else { - whipLength = whipLengthFullMoon; + this.whipLength = this.whipLengthFullMoon; } } else if (isFullMoon(world)) { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLengthFullMoon; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLengthFullMoon; } else { - whipLength = whipLengthFullMoon; + this.whipLength = this.whipLengthFullMoon; } } else { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLengthNight; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLengthNight; } else { - whipLength = whipLengthNight; + this.whipLength = this.whipLengthNight; } } } else { if (isFullMoon(world)) { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLengthFullMoon; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLengthFullMoon; } else { - whipLength = whipLengthFullMoon; + this.whipLength = this.whipLengthFullMoon; } } else { - if (ability.equals(Whip.PUNCH)) { - whipLength = punchLengthNight; + if (this.ability.equals(Whip.PUNCH)) { + this.whipLength = this.punchLengthNight; } else { - whipLength = whipLengthNight; + this.whipLength = this.whipLengthNight; } } } @@ -148,84 +165,84 @@ private void getAugments() { } private void createInstance() { - waterArms = getAbility(player, WaterArms.class); - if (waterArms != null) { - waterArms.switchPreferredArm(); - arm = waterArms.getActiveArm(); - time = System.currentTimeMillis() + holdTime; - playerHealth = player.getHealth(); - - if (arm.equals(Arm.LEFT)) { - if (waterArms.isLeftArmCooldown() || bPlayer.isOnCooldown("WaterArms_LEFT")) { + this.waterArms = getAbility(this.player, WaterArms.class); + if (this.waterArms != null) { + this.waterArms.switchPreferredArm(); + this.arm = this.waterArms.getActiveArm(); + this.time = System.currentTimeMillis() + this.holdTime; + this.playerHealth = this.player.getHealth(); + + if (this.arm.equals(Arm.LEFT)) { + if (this.waterArms.isLeftArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_LEFT")) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_LEFT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_LEFT", this.usageCooldown); } - waterArms.setLeftArmCooldown(true); + this.waterArms.setLeftArmCooldown(true); } } - if (arm.equals(Arm.RIGHT)) { - if (waterArms.isRightArmCooldown() || bPlayer.isOnCooldown("WaterArms_RIGHT")) { + if (this.arm.equals(Arm.RIGHT)) { + if (this.waterArms.isRightArmCooldown() || this.bPlayer.isOnCooldown("WaterArms_RIGHT")) { return; } else { - if (usageCooldownEnabled) { - bPlayer.addCooldown("WaterArms_RIGHT", usageCooldown); + if (this.usageCooldownEnabled) { + this.bPlayer.addCooldown("WaterArms_RIGHT", this.usageCooldown); } - waterArms.setRightArmCooldown(true); + this.waterArms.setRightArmCooldown(true); } } } else { return; } - if (!waterArms.isFullSource()) { - whipLength = whipLengthWeak; + if (!this.waterArms.isFullSource()) { + this.whipLength = this.whipLengthWeak; } - start(); + this.start(); } @Override public void progress() { - if (!hasAbility(player, WaterArms.class)) { - remove(); + if (!hasAbility(this.player, WaterArms.class)) { + this.remove(); return; - } else if (player.isDead() || !player.isOnline()) { - remove(); + } else if (this.player.isDead() || !this.player.isOnline()) { + this.remove(); return; } - if (!MultiAbilityManager.hasMultiAbilityBound(player, "WaterArms")) { - remove(); + if (!MultiAbilityManager.hasMultiAbilityBound(this.player, "WaterArms")) { + this.remove(); return; } - if (activeLength < whipLength && !reverting) { - activeLength += whipSpeed; - } else if (activeLength > initLength) { - if (!grabbed) { - activeLength -= whipSpeed; + if (this.activeLength < this.whipLength && !this.reverting) { + this.activeLength += this.whipSpeed; + } else if (this.activeLength > this.initLength) { + if (!this.grabbed) { + this.activeLength -= this.whipSpeed; } } else { - remove(); + this.remove(); return; } - if (activeLength >= whipLength && !grabbed) { - reverting = true; + if (this.activeLength >= this.whipLength && !this.grabbed) { + this.reverting = true; } - if (grabbed && (System.currentTimeMillis() > time || playerHealth > player.getHealth())) { - grabbed = false; - reverting = true; + if (this.grabbed && (System.currentTimeMillis() > this.time || this.playerHealth > this.player.getHealth())) { + this.grabbed = false; + this.reverting = true; } - useArm(); - dragEntity(end); + this.useArm(); + this.dragEntity(this.end); } - private boolean canPlaceBlock(Block block) { - if (!isTransparent(player, block) && !(isWater(block) && TempBlock.isTempBlock(block))) { + private boolean canPlaceBlock(final Block block) { + if (!isTransparent(this.player, block) && !(isWater(block) && TempBlock.isTempBlock(block))) { return false; } else if (GeneralMethods.isRegionProtectedFromBuild(this, block.getLocation())) { return false; @@ -234,94 +251,99 @@ private boolean canPlaceBlock(Block block) { } private void useArm() { - if (waterArms.canDisplayActiveArm()) { + if (this.waterArms.canDisplayActiveArm()) { Location l1 = null; - if (arm.equals(Arm.LEFT)) { - l1 = waterArms.getLeftArmEnd().clone(); + if (this.arm.equals(Arm.LEFT)) { + l1 = this.waterArms.getLeftArmEnd().clone(); } else { - l1 = waterArms.getRightArmEnd().clone(); + l1 = this.waterArms.getRightArmEnd().clone(); } - Vector dir = player.getLocation().getDirection(); - for (int i = 1; i <= activeLength; i++) { - Location l2 = l1.clone().add(dir.normalize().multiply(i)); + final Vector dir = this.player.getLocation().getDirection().clone(); + for (int i = 1; i <= this.activeLength; i++) { + final Location l2 = l1.clone().add(dir.normalize().multiply(i)); - if (!canPlaceBlock(l2.getBlock())) { - if (!l2.getBlock().getType().equals(Material.BARRIER)) { - grappled = true; + if (!this.canPlaceBlock(l2.getBlock())) { + if (l2.getBlock().getType() != Material.BARRIER) { + this.grappled = true; } - reverting = true; + this.reverting = true; + this.performAction(l2); break; } - new TempBlock(l2.getBlock(), Material.STATIONARY_WATER, (byte) 8); - WaterArms.getBlockRevertTimes().put(l2.getBlock(), System.currentTimeMillis() + 10); + final byte b = (byte) Math.ceil(8 / (Math.pow(i, 1 / 3))); + this.waterArms.addToArm(l2.getBlock(), this.arm); + this.waterArms.addBlock(l2.getBlock(), Material.STATIONARY_WATER, b, 40); - if (i == activeLength) { - Location l3 = null; - if (arm.equals(Arm.LEFT)) { - l3 = GeneralMethods.getRightSide(l2, 1); + if (i == this.activeLength) { + this.end = l2.clone(); + if (this.arm == Arm.LEFT) { + this.end = GeneralMethods.getRightSide(this.end, 1); } else { - l3 = GeneralMethods.getLeftSide(l2, 1); + this.end = GeneralMethods.getLeftSide(this.end, 1); } - end = l3.clone(); - if (canPlaceBlock(l3.getBlock())) { - new TempBlock(l3.getBlock(), Material.STATIONARY_WATER, (byte) 3); - WaterArms.getBlockRevertTimes().put(l3.getBlock(), System.currentTimeMillis() + 10); - performAction(l3); - } else { - if (!l3.getBlock().getType().equals(Material.BARRIER)) { - grappled = true; + if (!this.canPlaceBlock(this.end.getBlock())) { + if (this.end.getBlock().getType() != Material.BARRIER) { + this.grappled = true; } - reverting = true; + this.reverting = true; + this.performAction(this.end); + break; } + + this.waterArms.addToArm(this.end.getBlock(), this.arm); + this.waterArms.addBlock(this.end.getBlock(), Material.STATIONARY_WATER, (byte) 2, 40); + this.performAction(this.end); + } else { + this.performAction(l2); } } } } - private void performAction(Location location) { - Location endOfArm = waterArms.getLeftArmEnd().clone(); - switch (ability) { + private void performAction(final Location location) { + final Location endOfArm = this.waterArms.getActiveArmEnd().clone(); + switch (this.ability) { case PULL: - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { if (entity instanceof Player && Commands.invincible.contains(((Player) entity).getName())) { continue; } - Vector vector = endOfArm.toVector().subtract(entity.getLocation().toVector()); - entity.setVelocity(vector.multiply(pullMultiplier)); + final Vector vector = endOfArm.toVector().subtract(entity.getLocation().toVector()); + entity.setVelocity(vector.multiply(this.pullMultiplier)); } break; case PUNCH: - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { if (entity instanceof Player && Commands.invincible.contains(((Player) entity).getName())) { continue; } - Vector vector = entity.getLocation().toVector().subtract(endOfArm.toVector()); + final Vector vector = entity.getLocation().toVector().subtract(endOfArm.toVector()); entity.setVelocity(vector.multiply(0.15)); if (entity instanceof LivingEntity) { - if (entity.getEntityId() != player.getEntityId()) { - hasDamaged = true; - DamageHandler.damageEntity(entity, punchDamage, this); + if (entity.getEntityId() != this.player.getEntityId()) { + this.hasDamaged = true; + DamageHandler.damageEntity(entity, this.punchDamage, this); } } } break; case GRAPPLE: - grapplePlayer(end); + this.grapplePlayer(location); break; case GRAB: - if (grabbedEntity == null) { - for (Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { - if (entity instanceof LivingEntity && entity.getEntityId() != player.getEntityId() && !GRABBED_ENTITIES.containsKey(entity)) { + if (this.grabbedEntity == null) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(location, 2)) { + if (entity instanceof LivingEntity && entity.getEntityId() != this.player.getEntityId() && !GRABBED_ENTITIES.containsKey(entity)) { GRABBED_ENTITIES.put((LivingEntity) entity, this); - grabbedEntity = (LivingEntity) entity; - grabbed = true; - reverting = true; - waterArms.setActiveArmCooldown(true); + this.grabbedEntity = (LivingEntity) entity; + this.grabbed = true; + this.reverting = true; + this.waterArms.setActiveArmCooldown(true); break; } } @@ -332,23 +354,23 @@ private void performAction(Location location) { } } - private void dragEntity(Location location) { - if (grabbedEntity != null && grabbed) { - if (!waterArms.canDisplayActiveArm() || grabbedEntity.isDead()) { - grabbed = false; - GRABBED_ENTITIES.remove(grabbedEntity); + private void dragEntity(final Location location) { + if (this.grabbedEntity != null && this.grabbed) { + if (!this.waterArms.canDisplayActiveArm() || this.grabbedEntity.isDead()) { + this.grabbed = false; + GRABBED_ENTITIES.remove(this.grabbedEntity); return; } - if (grabbedEntity instanceof Player && hasAbility((Player) grabbedEntity, WaterArmsWhip.class)) { - WaterArmsWhip waw = getAbility((Player) grabbedEntity, WaterArmsWhip.class); + if (this.grabbedEntity instanceof Player && hasAbility((Player) this.grabbedEntity, WaterArmsWhip.class)) { + final WaterArmsWhip waw = getAbility((Player) this.grabbedEntity, WaterArmsWhip.class); if (waw.getAbility().equals(Whip.GRAB)) { - grabbed = false; - GRABBED_ENTITIES.remove(grabbedEntity); + this.grabbed = false; + GRABBED_ENTITIES.remove(this.grabbedEntity); return; } } - Location newLocation = grabbedEntity.getLocation(); + final Location newLocation = this.grabbedEntity.getLocation(); double distance = 0; if (location.getWorld().equals(newLocation.getWorld())) { distance = location.distance(newLocation); @@ -358,35 +380,36 @@ private void dragEntity(Location location) { dx = location.getX() - newLocation.getX(); dy = location.getY() - newLocation.getY(); dz = location.getZ() - newLocation.getZ(); - Vector vector = new Vector(dx, dy, dz); + final Vector vector = new Vector(dx, dy, dz); if (distance > 0.5) { - grabbedEntity.setVelocity(vector.normalize().multiply(.65)); + this.grabbedEntity.setVelocity(vector.normalize().multiply(.65)); } else { - grabbedEntity.setVelocity(new Vector(0, 0, 0)); + this.grabbedEntity.setVelocity(new Vector(0, 0, 0)); } - grabbedEntity.setFallDistance(0); - if (grabbedEntity instanceof Creature) { - ((Creature) grabbedEntity).setTarget(null); + this.grabbedEntity.setFallDistance(0); + if (this.grabbedEntity instanceof Creature) { + ((Creature) this.grabbedEntity).setTarget(null); } } } - private void grapplePlayer(Location location) { - if (reverting && grappled && player != null && end != null && ability.equals(Whip.GRAPPLE)) { - if (GeneralMethods.isRegionProtectedFromBuild(this, location) && grappleRespectRegions) { + private void grapplePlayer(final Location location) { + if (this.reverting && this.grappled && this.player != null && this.end != null && this.ability.equals(Whip.GRAPPLE)) { + if (GeneralMethods.isRegionProtectedFromBuild(this, location) && this.grappleRespectRegions) { return; } - Vector vector = player.getLocation().toVector().subtract(location.toVector()); - player.setVelocity(vector.multiply(-0.25)); - player.setFallDistance(0); + + final Vector vector = this.player.getLocation().toVector().subtract(location.toVector()); + this.player.setVelocity(vector.multiply(-0.25)); + this.player.setFallDistance(0); } } public static void checkValidEntities() { - for (LivingEntity livingEnt : GRABBED_ENTITIES.keySet()) { - WaterArmsWhip whip = GRABBED_ENTITIES.get(livingEnt); + for (final LivingEntity livingEnt : GRABBED_ENTITIES.keySet()) { + final WaterArmsWhip whip = GRABBED_ENTITIES.get(livingEnt); if (!whip.isRemoved()) { if (whip.grabbedEntity == null) { GRABBED_ENTITIES.remove(livingEnt); @@ -400,17 +423,17 @@ public static void checkValidEntities() { @Override public void remove() { super.remove(); - if (hasAbility(player, WaterArms.class)) { - if (arm.equals(Arm.LEFT)) { - waterArms.setLeftArmCooldown(false); + if (hasAbility(this.player, WaterArms.class)) { + if (this.arm.equals(Arm.LEFT)) { + this.waterArms.setLeftArmCooldown(false); } else { - waterArms.setRightArmCooldown(false); + this.waterArms.setRightArmCooldown(false); } - if (hasDamaged) { - waterArms.setMaxPunches(waterArms.getMaxPunches() - 1); + if (this.hasDamaged) { + this.waterArms.setMaxPunches(this.waterArms.getMaxPunches() - 1); } - - waterArms.setMaxUses(waterArms.getMaxUses() - 1); + + this.waterArms.setMaxUses(this.waterArms.getMaxUses() - 1); } } @@ -429,12 +452,12 @@ public String getName() { @Override public Location getLocation() { - return end; + return this.end; } @Override public long getCooldown() { - return usageCooldown; + return this.usageCooldown; } @Override @@ -448,218 +471,218 @@ public boolean isHarmlessAbility() { } public boolean isReverting() { - return reverting; + return this.reverting; } - public void setReverting(boolean reverting) { + public void setReverting(final boolean reverting) { this.reverting = reverting; } public boolean isHasDamaged() { - return hasDamaged; + return this.hasDamaged; } - public void setHasDamaged(boolean hasDamaged) { + public void setHasDamaged(final boolean hasDamaged) { this.hasDamaged = hasDamaged; } public boolean isGrappled() { - return grappled; + return this.grappled; } - public void setGrappled(boolean grappled) { + public void setGrappled(final boolean grappled) { this.grappled = grappled; } public boolean isGrabbed() { - return grabbed; + return this.grabbed; } - public void setGrabbed(boolean grabbed) { + public void setGrabbed(final boolean grabbed) { this.grabbed = grabbed; } public boolean isGrappleRespectRegions() { - return grappleRespectRegions; + return this.grappleRespectRegions; } - public void setGrappleRespectRegions(boolean grappleRespectRegions) { + public void setGrappleRespectRegions(final boolean grappleRespectRegions) { this.grappleRespectRegions = grappleRespectRegions; } public boolean isUsageCooldownEnabled() { - return usageCooldownEnabled; + return this.usageCooldownEnabled; } - public void setUsageCooldownEnabled(boolean usageCooldownEnabled) { + public void setUsageCooldownEnabled(final boolean usageCooldownEnabled) { this.usageCooldownEnabled = usageCooldownEnabled; } public int getWhipLength() { - return whipLength; + return this.whipLength; } - public void setWhipLength(int whipLength) { + public void setWhipLength(final int whipLength) { this.whipLength = whipLength; } public int getWhipLengthWeak() { - return whipLengthWeak; + return this.whipLengthWeak; } - public void setWhipLengthWeak(int whipLengthWeak) { + public void setWhipLengthWeak(final int whipLengthWeak) { this.whipLengthWeak = whipLengthWeak; } public int getWhipLengthNight() { - return whipLengthNight; + return this.whipLengthNight; } - public void setWhipLengthNight(int whipLengthNight) { + public void setWhipLengthNight(final int whipLengthNight) { this.whipLengthNight = whipLengthNight; } public int getWhipLengthFullMoon() { - return whipLengthFullMoon; + return this.whipLengthFullMoon; } - public void setWhipLengthFullMoon(int whipLengthFullMoon) { + public void setWhipLengthFullMoon(final int whipLengthFullMoon) { this.whipLengthFullMoon = whipLengthFullMoon; } public int getInitLength() { - return initLength; + return this.initLength; } - public void setInitLength(int initLength) { + public void setInitLength(final int initLength) { this.initLength = initLength; } public int getPunchLength() { - return punchLength; + return this.punchLength; } - public void setPunchLength(int punchLength) { + public void setPunchLength(final int punchLength) { this.punchLength = punchLength; } public int getPunchLengthNight() { - return punchLengthNight; + return this.punchLengthNight; } - public void setPunchLengthNight(int punchLengthNight) { + public void setPunchLengthNight(final int punchLengthNight) { this.punchLengthNight = punchLengthNight; } public int getPunchLengthFullMoon() { - return punchLengthFullMoon; + return this.punchLengthFullMoon; } - public void setPunchLengthFullMoon(int punchLengthFullMoon) { + public void setPunchLengthFullMoon(final int punchLengthFullMoon) { this.punchLengthFullMoon = punchLengthFullMoon; } public int getActiveLength() { - return activeLength; + return this.activeLength; } - public void setActiveLength(int activeLength) { + public void setActiveLength(final int activeLength) { this.activeLength = activeLength; } public int getWhipSpeed() { - return whipSpeed; + return this.whipSpeed; } - public void setWhipSpeed(int whipSpeed) { + public void setWhipSpeed(final int whipSpeed) { this.whipSpeed = whipSpeed; } public long getHoldTime() { - return holdTime; + return this.holdTime; } - public void setHoldTime(long holdTime) { + public void setHoldTime(final long holdTime) { this.holdTime = holdTime; } public long getUsageCooldown() { - return usageCooldown; + return this.usageCooldown; } - public void setUsageCooldown(long usageCooldown) { + public void setUsageCooldown(final long usageCooldown) { this.usageCooldown = usageCooldown; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public double getPullMultiplier() { - return pullMultiplier; + return this.pullMultiplier; } - public void setPullMultiplier(double pullMultiplier) { + public void setPullMultiplier(final double pullMultiplier) { this.pullMultiplier = pullMultiplier; } public double getPunchDamage() { - return punchDamage; + return this.punchDamage; } - public void setPunchDamage(double punchDamage) { + public void setPunchDamage(final double punchDamage) { this.punchDamage = punchDamage; } public double getPlayerHealth() { - return playerHealth; + return this.playerHealth; } - public void setPlayerHealth(double playerHealth) { + public void setPlayerHealth(final double playerHealth) { this.playerHealth = playerHealth; } public Arm getArm() { - return arm; + return this.arm; } - public void setArm(Arm arm) { + public void setArm(final Arm arm) { this.arm = arm; } public Whip getAbility() { - return ability; + return this.ability; } - public void setAbility(Whip ability) { + public void setAbility(final Whip ability) { this.ability = ability; } public LivingEntity getGrabbedEntity() { - return grabbedEntity; + return this.grabbedEntity; } - public void setGrabbedEntity(LivingEntity grabbedEntity) { + public void setGrabbedEntity(final LivingEntity grabbedEntity) { this.grabbedEntity = grabbedEntity; } public Location getEnd() { - return end; + return this.end; } - public void setEnd(Location end) { + public void setEnd(final Location end) { this.end = end; } public WaterArms getWaterArms() { - return waterArms; + return this.waterArms; } - public void setWaterArms(WaterArms waterArms) { + public void setWaterArms(final WaterArms waterArms) { this.waterArms = waterArms; } diff --git a/src/com/projectkorra/projectkorra/waterbending/passive/FastSwim.java b/src/com/projectkorra/projectkorra/waterbending/passive/FastSwim.java index 84dc650d0..de4b7372b 100644 --- a/src/com/projectkorra/projectkorra/waterbending/passive/FastSwim.java +++ b/src/com/projectkorra/projectkorra/waterbending/passive/FastSwim.java @@ -4,6 +4,7 @@ import org.bukkit.entity.Player; import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.ElementalAbility; import com.projectkorra.projectkorra.ability.PassiveAbility; import com.projectkorra.projectkorra.ability.WaterAbility; import com.projectkorra.projectkorra.configuration.ConfigManager; @@ -12,36 +13,44 @@ import com.projectkorra.projectkorra.waterbending.multiabilities.WaterArms; public class FastSwim extends WaterAbility implements PassiveAbility { - private long cooldown; private double swimSpeed; + private long duration; - public FastSwim(Player player) { + public FastSwim(final Player player) { super(player); + if (this.bPlayer.isOnCooldown(this)) { + return; + } this.cooldown = ConfigManager.getConfig().getLong("Abilities.Water.Passive.FastSwim.Cooldown"); this.swimSpeed = ConfigManager.getConfig().getDouble("Abilities.Water.Passive.FastSwim.SpeedFactor"); + this.duration = ConfigManager.getConfig().getLong("Abilities.Water.Passive.FastSwim.Duration"); } @Override public void progress() { - if (bPlayer.isOnCooldown(this)) { + if (!this.bPlayer.canUsePassive(this) || !this.bPlayer.canBendPassive(this) || CoreAbility.hasAbility(this.player, WaterSpout.class) || CoreAbility.hasAbility(this.player, EarthArmor.class) || CoreAbility.hasAbility(this.player, WaterArms.class)) { return; } - if (CoreAbility.hasAbility(player, WaterSpout.class) || CoreAbility.hasAbility(player, EarthArmor.class)) { - return; - } else if (CoreAbility.hasAbility(player, WaterArms.class)) { - return; - } else if (bPlayer.getBoundAbility() == null || (bPlayer.getBoundAbility() != null && !bPlayer.getBoundAbility().isSneakAbility())) { - if (player.isSneaking() && WaterAbility.isWater(player.getLocation().getBlock())) { - player.setVelocity(player.getEyeLocation().getDirection().clone().normalize().multiply(swimSpeed)); - } - else if (!player.isSneaking()) { - bPlayer.addCooldown(this); + + if (this.bPlayer.getBoundAbility() == null || (this.bPlayer.getBoundAbility() != null && !this.bPlayer.getBoundAbility().isSneakAbility())) { + if (this.player.isSneaking() && ElementalAbility.isWater(this.player.getLocation().getBlock()) && !this.bPlayer.isOnCooldown(this)) { + if (this.duration != 0 && System.currentTimeMillis() > this.getStartTime() + this.duration) { + this.bPlayer.addCooldown(this); + return; + } + this.player.setVelocity(this.player.getEyeLocation().getDirection().clone().normalize().multiply(this.swimSpeed)); + } else if (!this.player.isSneaking()) { + this.bPlayer.addCooldown(this); } } } + public static double getSwimSpeed() { + return ConfigManager.getConfig().getDouble("Abilities.Water.Passive.FastSwim.SpeedFactor"); + } + @Override public boolean isSneakAbility() { return true; @@ -54,7 +63,7 @@ public boolean isHarmlessAbility() { @Override public long getCooldown() { - return cooldown; + return this.cooldown; } @Override @@ -64,7 +73,7 @@ public String getName() { @Override public Location getLocation() { - return null; + return this.player.getLocation(); } @Override @@ -72,4 +81,8 @@ public boolean isInstantiable() { return true; } + @Override + public boolean isProgressable() { + return true; + } } diff --git a/src/com/projectkorra/projectkorra/waterbending/passive/HydroSink.java b/src/com/projectkorra/projectkorra/waterbending/passive/HydroSink.java new file mode 100644 index 000000000..943ea2b97 --- /dev/null +++ b/src/com/projectkorra/projectkorra/waterbending/passive/HydroSink.java @@ -0,0 +1,79 @@ +package com.projectkorra.projectkorra.waterbending.passive; + +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; + +import com.projectkorra.projectkorra.ability.ElementalAbility; +import com.projectkorra.projectkorra.ability.PassiveAbility; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.command.Commands; +import com.projectkorra.projectkorra.configuration.ConfigManager; +import com.projectkorra.projectkorra.util.TempBlock; + +public class HydroSink extends WaterAbility implements PassiveAbility { + public HydroSink(final Player player) { + super(player); + } + + public static boolean applyNoFall(final Player player) { + if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { + return false; + } + + final Block block = player.getLocation().getBlock(); + final Block fallBlock = block.getRelative(BlockFace.DOWN); + if (TempBlock.isTempBlock(fallBlock) && (fallBlock.getType().equals(Material.ICE))) { + return true; + } else if (WaterAbility.isWaterbendable(player, null, block) && !ElementalAbility.isPlant(block)) { + return true; + } else if (fallBlock.getType() == Material.AIR) { + return true; + } else if ((WaterAbility.isWaterbendable(player, null, fallBlock) && !ElementalAbility.isPlant(fallBlock)) || fallBlock.getType() == Material.SNOW_BLOCK) { + return true; + } + + return false; + } + + @Override + public void progress() { + } + + @Override + public boolean isSneakAbility() { + return false; + } + + @Override + public boolean isHarmlessAbility() { + return true; + } + + @Override + public long getCooldown() { + return 0; + } + + @Override + public String getName() { + return "HydroSink"; + } + + @Override + public Location getLocation() { + return this.player.getLocation(); + } + + @Override + public boolean isInstantiable() { + return false; + } + + @Override + public boolean isProgressable() { + return false; + } +} diff --git a/src/com/projectkorra/projectkorra/waterbending/passive/Hydrosink.java b/src/com/projectkorra/projectkorra/waterbending/passive/Hydrosink.java deleted file mode 100644 index f2c40fb49..000000000 --- a/src/com/projectkorra/projectkorra/waterbending/passive/Hydrosink.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.projectkorra.projectkorra.waterbending.passive; - -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import com.projectkorra.projectkorra.ability.PassiveAbility; -import com.projectkorra.projectkorra.ability.WaterAbility; - -public class Hydrosink extends WaterAbility implements PassiveAbility { - - public Hydrosink(Player player) { - super(player); - } - - @Override - public void progress() { - - } - - @Override - public boolean isSneakAbility() { - return false; - } - - @Override - public boolean isHarmlessAbility() { - return true; - } - - @Override - public long getCooldown() { - return 0; - } - - @Override - public String getName() { - return "Hydrosink"; - } - - @Override - public Location getLocation() { - return null; - } - - @Override - public boolean isInstantiable() { - return false; - } - -} diff --git a/src/com/projectkorra/projectkorra/waterbending/passive/WaterPassive.java b/src/com/projectkorra/projectkorra/waterbending/passive/WaterPassive.java deleted file mode 100644 index 0d3ca5a05..000000000 --- a/src/com/projectkorra/projectkorra/waterbending/passive/WaterPassive.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.projectkorra.projectkorra.waterbending.passive; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; - -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.command.Commands; -import com.projectkorra.projectkorra.configuration.ConfigManager; -import com.projectkorra.projectkorra.util.TempBlock; - -public class WaterPassive { - - public static boolean applyNoFall(Player player) { - if (Commands.isToggledForAll && ConfigManager.defaultConfig.get().getBoolean("Properties.TogglePassivesWithAllBending")) { - return false; - } - Block block = player.getLocation().getBlock(); - Block fallBlock = block.getRelative(BlockFace.DOWN); - if (TempBlock.isTempBlock(fallBlock) && (fallBlock.getType().equals(Material.ICE))) { - return true; - } else if (WaterAbility.isWaterbendable(player, null, block) && !WaterAbility.isPlant(block)) { - return true; - } else if (fallBlock.getType() == Material.AIR) { - return true; - } else if ((WaterAbility.isWaterbendable(player, null, fallBlock) && !WaterAbility.isPlant(fallBlock)) || fallBlock.getType() == Material.SNOW_BLOCK) { - return true; - } - return false; - } - - /** - * Fast Swim is now managed in FastSwim.java - */ - /* - * public static void handlePassive() { if (Commands.isToggledForAll && - * ConfigManager.defaultConfig.get().getBoolean( - * "Properties.TogglePassivesWithAllBending")) { return; } - * - * double swimSpeed = getSwimSpeed(); - * - * for (Player player : Bukkit.getServer().getOnlinePlayers()) { - * BendingPlayer bPlayer = BendingPlayer.getBendingPlayer(player); if - * (bPlayer == null) { continue; } - * - * String ability = bPlayer.getBoundAbilityName(); CoreAbility coreAbil = - * CoreAbility.getAbility(ability); if - * (bPlayer.canBendPassive(Element.WATER)) { if - * (CoreAbility.hasAbility(player, WaterSpout.class) || - * CoreAbility.hasAbility(player, EarthArmor.class)) { continue; } else if - * (CoreAbility.getAbility(player, WaterArms.class) != null) { continue; } - * else if (coreAbil == null || (coreAbil != null && - * !coreAbil.isSneakAbility())) { if (player.isSneaking() && - * WaterAbility.isWater(player.getLocation().getBlock())) { - * player.setVelocity(player.getEyeLocation().getDirection().clone(). - * normalize().multiply(swimSpeed)); } } } } } - */ - - public static double getSwimSpeed() { - return ConfigManager.getConfig().getDouble("Abilities.Water.Passive.FastSwim.SpeedFactor"); - } -} diff --git a/src/com/projectkorra/projectkorra/waterbending/plant/PlantRegrowth.java b/src/com/projectkorra/projectkorra/waterbending/plant/PlantRegrowth.java index ddf4e1bf5..b44ad18f1 100644 --- a/src/com/projectkorra/projectkorra/waterbending/plant/PlantRegrowth.java +++ b/src/com/projectkorra/projectkorra/waterbending/plant/PlantRegrowth.java @@ -1,14 +1,14 @@ package com.projectkorra.projectkorra.waterbending.plant; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.PlantAbility; - import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.PlantAbility; + public class PlantRegrowth extends PlantAbility { private byte data; @@ -17,12 +17,11 @@ public class PlantRegrowth extends PlantAbility { private Material type; private Block block; - @SuppressWarnings("deprecation") - public PlantRegrowth(Player player, Block block) { + public PlantRegrowth(final Player player, final Block block) { super(player); this.regrowTime = getConfig().getLong("Abilities.Water.Plantbending.RegrowTime"); - if (regrowTime != 0) { + if (this.regrowTime != 0) { this.block = block; this.type = block.getType(); this.data = block.getData(); @@ -40,32 +39,31 @@ public PlantRegrowth(Player player, Block block) { } } - time = System.currentTimeMillis() + regrowTime / 2 + (long) (Math.random() * (double) regrowTime) / 2; - start(); + this.time = System.currentTimeMillis() + this.regrowTime / 2 + (long) (Math.random() * this.regrowTime) / 2; + this.start(); } } @Override - @SuppressWarnings("deprecation") public void remove() { super.remove(); - if (block.getType() == Material.AIR) { - block.setType(type); - block.setData(data); - if (type == Material.DOUBLE_PLANT) { - block.getRelative(BlockFace.UP).setType(Material.DOUBLE_PLANT); - block.getRelative(BlockFace.UP).setData((byte) 10); + if (this.block.getType() == Material.AIR) { + this.block.setType(this.type); + this.block.setData(this.data); + if (this.type == Material.DOUBLE_PLANT) { + this.block.getRelative(BlockFace.UP).setType(Material.DOUBLE_PLANT); + this.block.getRelative(BlockFace.UP).setData((byte) 10); } } else { - GeneralMethods.dropItems(block, GeneralMethods.getDrops(block, type, data, null)); + GeneralMethods.dropItems(this.block, GeneralMethods.getDrops(this.block, this.type, this.data, null)); } } @Override public void progress() { - if (time < System.currentTimeMillis()) { - remove(); + if (this.time < System.currentTimeMillis()) { + this.remove(); } } @@ -76,7 +74,7 @@ public String getName() { @Override public Location getLocation() { - return block != null ? block.getLocation() : null; + return this.block != null ? this.block.getLocation() : null; } @Override @@ -100,42 +98,42 @@ public boolean isHarmlessAbility() { } public byte getData() { - return data; + return this.data; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getRegrowTime() { - return regrowTime; + return this.regrowTime; } - public void setRegrowTime(long regrowTime) { + public void setRegrowTime(final long regrowTime) { this.regrowTime = regrowTime; } public Material getType() { - return type; + return this.type; } - public void setType(Material type) { + public void setType(final Material type) { this.type = type; } public Block getBlock() { - return block; + return this.block; } - public void setBlock(Block block) { + public void setBlock(final Block block) { this.block = block; } diff --git a/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java b/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java index 4240b7bd3..5b158aa64 100644 --- a/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java +++ b/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java @@ -1,13 +1,6 @@ package com.projectkorra.projectkorra.waterbending.util; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.util.ParticleEffect; -import com.projectkorra.projectkorra.util.TempBlock; -import com.projectkorra.projectkorra.waterbending.OctopusForm; -import com.projectkorra.projectkorra.waterbending.SurgeWall; -import com.projectkorra.projectkorra.waterbending.WaterManipulation; -import com.projectkorra.projectkorra.waterbending.ice.IceSpikeBlast; +import java.util.HashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -19,7 +12,14 @@ import org.bukkit.potion.PotionType; import org.bukkit.util.Vector; -import java.util.HashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.util.ParticleEffect; +import com.projectkorra.projectkorra.util.TempBlock; +import com.projectkorra.projectkorra.waterbending.OctopusForm; +import com.projectkorra.projectkorra.waterbending.SurgeWall; +import com.projectkorra.projectkorra.waterbending.WaterManipulation; +import com.projectkorra.projectkorra.waterbending.ice.IceSpikeBlast; public class WaterReturn extends WaterAbility { @@ -29,7 +29,7 @@ public class WaterReturn extends WaterAbility { private Location location; private TempBlock block; - public WaterReturn(Player player, Block block) { + public WaterReturn(final Player player, final Block block) { super(player); if (hasAbility(player, WaterReturn.class)) { return; @@ -39,57 +39,57 @@ public WaterReturn(Player player, Block block) { this.range = 30; this.interval = 50; - this.range = getNightFactor(range); + this.range = this.getNightFactor(this.range); - if (bPlayer.canBendIgnoreBindsCooldowns(this)) { - if (isTransparent(player, block) && ((TempBlock.isTempBlock(block) && block.isLiquid()) || !block.isLiquid()) && hasEmptyWaterBottle()) { + if (this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + if (isTransparent(player, block) && ((TempBlock.isTempBlock(block) && block.isLiquid()) || !block.isLiquid()) && this.hasEmptyWaterBottle()) { this.block = new TempBlock(block, Material.WATER, (byte) 0); } } - start(); + this.start(); } @Override public void progress() { - if (!bPlayer.canBendIgnoreBindsCooldowns(this)) { - remove(); + if (!this.bPlayer.canBendIgnoreBindsCooldowns(this)) { + this.remove(); return; - } else if (!hasEmptyWaterBottle()) { - remove(); + } else if (!this.hasEmptyWaterBottle()) { + this.remove(); return; - } else if (System.currentTimeMillis() < time + interval) { + } else if (System.currentTimeMillis() < this.time + this.interval) { return; } - Vector direction = GeneralMethods.getDirection(location, player.getEyeLocation()).normalize(); - time = System.currentTimeMillis(); - location = location.clone().add(direction); + final Vector direction = GeneralMethods.getDirection(this.location, this.player.getEyeLocation()).normalize(); + this.time = System.currentTimeMillis(); + this.location = this.location.clone().add(direction); - if (location == null || block == null) { - remove(); + if (this.location == null || this.block == null) { + this.remove(); return; - } else if (location.getBlock().equals(block.getLocation().getBlock())) { + } else if (this.location.getBlock().equals(this.block.getLocation().getBlock())) { return; } - if (location.distanceSquared(player.getEyeLocation()) > range * range) { - remove(); + if (this.location.distanceSquared(this.player.getEyeLocation()) > this.range * this.range) { + this.remove(); return; - } else if (location.distanceSquared(player.getEyeLocation()) <= 1.5 * 1.5) { - fillBottle(); + } else if (this.location.distanceSquared(this.player.getEyeLocation()) <= 1.5 * 1.5) { + this.fillBottle(); return; } - Block newblock = location.getBlock(); - if (isTransparent(player, newblock) && !newblock.isLiquid()) { - block.revertBlock(); - block = new TempBlock(newblock, Material.WATER, (byte) 0); - } else if (isTransparent(player, newblock)) { + final Block newblock = this.location.getBlock(); + if (isTransparent(this.player, newblock) && !newblock.isLiquid()) { + this.block.revertBlock(); + this.block = new TempBlock(newblock, Material.WATER, (byte) 0); + } else if (isTransparent(this.player, newblock)) { if (isWater(newblock)) { ParticleEffect.WATER_BUBBLE.display((float) Math.random(), (float) Math.random(), (float) Math.random(), 0f, 5, newblock.getLocation().clone().add(.5, .5, .5), 255.0); } } else { - remove(); + this.remove(); return; } @@ -98,13 +98,13 @@ public void progress() { @Override public void remove() { super.remove(); - if (block != null) { - block.revertBlock(); + if (this.block != null) { + this.block.revertBlock(); } } private boolean hasEmptyWaterBottle() { - PlayerInventory inventory = player.getInventory(); + final PlayerInventory inventory = this.player.getInventory(); if (inventory.contains(Material.GLASS_BOTTLE)) { return true; } @@ -112,56 +112,59 @@ private boolean hasEmptyWaterBottle() { } private void fillBottle() { - PlayerInventory inventory = player.getInventory(); + final PlayerInventory inventory = this.player.getInventory(); if (inventory.contains(Material.GLASS_BOTTLE)) { - int index = inventory.first(Material.GLASS_BOTTLE); - ItemStack item = inventory.getItem(index); + final int index = inventory.first(Material.GLASS_BOTTLE); + final ItemStack item = inventory.getItem(index); if (item.getAmount() == 1) { inventory.setItem(index, new ItemStack(Material.POTION)); } else { item.setAmount(item.getAmount() - 1); inventory.setItem(index, item); - HashMap leftover = inventory.addItem(new ItemStack(Material.POTION)); - for (int left : leftover.keySet()) { - player.getWorld().dropItemNaturally(player.getLocation(), leftover.get(left)); + final HashMap leftover = inventory.addItem(new ItemStack(Material.POTION)); + for (final int left : leftover.keySet()) { + this.player.getWorld().dropItemNaturally(this.player.getLocation(), leftover.get(left)); } } } - remove(); + this.remove(); } - private static boolean isBending(Player player) { + private static boolean isBending(final Player player) { if (hasAbility(player, WaterManipulation.class) || hasAbility(player, WaterManipulation.class) || hasAbility(player, OctopusForm.class) - // || hasAbility(player, SurgeWave.class) NOTE: ONLY DISABLED TO PREVENT BOTTLEBENDING FROM BEING DISABLED FOREVER. ONCE BOTTLEBENDING HAS BEEN RECODED IN 1.9, THIS NEEDS TO BE READDED TO THE NEW SYSTEM. + // || hasAbility(player, SurgeWave.class) NOTE: ONLY DISABLED TO + // PREVENT BOTTLEBENDING FROM BEING DISABLED FOREVER. ONCE + // BOTTLEBENDING HAS BEEN RECODED IN 1.9, THIS NEEDS TO BE + // READDED TO THE NEW SYSTEM. || hasAbility(player, SurgeWall.class) || hasAbility(player, IceSpikeBlast.class)) { return true; } return false; } - public static boolean hasWaterBottle(Player player) { + public static boolean hasWaterBottle(final Player player) { if (hasAbility(player, WaterReturn.class) || isBending(player)) { return false; } - PlayerInventory inventory = player.getInventory(); + final PlayerInventory inventory = player.getInventory(); if (inventory.contains(Material.POTION)) { - ItemStack item = inventory.getItem(inventory.first(Material.POTION)); - PotionMeta meta = (PotionMeta) item.getItemMeta(); - return meta.getBasePotionData().getType().equals(PotionType.WATER); + final ItemStack item = inventory.getItem(inventory.first(Material.POTION)); + final PotionMeta meta = (PotionMeta) item.getItemMeta(); + return meta.getBasePotionData().getType() == PotionType.WATER; } return false; } - public static void emptyWaterBottle(Player player) { - PlayerInventory inventory = player.getInventory(); + public static void emptyWaterBottle(final Player player) { + final PlayerInventory inventory = player.getInventory(); int index = inventory.first(Material.POTION); - //Check that the first one found is actually a WATER bottle. We aren't implementing potion bending just yet ;) + // Check that the first one found is actually a WATER bottle. We aren't implementing potion bending just yet. if (index != -1 && !((PotionMeta) inventory.getItem(index).getItemMeta()).getBasePotionData().getType().equals(PotionType.WATER)) { for (int i = 0; i < inventory.getSize(); i++) { if (inventory.getItem(i).getType() == Material.POTION) { - PotionMeta meta = (PotionMeta) inventory.getItem(i).getItemMeta(); + final PotionMeta meta = (PotionMeta) inventory.getItem(i).getItemMeta(); if (meta.getBasePotionData().getType().equals(PotionType.WATER)) { index = i; break; @@ -171,15 +174,15 @@ public static void emptyWaterBottle(Player player) { } if (index != -1) { - ItemStack item = inventory.getItem(index); + final ItemStack item = inventory.getItem(index); if (item.getAmount() == 1) { inventory.setItem(index, new ItemStack(Material.GLASS_BOTTLE)); } else { item.setAmount(item.getAmount() - 1); inventory.setItem(index, item); - HashMap leftover = inventory.addItem(new ItemStack(Material.GLASS_BOTTLE)); + final HashMap leftover = inventory.addItem(new ItemStack(Material.GLASS_BOTTLE)); - for (int left : leftover.keySet()) { + for (final int left : leftover.keySet()) { player.getWorld().dropItemNaturally(player.getLocation(), leftover.get(left)); } } @@ -187,32 +190,32 @@ public static void emptyWaterBottle(Player player) { } public long getTime() { - return time; + return this.time; } - public void setTime(long time) { + public void setTime(final long time) { this.time = time; } public long getInterval() { - return interval; + return this.interval; } - public void setInterval(long interval) { + public void setInterval(final long interval) { this.interval = interval; } public double getRange() { - return range; + return this.range; } - public void setRange(double range) { + public void setRange(final double range) { this.range = range; } @Override public Location getLocation() { - return location; + return this.location; } @Override @@ -225,15 +228,15 @@ public boolean isHarmlessAbility() { return true; } - public void setLocation(Location location) { + public void setLocation(final Location location) { this.location = location; } public TempBlock getBlock() { - return block; + return this.block; } - public void setBlock(TempBlock block) { + public void setBlock(final TempBlock block) { this.block = block; } diff --git a/src/com/projectkorra/projectkorra/waterbending/util/WaterSourceGrabber.java b/src/com/projectkorra/projectkorra/waterbending/util/WaterSourceGrabber.java index 7742e92ce..489da3f13 100644 --- a/src/com/projectkorra/projectkorra/waterbending/util/WaterSourceGrabber.java +++ b/src/com/projectkorra/projectkorra/waterbending/util/WaterSourceGrabber.java @@ -1,8 +1,9 @@ package com.projectkorra.projectkorra.waterbending.util; -import com.projectkorra.projectkorra.GeneralMethods; -import com.projectkorra.projectkorra.ability.WaterAbility; -import com.projectkorra.projectkorra.util.TempBlock; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; import org.bukkit.Material; @@ -10,10 +11,9 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.WaterAbility; +import com.projectkorra.projectkorra.util.TempBlock; public class WaterSourceGrabber { @@ -31,13 +31,13 @@ public static enum AnimationState { private AnimationState state; private Material material; private Location currentLoc; - private Map affectedBlocks; + private final Map affectedBlocks; - public WaterSourceGrabber(Player player, Location origin) { + public WaterSourceGrabber(final Player player, final Location origin) { this(player, origin, 1); } - public WaterSourceGrabber(Player player, Location origin, double animationSpeed) { + public WaterSourceGrabber(final Player player, final Location origin, final double animationSpeed) { this.player = player; this.animimationSpeed = animationSpeed; this.material = Material.STATIONARY_WATER; @@ -48,114 +48,114 @@ public WaterSourceGrabber(Player player, Location origin, double animationSpeed) } public void progress() { - if (state == AnimationState.FAILED || state == AnimationState.FINISHED) { + if (this.state == AnimationState.FAILED || this.state == AnimationState.FINISHED) { return; - } else if (state == AnimationState.RISING) { - revertBlocks(); - double locDiff = player.getEyeLocation().getY() - currentLoc.getY(); - currentLoc.add(0, animimationSpeed * Math.signum(locDiff), 0); - Block block = currentLoc.getBlock(); - - if (!(WaterAbility.isWaterbendable(player, null, block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(player, "WaterSpout", block.getLocation())) { - remove(); + } else if (this.state == AnimationState.RISING) { + this.revertBlocks(); + final double locDiff = this.player.getEyeLocation().getY() - this.currentLoc.getY(); + this.currentLoc.add(0, this.animimationSpeed * Math.signum(locDiff), 0); + final Block block = this.currentLoc.getBlock(); + + if (!(WaterAbility.isWaterbendable(this.player, null, block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this.player, "WaterSpout", block.getLocation())) { + this.remove(); return; } - createBlock(block, material, data); + this.createBlock(block, this.material, this.data); if (Math.abs(locDiff) < 1) { - state = AnimationState.TOWARD; + this.state = AnimationState.TOWARD; } } else { - revertBlocks(); - Location eyeLoc = player.getTargetBlock((HashSet) null, 2).getLocation(); - eyeLoc.setY(player.getEyeLocation().getY()); - Vector vec = GeneralMethods.getDirection(currentLoc, eyeLoc); - currentLoc.add(vec.normalize().multiply(animimationSpeed)); - - Block block = currentLoc.getBlock(); - if (!(WaterAbility.isWaterbendable(player, null, block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(player, "WaterManipulation", block.getLocation())) { - remove(); + this.revertBlocks(); + final Location eyeLoc = this.player.getTargetBlock((HashSet) null, 2).getLocation(); + eyeLoc.setY(this.player.getEyeLocation().getY()); + final Vector vec = GeneralMethods.getDirection(this.currentLoc, eyeLoc); + this.currentLoc.add(vec.normalize().multiply(this.animimationSpeed)); + + final Block block = this.currentLoc.getBlock(); + if (!(WaterAbility.isWaterbendable(this.player, null, block) || block.getType() == Material.AIR) || GeneralMethods.isRegionProtectedFromBuild(this.player, "WaterManipulation", block.getLocation())) { + this.remove(); return; } - createBlock(block, material, data); - if (currentLoc.distanceSquared(eyeLoc) < 1.2) { - state = AnimationState.FINISHED; - revertBlocks(); + this.createBlock(block, this.material, this.data); + if (this.currentLoc.distanceSquared(eyeLoc) < 1.2) { + this.state = AnimationState.FINISHED; + this.revertBlocks(); } } } public AnimationState getState() { - return state; + return this.state; } public void remove() { - state = AnimationState.FAILED; + this.state = AnimationState.FAILED; } public void revertBlocks() { - Iterator keys = affectedBlocks.keySet().iterator(); + final Iterator keys = this.affectedBlocks.keySet().iterator(); while (keys.hasNext()) { - Block block = keys.next(); - affectedBlocks.get(block).revertBlock(); - affectedBlocks.remove(block); + final Block block = keys.next(); + this.affectedBlocks.get(block).revertBlock(); + this.affectedBlocks.remove(block); } } - public void createBlock(Block block, Material mat) { - createBlock(block, mat, (byte) 0); + public void createBlock(final Block block, final Material mat) { + this.createBlock(block, mat, (byte) 0); } - public void createBlock(Block block, Material mat, byte data) { - affectedBlocks.put(block, new TempBlock(block, mat, data)); + public void createBlock(final Block block, final Material mat, final byte data) { + this.affectedBlocks.put(block, new TempBlock(block, mat, data)); } public Player getPlayer() { - return player; + return this.player; } - public void setPlayer(Player player) { + public void setPlayer(final Player player) { this.player = player; } public byte getData() { - return data; + return this.data; } - public void setData(byte data) { + public void setData(final byte data) { this.data = data; } public double getAnimimationSpeed() { - return animimationSpeed; + return this.animimationSpeed; } - public void setAnimimationSpeed(double animimationSpeed) { + public void setAnimimationSpeed(final double animimationSpeed) { this.animimationSpeed = animimationSpeed; } public Material getMaterial() { - return material; + return this.material; } - public void setMaterial(Material material) { + public void setMaterial(final Material material) { this.material = material; } public Location getCurrentLoc() { - return currentLoc; + return this.currentLoc; } - public void setCurrentLoc(Location currentLoc) { + public void setCurrentLoc(final Location currentLoc) { this.currentLoc = currentLoc; } public Map getAffectedBlocks() { - return affectedBlocks; + return this.affectedBlocks; } - public void setState(AnimationState state) { + public void setState(final AnimationState state) { this.state = state; } diff --git a/src/com/projectkorra/projectkorra/waterbending/util/WaterbendingManager.java b/src/com/projectkorra/projectkorra/waterbending/util/WaterbendingManager.java index 8fd375d8c..9080e7506 100644 --- a/src/com/projectkorra/projectkorra/waterbending/util/WaterbendingManager.java +++ b/src/com/projectkorra/projectkorra/waterbending/util/WaterbendingManager.java @@ -9,13 +9,13 @@ public class WaterbendingManager implements Runnable { public ProjectKorra plugin; - public WaterbendingManager(ProjectKorra plugin) { + public WaterbendingManager(final ProjectKorra plugin) { this.plugin = plugin; } @Override public void run() { - //WaterPassive.handlePassive(); # Fast Swim is now managed in FastSwim.java + // WaterPassive.handlePassive(); # Fast Swim is now managed in FastSwim.java. Torrent.progressAllCleanup(); WaterArms.progressAllCleanup(); WaterSpoutWave.progressAllCleanup(); diff --git a/src/plugin.yml b/src/plugin.yml index fbfec6408..109c901ec 100644 --- a/src/plugin.yml +++ b/src/plugin.yml @@ -20,6 +20,7 @@ permissions: bending.command.add: true bending.command.rechoose: true bending.admin.choose: true + bending.choose.ignorecooldown: true bending.ability.AvatarState: true bending.water.bloodbending.anytime: true bending.water.bloodbending: true @@ -53,7 +54,7 @@ permissions: bending.command.clear: true bending.command.who: true bending.command.preset.list: true - bending.command.preset.create.2: true + bending.command.preset.create.5: true bending.command.preset.create: true bending.command.preset.bind: true bending.command.preset.delete: true @@ -137,6 +138,7 @@ permissions: bending.ability.LavaFlow: true bending.ability.EarthSmash: true bending.ability.SandSpout: true + bending.ability.EarthCombo: true bending.fire: default: true description: Grants access to all firebending abilities. @@ -153,6 +155,7 @@ permissions: bending.ability.Lightning: true bending.ability.WallOfFire: true bending.ability.Combustion: true + bending.ability.FireManipulation: true bending.ability.FireCombo: true bending.message.daymessage: true bending.fire.passive: true @@ -187,31 +190,38 @@ permissions: default: false description: Grants access to all AirCombos. children: - bending.ability.AirSweep: true - bending.ability.AirStream: true - bending.ability.Twister: true + bending.ability.AirSweep: true + bending.ability.AirStream: true + bending.ability.Twister: true bending.ability.WaterCombo: default: false description: Grants access to all WaterCombos. children: - bending.ability.IceWave: true - bending.ability.IceBullet: true - bending.ability.IceBulletLeftClick: true - bending.ability.IceBulletRightClick: true + bending.ability.IceWave: true + bending.ability.IceBullet: true + bending.ability.IceBulletLeftClick: true + bending.ability.IceBulletRightClick: true + bending.ability.EarthCombo: + default: false + description: Grants access to all EarthCombos. + children: + bending.ability.EarthPillars: true + bending.ability.EarthDome: true + bending.ability.EarthDomeOthers: true bending.ability.FireCombo: default: false description: Grants access to all FireCombos. children: - bending.ability.FireKick: true - bending.ability.FireSpin: true - bending.ability.JetBlast: true - bending.ability.JetBlaze: true - bending.ability.FireWheel: true + bending.ability.FireKick: true + bending.ability.FireSpin: true + bending.ability.JetBlast: true + bending.ability.JetBlaze: true + bending.ability.FireWheel: true bending.ability.ChiCombo: default: false description: Grants access to all ChiCombos. children: - bending.ability.Immobilize: true + bending.ability.Immobilize: true bending.air.passive: default: false description: Grants access to all air passives.