From 563775016686ce21897c5570182a0d8d8ebe629b Mon Sep 17 00:00:00 2001 From: Josh Date: Thu, 22 Aug 2019 17:04:04 -0400 Subject: [PATCH 01/22] Change AirSweep and FireJet + Lightning (#1007) ## Additions * Adds HorizontalVelocityTracker to AirSweep * Adds GeneralMethods#getMainHandLocation(final Player player) ## Changes * Changed AirSweep and AirSwipe to originate from a Player's main hand location * Changed the knockback caused by AirSweep more consistent in the air and on the ground * Disable Lightning use when using FireJet --- .../projectkorra/GeneralMethods.java | 11 +++++++ .../projectkorra/airbending/AirSwipe.java | 2 +- .../airbending/combo/AirSweep.java | 30 ++++++++++--------- .../firebending/lightning/Lightning.java | 5 ++++ 4 files changed, 33 insertions(+), 15 deletions(-) diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index 7c86931c..1c7c24d8 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -81,6 +81,7 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.MainHand; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -1107,6 +1108,16 @@ public class GeneralMethods { return location.clone().subtract(new Vector(Math.cos(angle), 0, Math.sin(angle)).normalize().multiply(distance)); } + public static Location getMainHandLocation(final Player player) { + Location loc; + if (player.getMainHand() == MainHand.LEFT) { + loc = GeneralMethods.getLeftSide(player.getLocation(), .55).add(0, 1.2, 0); + } else { + loc = GeneralMethods.getRightSide(player.getLocation(), .55).add(0, 1.2, 0); + } + return loc; + } + public static Plugin getProbending() { if (hasProbending()) { return Bukkit.getServer().getPluginManager().getPlugin("Probending"); diff --git a/src/com/projectkorra/projectkorra/airbending/AirSwipe.java b/src/com/projectkorra/projectkorra/airbending/AirSwipe.java index bc10f48a..999bfa45 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirSwipe.java +++ b/src/com/projectkorra/projectkorra/airbending/AirSwipe.java @@ -77,7 +77,7 @@ public class AirSwipe extends AirAbility { } this.charging = charging; - this.origin = player.getEyeLocation(); + this.origin = GeneralMethods.getMainHandLocation(player); this.particles = getConfig().getInt("Abilities.Air.AirSwipe.Particles"); this.arc = getConfig().getInt("Abilities.Air.AirSwipe.Arc"); this.arcIncrement = getConfig().getInt("Abilities.Air.AirSwipe.StepSize"); diff --git a/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java b/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java index 2c2cc797..5bbfd83d 100644 --- a/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java +++ b/src/com/projectkorra/projectkorra/airbending/combo/AirSweep.java @@ -3,6 +3,7 @@ package com.projectkorra.projectkorra.airbending.combo; import java.util.ArrayList; import java.util.List; +import com.projectkorra.projectkorra.object.HorizontalVelocityTracker; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -131,22 +132,23 @@ public class AirSweep extends AirAbility implements ComboAbility { if (this.origin == null) { this.direction = this.player.getEyeLocation().getDirection().normalize(); - this.origin = this.player.getLocation().add(this.direction.clone().multiply(10)); + this.origin = GeneralMethods.getMainHandLocation(player).add(this.direction.clone().multiply(10)); } if (this.progressCounter < 8) { return; } if (this.destination == null) { - this.destination = this.player.getLocation().add(this.player.getEyeLocation().getDirection().normalize().multiply(10)); + this.destination = GeneralMethods.getMainHandLocation(player).add(GeneralMethods.getMainHandLocation(player).getDirection().normalize().multiply(10)); final Vector origToDest = GeneralMethods.getDirection(this.origin, this.destination); + final Location hand = GeneralMethods.getMainHandLocation(player); for (double i = 0; i < 30; i++) { final Location endLoc = this.origin.clone().add(origToDest.clone().multiply(i / 30)); - if (GeneralMethods.locationEqualsIgnoreDirection(this.player.getLocation(), endLoc)) { + if (GeneralMethods.locationEqualsIgnoreDirection(hand, endLoc)) { continue; } - final Vector vec = GeneralMethods.getDirection(this.player.getLocation(), endLoc); + final Vector vec = GeneralMethods.getDirection(hand, endLoc); - final FireComboStream fs = new FireComboStream(this.player, this, vec, this.player.getLocation(), this.range, this.speed); + final FireComboStream fs = new FireComboStream(this.player, this, vec, hand, this.range, this.speed); fs.setDensity(1); fs.setSpread(0F); fs.setUseNewParticles(true); @@ -191,17 +193,17 @@ public class AirSweep extends AirAbility implements ComboAbility { this.remove(); return; } - if (!entity.equals(this.player) && !this.affectedEntities.contains(entity) && !(entity instanceof Player && Commands.invincible.contains(((Player) entity).getName()))) { - this.affectedEntities.add(entity); + if (!entity.equals(this.player) && !(entity instanceof Player && Commands.invincible.contains(((Player) entity).getName()))) { if (this.knockback != 0) { - final Vector force = fstream.getDirection(); - entity.setVelocity(force.multiply(this.knockback)); + final Vector force = fstream.getLocation().getDirection(); + GeneralMethods.setVelocity(entity, force.clone().multiply(this.knockback)); + new HorizontalVelocityTracker(entity, this.player, 200l, this); + entity.setFallDistance(0); } - if (this.damage != 0) { - if (entity instanceof LivingEntity) { - if (fstream.getAbility().getName().equalsIgnoreCase("AirSweep")) { - DamageHandler.damageEntity(entity, this.damage, this); - } else { + if(!this.affectedEntities.contains(entity)) { + this.affectedEntities.add(entity); + if (this.damage != 0) { + if (entity instanceof LivingEntity) { DamageHandler.damageEntity(entity, this.damage, this); } } diff --git a/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java b/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java index ed0c15d7..93393abc 100644 --- a/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java +++ b/src/com/projectkorra/projectkorra/firebending/lightning/Lightning.java @@ -3,6 +3,8 @@ package com.projectkorra.projectkorra.firebending.lightning; import java.util.ArrayList; import java.util.List; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.firebending.FireJet; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Entity; @@ -180,6 +182,9 @@ public class Lightning extends LightningAbility { } else if (!this.bPlayer.canBendIgnoreCooldowns(this)) { this.remove(); return; + } else if (CoreAbility.hasAbility(player, FireJet.class)){ + this.removeWithTasks(); + return; } this.locations.clear(); From 3972104586793a384e87e4bad823a53280800458 Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Thu, 22 Aug 2019 17:45:23 -0400 Subject: [PATCH 02/22] Fix config issues in AirBlast, AirSuction, and EarthSmash (#1008) ## Additions * Adds self/others options for AirSuction ## Fixes * Fixes AirBlast push self and others being mixed up * Fixes AirBlast not using self push at all * #1006 * Fixes EarthSmash using nonexistent AvatarState config options ## Removals * Removes unnecessary arithmetic from AirBlast and AirSuction in determining knockback power * Defaults in config have been changed to make up for removing the arithmetic --- .../projectkorra/airbending/AirBlast.java | 98 ++++++++++--------- .../projectkorra/airbending/AirSuction.java | 34 ++++--- .../configuration/ConfigManager.java | 7 +- .../projectkorra/earthbending/EarthSmash.java | 8 +- 4 files changed, 77 insertions(+), 70 deletions(-) diff --git a/src/com/projectkorra/projectkorra/airbending/AirBlast.java b/src/com/projectkorra/projectkorra/airbending/AirBlast.java index c31ed585..938f841b 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirBlast.java +++ b/src/com/projectkorra/projectkorra/airbending/AirBlast.java @@ -141,8 +141,8 @@ public class AirBlast extends AirAbility { this.speed = getConfig().getDouble("Abilities.Air.AirBlast.Speed"); this.range = getConfig().getDouble("Abilities.Air.AirBlast.Range"); this.radius = getConfig().getDouble("Abilities.Air.AirBlast.Radius"); - this.pushFactor = getConfig().getDouble("Abilities.Air.AirBlast.Push.Entities"); - this.pushFactorForOthers = getConfig().getDouble("Abilities.Air.AirBlast.Push.Self"); + this.pushFactor = getConfig().getDouble("Abilities.Air.AirBlast.Push.Self"); + this.pushFactorForOthers = getConfig().getDouble("Abilities.Air.AirBlast.Push.Entities"); this.canFlickLevers = getConfig().getBoolean("Abilities.Air.AirBlast.CanFlickLevers"); this.canOpenDoors = getConfig().getBoolean("Abilities.Air.AirBlast.CanOpenDoors"); this.canPressButtons = getConfig().getBoolean("Abilities.Air.AirBlast.CanPressButtons"); @@ -212,14 +212,26 @@ public class AirBlast extends AirAbility { } private void affect(final Entity entity) { - final boolean isUser = entity.getUniqueId() == this.player.getUniqueId(); - - if (!isUser || this.isFromOtherOrigin) { - this.pushFactor = this.pushFactorForOthers; - final Vector velocity = entity.getVelocity(); + if (entity instanceof Player) { + if (Commands.invincible.contains(((Player) entity).getName())) { + return; + } + } + + if (!affectedEntities.contains(entity)) { + final boolean isUser = entity.getUniqueId() == this.player.getUniqueId(); + double knockback = this.pushFactorForOthers; + + if (isUser) { + if (isFromOtherOrigin) { + knockback = this.pushFactor; + } else { + return; + } + } + final double max = this.speed / this.speedFactor; - double factor = this.pushFactor; - + final Vector push = this.direction.clone(); if (Math.abs(push.getY()) > max && !isUser) { if (push.getY() < 0) { @@ -228,56 +240,46 @@ public class AirBlast extends AirAbility { push.setY(max); } } + if (this.location.getWorld().equals(this.origin.getWorld())) { - factor *= 1 - this.location.distance(this.origin) / (2 * this.range); + knockback *= 1 - this.location.distance(this.origin) / (2 * this.range); } - - if (isUser && GeneralMethods.isSolid(this.player.getLocation().add(0, -.5, 0).getBlock())) { - factor *= .5; + + if (GeneralMethods.isSolid(entity.getLocation().add(0, -.5, 0).getBlock())) { + knockback *= .5; } - - 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()))); - } else if (comp + factor * .5 > factor) { - velocity.add(push.clone().multiply(factor - comp)); - } else { - velocity.add(push.clone().multiply(factor * .5)); + + push.normalize().multiply(knockback); + + if (Math.abs(entity.getVelocity().dot(push)) > knockback) { + push.normalize().add(entity.getVelocity()).multiply(knockback); } - - if (entity instanceof Player) { - if (Commands.invincible.contains(((Player) entity).getName())) { - return; - } - } - - if (Double.isNaN(velocity.length())) { - return; - } - - GeneralMethods.setVelocity(entity, velocity); + + GeneralMethods.setVelocity(entity, push); + if (this.source != null) { new HorizontalVelocityTracker(entity, this.player, 200l, this.source); } else { new HorizontalVelocityTracker(entity, this.player, 200l, this); } - - if (entity.getFireTicks() > 0) { - entity.getWorld().playEffect(entity.getLocation(), Effect.EXTINGUISH, 0); - } - - entity.setFireTicks(0); - breakBreathbendingHold(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); + + if (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(this.player)) { + if (this.source != null) { + DamageHandler.damageEntity(entity, this.damage, this.source); + } else { + DamageHandler.damageEntity(entity, this.damage, this); + } } + + this.affectedEntities.add(entity); } + + if (entity.getFireTicks() > 0) { + entity.getWorld().playEffect(entity.getLocation(), Effect.EXTINGUISH, 0); + } + + entity.setFireTicks(0); + breakBreathbendingHold(entity); } @Override diff --git a/src/com/projectkorra/projectkorra/airbending/AirSuction.java b/src/com/projectkorra/projectkorra/airbending/AirSuction.java index 8a494387..3aff0212 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirSuction.java +++ b/src/com/projectkorra/projectkorra/airbending/AirSuction.java @@ -42,6 +42,8 @@ public class AirSuction extends AirAbility { private double radius; @Attribute(Attribute.KNOCKBACK) private double pushFactor; + @Attribute(Attribute.KNOCKBACK + "Others") + private double pushFactorForOthers; private Random random; private Location location; private Location origin; @@ -76,7 +78,8 @@ public class AirSuction extends AirAbility { this.speed = getConfig().getDouble("Abilities.Air.AirSuction.Speed"); this.range = getConfig().getDouble("Abilities.Air.AirSuction.Range"); this.radius = getConfig().getDouble("Abilities.Air.AirSuction.Radius"); - this.pushFactor = getConfig().getDouble("Abilities.Air.AirSuction.Push"); + this.pushFactor = getConfig().getDouble("Abilities.Air.AirSuction.Push.Self"); + this.pushFactorForOthers = getConfig().getDouble("Abilities.Air.AirSuction.Push.Others"); this.cooldown = getConfig().getLong("Abilities.Air.AirSuction.Cooldown"); this.random = new Random(); this.origin = this.getTargetLocation(); @@ -201,10 +204,15 @@ public class AirSuction extends AirAbility { if ((entity.getEntityId() == this.player.getEntityId()) && !this.canAffectSelf) { continue; } - final Vector velocity = entity.getVelocity(); + + double knockback = this.pushFactor; + + if (entity.getEntityId() != player.getEntityId()) { + knockback = this.pushFactorForOthers; + } + final double max = this.speed; final Vector push = this.direction.clone(); - double factor = this.pushFactor; if (Math.abs(push.getY()) > max) { if (push.getY() < 0) { @@ -215,20 +223,16 @@ public class AirSuction extends AirAbility { } if (this.location.getWorld().equals(this.origin.getWorld())) { - factor *= 1 - this.location.distance(this.origin) / (2 * this.range); + knockback *= 1 - this.location.distance(this.origin) / (2 * this.range); + } + + push.normalize().multiply(knockback); + + if (Math.abs(entity.getVelocity().dot(push)) > knockback) { + push.normalize().add(entity.getVelocity()).multiply(knockback); } - 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()))); - } else if (comp + factor * .5 > factor) { - velocity.add(push.clone().multiply(factor - comp)); - } else { - velocity.add(push.clone().multiply(factor * .5)); - } - - GeneralMethods.setVelocity(entity, velocity); + GeneralMethods.setVelocity(entity, push.normalize().multiply(knockback)); new HorizontalVelocityTracker(entity, this.player, 200l, this); entity.setFallDistance(0); diff --git a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java index 7a0b08a3..e90002d9 100644 --- a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java +++ b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java @@ -802,8 +802,8 @@ public class ConfigManager { config.addDefault("Abilities.Air.AirBlast.SelectParticles", 4); config.addDefault("Abilities.Air.AirBlast.Particles", 6); config.addDefault("Abilities.Air.AirBlast.Cooldown", 500); - config.addDefault("Abilities.Air.AirBlast.Push.Self", 2.5); - config.addDefault("Abilities.Air.AirBlast.Push.Entities", 3.5); + config.addDefault("Abilities.Air.AirBlast.Push.Self", 2.0); + config.addDefault("Abilities.Air.AirBlast.Push.Entities", 1.6); config.addDefault("Abilities.Air.AirBlast.CanFlickLevers", true); config.addDefault("Abilities.Air.AirBlast.CanOpenDoors", true); config.addDefault("Abilities.Air.AirBlast.CanPressButtons", true); @@ -850,7 +850,8 @@ public class ConfigManager { config.addDefault("Abilities.Air.AirSuction.Range", 20); config.addDefault("Abilities.Air.AirSuction.SelectRange", 10); config.addDefault("Abilities.Air.AirSuction.Radius", 2); - config.addDefault("Abilities.Air.AirSuction.Push", 2.5); + config.addDefault("Abilities.Air.AirSuction.Push.Self", 2.0); + config.addDefault("Abilities.Air.AirSuction.Push.Others", 1.3); config.addDefault("Abilities.Air.AirSuction.Cooldown", 500); config.addDefault("Abilities.Air.AirSuction.Particles", 6); config.addDefault("Abilities.Air.AirSuction.SelectParticles", 6); diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java b/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java index 88cd0df3..e71a0d9e 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthSmash.java @@ -163,14 +163,14 @@ public class EarthSmash extends EarthAbility { if (bPlayer.isAvatarState()) { this.selectRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.SelectRange"); - this.grabRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Grab.Range"); + 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.Flight.Speed"); - this.flightDuration = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.Flight.Duration"); - this.shootRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.Shoot.Range"); + this.flightSpeed = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightSpeed"); + this.flightDuration = getConfig().getLong("Abilities.Avatar.AvatarState.Earth.EarthSmash.FlightTimer"); + this.shootRange = getConfig().getDouble("Abilities.Avatar.AvatarState.Earth.EarthSmash.ShootRange"); } } From cd9968a1c15c227bd48f702b3acc1c710c7139c0 Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Mon, 26 Aug 2019 00:18:41 -0400 Subject: [PATCH 03/22] Fix EarthBlast and Suffocate, and clean up RaiseEarth (#1009) ## Additions * Adds logic for EarthBlast being used on ceilings * Adds default cooldown to Suffocate ## Changes * Fixes Suffocate being usable through walls * Improves logic for EarthBlast pathing in general ## Removals * `ALL_AFFECTED_BLOCKS` in RaiseEarth isn't actually used, removes it. --- .../projectkorra/projectkorra/GeneralMethods.java | 15 ++++++++++++--- .../projectkorra/airbending/Suffocate.java | 4 ++-- .../projectkorra/configuration/ConfigManager.java | 2 +- .../projectkorra/earthbending/EarthBlast.java | 8 ++++++-- .../projectkorra/earthbending/RaiseEarth.java | 14 ++++++++------ 5 files changed, 29 insertions(+), 14 deletions(-) diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index 1c7c24d8..ccf82892 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -1187,8 +1187,8 @@ public class GeneralMethods { public static Entity getTargetedEntity(final Player player, final double range) { return getTargetedEntity(player, range, new ArrayList()); } - - public static Location getTargetedLocation(final Player player, final double range, final boolean ignoreTempBlocks, final Material... nonOpaque2) { + + public static Location getTargetedLocation(final Player player, final double range, final boolean ignoreTempBlocks, final boolean checkDiagonals, final Material... nonOpaque2) { final Location origin = player.getEyeLocation(); final Vector direction = origin.getDirection(); @@ -1208,6 +1208,11 @@ public class GeneralMethods { for (double i = 0; i < range; i += 0.2) { location.add(vec); + + if (checkDiagonals && checkDiagonalWall(location, vec)) { + location.subtract(vec); + break; + } final Block block = location.getBlock(); @@ -1224,12 +1229,16 @@ public class GeneralMethods { return location; } + public static Location getTargetedLocation(final Player player, final double range, final boolean ignoreTempBlocks, final Material... nonOpaque2) { + return getTargetedLocation(player, range, ignoreTempBlocks, true, nonOpaque2); + } + public static Location getTargetedLocation(final Player player, final double range, final Material... nonOpaque2) { return getTargetedLocation(player, range, false, nonOpaque2); } public static Location getTargetedLocation(final Player player, final int range) { - return getTargetedLocation(player, range, Material.AIR); + return getTargetedLocation(player, range); } public static Block getTopBlock(final Location loc, final int range) { diff --git a/src/com/projectkorra/projectkorra/airbending/Suffocate.java b/src/com/projectkorra/projectkorra/airbending/Suffocate.java index 81623b49..a42abeae 100644 --- a/src/com/projectkorra/projectkorra/airbending/Suffocate.java +++ b/src/com/projectkorra/projectkorra/airbending/Suffocate.java @@ -142,7 +142,6 @@ public class Suffocate extends AirAbility { } } - this.bPlayer.addCooldown(this); this.start(); } @@ -171,7 +170,7 @@ public class Suffocate extends AirAbility { if (this.player.getWorld().equals(this.targets.get(0).getWorld())) { dist = this.player.getEyeLocation().distance(this.targets.get(0).getEyeLocation()); } - final Location targetLoc = this.player.getEyeLocation().clone().add(this.player.getEyeLocation().getDirection().normalize().multiply(dist)); + final Location targetLoc = GeneralMethods.getTargetedLocation(player, dist, false, getTransparentMaterials()); final List ents = GeneralMethods.getEntitiesAroundPoint(targetLoc, this.constantAimRadius); for (int i = 0; i < this.targets.size(); i++) { @@ -336,6 +335,7 @@ public class Suffocate extends AirAbility { @Override public void remove() { super.remove(); + this.bPlayer.addCooldown(this); for (int i = 0; i < this.tasks.size(); i++) { this.tasks.get(i).cancel(); this.tasks.remove(i); diff --git a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java index e90002d9..871f4ada 100644 --- a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java +++ b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java @@ -876,7 +876,7 @@ public class ConfigManager { config.addDefault("Abilities.Air.Suffocate.Enabled", true); config.addDefault("Abilities.Air.Suffocate.ChargeTime", 500); - config.addDefault("Abilities.Air.Suffocate.Cooldown", 0); + config.addDefault("Abilities.Air.Suffocate.Cooldown", 6500); config.addDefault("Abilities.Air.Suffocate.Range", 20); config.addDefault("Abilities.Air.Suffocate.Damage", 2); config.addDefault("Abilities.Air.Suffocate.DamageInitialDelay", 2); diff --git a/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java b/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java index b00cf9ad..6157139e 100644 --- a/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java +++ b/src/com/projectkorra/projectkorra/earthbending/EarthBlast.java @@ -5,6 +5,7 @@ import java.util.ArrayList; 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.LivingEntity; import org.bukkit.entity.Player; @@ -71,7 +72,6 @@ public class EarthBlast extends EarthAbility { 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 (this.prepare()) { @@ -380,8 +380,12 @@ public class EarthBlast extends EarthAbility { this.firstDestination = this.location.clone(); if (this.destination.getY() - this.location.getY() > 2) { this.firstDestination.setY(this.destination.getY() - 1); - } else { + } else if (this.location.getY() > player.getEyeLocation().getY() && this.location.getBlock().getRelative(BlockFace.UP).isPassable()) { + this.firstDestination.subtract(0, 2, 0); + } else if (this.location.getBlock().getRelative(BlockFace.UP).isPassable() && this.location.getBlock().getRelative(BlockFace.UP, 2).isPassable()) { this.firstDestination.add(0, 2, 0); + } else { + this.firstDestination.add(GeneralMethods.getDirection(this.location, this.destination).normalize().setY(0)); } if (this.destination.distanceSquared(this.location) <= 1) { diff --git a/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java b/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java index fbc88f19..12330e89 100644 --- a/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java +++ b/src/com/projectkorra/projectkorra/earthbending/RaiseEarth.java @@ -2,7 +2,6 @@ package com.projectkorra.projectkorra.earthbending; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.bukkit.Location; @@ -15,11 +14,10 @@ import com.projectkorra.projectkorra.attribute.Attribute; import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.util.BlockSource; import com.projectkorra.projectkorra.util.ClickType; +import com.projectkorra.projectkorra.util.TempBlock; public class RaiseEarth extends EarthAbility { - private static final Map ALL_AFFECTED_BLOCKS = new ConcurrentHashMap<>(); - private int distance; @Attribute(Attribute.HEIGHT) private int height; @@ -104,7 +102,7 @@ public class RaiseEarth extends EarthAbility { private boolean canInstantiate() { for (final Block block : this.affectedBlocks.keySet()) { - if (!this.isEarthbendable(block) || ALL_AFFECTED_BLOCKS.containsKey(block)) { + if (!this.isEarthbendable(block) || TempBlock.isTempBlock(block)) { return false; } } @@ -143,11 +141,15 @@ public class RaiseEarth extends EarthAbility { } public static boolean blockInAllAffectedBlocks(final Block block) { - return ALL_AFFECTED_BLOCKS.containsKey(block); + for (RaiseEarth raiseEarth : getAbilities(RaiseEarth.class)) { + if (raiseEarth.affectedBlocks.contains(block)) { + return true; + } + } + return false; } public static void revertAffectedBlock(final Block block) { - ALL_AFFECTED_BLOCKS.remove(block); for (final RaiseEarth raiseEarth : getAbilities(RaiseEarth.class)) { raiseEarth.affectedBlocks.remove(block); } From 5d9e1d5b058facc033a70c2cac4e6406cb4424d8 Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Mon, 26 Aug 2019 03:18:58 -0400 Subject: [PATCH 04/22] Fix infinite recursion in GeneralMethods from incorrect method call (#1014) ## Fixes * Fixes infinite recursion in `GeneralMethods#getTargetedLocation(Player, int)` --- src/com/projectkorra/projectkorra/GeneralMethods.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index ccf82892..59cf232e 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -1238,7 +1238,7 @@ public class GeneralMethods { } public static Location getTargetedLocation(final Player player, final int range) { - return getTargetedLocation(player, range); + return getTargetedLocation(player, range, false); } public static Block getTopBlock(final Location loc, final int range) { From 34fa6d08b82b0a11ee1d80fbef006f636e6a6a19 Mon Sep 17 00:00:00 2001 From: Josh Date: Sat, 31 Aug 2019 19:28:31 -0400 Subject: [PATCH 05/22] Fix cooldowns of fire abilities with a duration, getClosestEntity, and Surge Wall diagonal check (#1016) ## Fixes * Fixes getClosestEntity to not rely on a distance check for if the entity is returned, but instead purely get the closest entity from getEntitiesAroundPoint * Fixes SurgeWall to not do that new diagonal check, fixes Ice wall glitching out ## Misc. Changes * Changes JetBlaze hitbox size, was way too big * Changes FireJet, WallOfFire, and the FireJet Combos cooldowns to activate when the move completes --- .../projectkorra/projectkorra/GeneralMethods.java | 14 +++++++------- .../projectkorra/firebending/FireJet.java | 2 +- .../projectkorra/firebending/WallOfFire.java | 7 ++++++- .../projectkorra/firebending/combo/JetBlast.java | 2 +- .../projectkorra/firebending/combo/JetBlaze.java | 4 ++-- .../projectkorra/waterbending/SurgeWall.java | 3 +-- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index 59cf232e..d16fa96d 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -872,17 +872,17 @@ public class GeneralMethods { */ public static Entity getClosestEntity(Location center, double radius) { Entity found = null; - double distance = radius * radius; + Double distance = null; for (Entity entity : GeneralMethods.getEntitiesAroundPoint(center, radius)) { - double check = center.distance(entity.getLocation()); + double check = center.distanceSquared(entity.getLocation()); - if (check < distance) { + if (distance == null || check < distance) { found = entity; distance = check; } } - + return found; } @@ -894,12 +894,12 @@ public class GeneralMethods { */ public static LivingEntity getClosestLivingEntity(Location center, double radius) { LivingEntity le = null; - double distance = radius * radius; + Double distance = null; for (Entity entity : GeneralMethods.getEntitiesAroundPoint(center, radius)) { - double check = center.distance(entity.getLocation()); + double check = center.distanceSquared(entity.getLocation()); - if (entity instanceof LivingEntity && check < distance) { + if (entity instanceof LivingEntity && (distance == null || check < distance)) { le = (LivingEntity) entity; distance = check; } diff --git a/src/com/projectkorra/projectkorra/firebending/FireJet.java b/src/com/projectkorra/projectkorra/firebending/FireJet.java index 0f492483..68da1d7a 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireJet.java +++ b/src/com/projectkorra/projectkorra/firebending/FireJet.java @@ -77,7 +77,6 @@ public class FireJet extends FireAbility { this.previousGlidingState = player.isGliding(); player.setGliding(true); } - this.bPlayer.addCooldown(this); } } @@ -118,6 +117,7 @@ public class FireJet extends FireAbility { } this.flightHandler.removeInstance(this.player, this.getName()); this.player.setFallDistance(0); + this.bPlayer.addCooldown(this); } @Override diff --git a/src/com/projectkorra/projectkorra/firebending/WallOfFire.java b/src/com/projectkorra/projectkorra/firebending/WallOfFire.java index d73935de..e11cd6c8 100644 --- a/src/com/projectkorra/projectkorra/firebending/WallOfFire.java +++ b/src/com/projectkorra/projectkorra/firebending/WallOfFire.java @@ -102,7 +102,6 @@ public class WallOfFire extends FireAbility { this.initializeBlocks(); this.start(); - this.bPlayer.addCooldown(this); } private void affect(final Entity entity) { @@ -210,6 +209,12 @@ public class WallOfFire extends FireAbility { } } + @Override + public void remove() { + super.remove(); + this.bPlayer.addCooldown(this); + } + @Override public String getName() { return "WallOfFire"; diff --git a/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java b/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java index 3642ef7d..ffb6efef 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/JetBlast.java @@ -79,7 +79,6 @@ public class JetBlast extends FireAbility implements ComboAbility { return; } - this.bPlayer.addCooldown("JetBlast", this.cooldown); this.firstTime = false; final float spread = 0F; ParticleEffect.EXPLOSION_LARGE.display(this.player.getLocation(), 1, spread, spread, spread, 0); @@ -106,6 +105,7 @@ public class JetBlast extends FireAbility implements ComboAbility { task.remove(); } super.remove(); + this.bPlayer.addCooldown("JetBlast", this.cooldown); } @Override diff --git a/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java b/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java index f860aa7a..c04cb42a 100644 --- a/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java +++ b/src/com/projectkorra/projectkorra/firebending/combo/JetBlaze.java @@ -88,7 +88,6 @@ public class JetBlaze extends FireAbility implements ComboAbility { this.remove(); return; } - this.bPlayer.addCooldown("JetBlaze", this.cooldown); this.firstTime = false; } else if (System.currentTimeMillis() - this.time > this.duration) { this.remove(); @@ -103,7 +102,7 @@ public class JetBlaze extends FireAbility implements ComboAbility { fs.setDensity(8); fs.setSpread(1.0F); fs.setUseNewParticles(true); - fs.setCollisionRadius(3); + fs.setCollisionRadius(2); fs.setParticleEffect(ParticleEffect.SMOKE_LARGE); fs.setDamage(this.damage); fs.setFireTicks(this.fireTicks); @@ -121,6 +120,7 @@ public class JetBlaze extends FireAbility implements ComboAbility { task.remove(); } super.remove(); + this.bPlayer.addCooldown("JetBlaze", this.cooldown); } @Override diff --git a/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java b/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java index 5f9f8614..9f6fead2 100644 --- a/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java +++ b/src/com/projectkorra/projectkorra/waterbending/SurgeWall.java @@ -255,12 +255,11 @@ public class SurgeWall extends WaterAbility { } final ArrayList blocks = new ArrayList(); - final Location targetLoc = GeneralMethods.getTargetedLocation(this.player, (int) this.range, Material.WATER, Material.ICE); + final Location targetLoc = GeneralMethods.getTargetedLocation(this.player, (int) this.range, false, false, Material.WATER, Material.ICE); this.location = targetLoc.clone(); final Vector eyeDir = this.player.getEyeLocation().getDirection(); Vector vector; Block block; - 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); From c4be31c3b939da375037b8a8bd2433f61e0aeb4b Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Sat, 31 Aug 2019 22:42:32 -0400 Subject: [PATCH 06/22] Fix Charged FireBlast radius and cooldown (#1019) ## Fixes * Fixes Charged FireBlast radius being too big * Fixes Charged FireBlast cooldown happening without using the ability --- .../projectkorra/firebending/FireBlastCharged.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java b/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java index 3702a830..60df8218 100644 --- a/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java +++ b/src/com/projectkorra/projectkorra/firebending/FireBlastCharged.java @@ -216,7 +216,7 @@ public class FireBlastCharged extends FireAbility { } boolean exploded = false; - for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, 2 * this.collisionRadius)) { + for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.location, this.collisionRadius)) { if (entity.getEntityId() == this.player.getEntityId() || GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation())) { continue; } @@ -310,7 +310,9 @@ public class FireBlastCharged extends FireAbility { @Override public void remove() { super.remove(); - this.bPlayer.addCooldown(this); + if (this.charged) { + this.bPlayer.addCooldown(this); + } } @Override From 861f0055d52865e24ed5a126e78eadefba806202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hern=C3=A1n=20Ind=C3=ADbil=20de=20la=20Cruz=20Calvo?= Date: Mon, 2 Sep 2019 18:53:51 +0200 Subject: [PATCH 07/22] Fix WaterReturn not finding bottles after potions (#1021) ## Additions Static Function that returns the slot id of the first water bottle found, -1 if none found. Used to not repeat code that should be the same (hasWaterBottle and emptyWaterBottle start finding this index, but they don't use the same code). ## Fixes Fixes an error in hasWaterBottle function. In the former version of the WaterReturn.java file, hasWaterBottle only tests if the first item with Material.POTION in the inventory is of type PotionType.WATER. Having a random potion in the inventory in any slot before a Water Bottle makes this to return false, instead of checking all the potions in the Player Inventory. This causes the player to be unable to use the bottle as a water source. The new code checks all the potions. ## Misc. Changes Since the items in an inventory aren't usually sorted (players don't sort items by id in their inventories), the "contains" method iterates all over the items on the inventory until it finds one with the specified material. The "first" method does the same, but instead of returning a boolean, it gives us the slot index of the item or -1 if not found. Since in "fillBottle" method we are going to calculate that index after checking whether the item is in the inventory or not, I've calculated this index with the "first" method and checking if it is greater or equals than 0 (not -1). Doing so we don't repeat the search task and we have a little improvement in efficiency terms. --- .../waterbending/util/WaterReturn.java | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java b/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java index bcdb7bec..c0784ece 100644 --- a/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java +++ b/src/com/projectkorra/projectkorra/waterbending/util/WaterReturn.java @@ -114,8 +114,8 @@ public class WaterReturn extends WaterAbility { private void fillBottle() { final PlayerInventory inventory = this.player.getInventory(); - if (inventory.contains(Material.GLASS_BOTTLE)) { - final int index = inventory.first(Material.GLASS_BOTTLE); + final int index = inventory.first(Material.GLASS_BOTTLE); + if (index >= 0) { final ItemStack item = inventory.getItem(index); final ItemStack water = waterBottleItem(); @@ -146,27 +146,15 @@ public class WaterReturn extends WaterAbility { return false; } - public static boolean hasWaterBottle(final Player player) { - if (hasAbility(player, WaterReturn.class) || isBending(player)) { - return false; - } - final PlayerInventory inventory = player.getInventory(); - if (inventory.contains(Material.POTION)) { - 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(final Player player) { - final PlayerInventory inventory = player.getInventory(); + public static int firstWaterBottle(final PlayerInventory inventory) { 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. - 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) { + if (index != -1) { + int aux = index; + index = -1; + for (int i = aux; i < inventory.getSize(); i++) { + if (inventory.getItem(i) != null && inventory.getItem(i).getType() == Material.POTION && inventory.getItem(i).hasItemMeta()) { final PotionMeta meta = (PotionMeta) inventory.getItem(i).getItemMeta(); if (meta.getBasePotionData().getType().equals(PotionType.WATER)) { index = i; @@ -176,6 +164,22 @@ public class WaterReturn extends WaterAbility { } } + return index; + } + + public static boolean hasWaterBottle(final Player player) { + if (hasAbility(player, WaterReturn.class) || isBending(player)) { + return false; + } + final PlayerInventory inventory = player.getInventory(); + + return WaterReturn.firstWaterBottle(inventory) >= 0; + } + + public static void emptyWaterBottle(final Player player) { + final PlayerInventory inventory = player.getInventory(); + int index = WaterReturn.firstWaterBottle(inventory); + if (index != -1) { final ItemStack item = inventory.getItem(index); if (item.getAmount() == 1) { From 0f2940f5ebbf96b2223f50a85b647e6d47b0be59 Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Sun, 8 Sep 2019 23:19:49 -0400 Subject: [PATCH 08/22] Remove revertBlock recursive calls in EarthAbility and Collapse (#1023) ## Fixes * Fixes recursive calls to `EarthAbility#revertBlock(Block)` --- .../projectkorra/projectkorra/ability/EarthAbility.java | 8 ++++---- .../projectkorra/projectkorra/earthbending/Collapse.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/com/projectkorra/projectkorra/ability/EarthAbility.java b/src/com/projectkorra/projectkorra/ability/EarthAbility.java index 890102ae..200bc1c2 100644 --- a/src/com/projectkorra/projectkorra/ability/EarthAbility.java +++ b/src/com/projectkorra/projectkorra/ability/EarthAbility.java @@ -604,10 +604,10 @@ public abstract class EarthAbility extends ElementalAbility { if (block.equals(sourceblock)) { info.getState().update(true, false); if (RaiseEarth.blockInAllAffectedBlocks(sourceblock)) { - EarthAbility.revertBlock(sourceblock); + RaiseEarth.revertAffectedBlock(sourceblock); } if (RaiseEarth.blockInAllAffectedBlocks(block)) { - EarthAbility.revertBlock(block); + RaiseEarth.revertAffectedBlock(block); } MOVED_EARTH.remove(block); return true; @@ -636,10 +636,10 @@ public abstract class EarthAbility extends ElementalAbility { } if (RaiseEarth.blockInAllAffectedBlocks(sourceblock)) { - EarthAbility.revertBlock(sourceblock); + RaiseEarth.revertAffectedBlock(sourceblock); } if (RaiseEarth.blockInAllAffectedBlocks(block)) { - EarthAbility.revertBlock(block); + RaiseEarth.revertAffectedBlock(block); } MOVED_EARTH.remove(block); } diff --git a/src/com/projectkorra/projectkorra/earthbending/Collapse.java b/src/com/projectkorra/projectkorra/earthbending/Collapse.java index c4d518dd..1bcf02ac 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Collapse.java +++ b/src/com/projectkorra/projectkorra/earthbending/Collapse.java @@ -98,7 +98,7 @@ public class Collapse extends EarthAbility { thisBlock = this.block.getWorld().getBlockAt(this.location.clone().add(this.direction.clone().multiply(-i))); this.affectedBlocks.put(thisBlock, thisBlock); if (RaiseEarth.blockInAllAffectedBlocks(thisBlock)) { - EarthAbility.revertBlock(thisBlock); + RaiseEarth.revertAffectedBlock(thisBlock); } } } From 2091e58c359ff9d3bb85f3930172fd0a6e76786e Mon Sep 17 00:00:00 2001 From: Benford Whitaker Date: Sun, 8 Sep 2019 23:41:49 -0400 Subject: [PATCH 09/22] AirBlast and AirBurst Changes (#1017) ## Removals * Removes `AirBurst#getAffectedEntities()`, shouldn't allow direct access to the list ## Misc. Changes * Lowers "friction" in AirBlast knockback for entities on the ground * Ignore "friction" in AirBlast when the AirBurst source isn't null * Changes entity velocity comparison to only add vectors angled > pi/3 from push vector * Increase default AirBurst push option --- .../projectkorra/airbending/AirBlast.java | 98 +++++++++---------- .../projectkorra/airbending/AirBurst.java | 4 - .../configuration/ConfigManager.java | 2 +- 3 files changed, 49 insertions(+), 55 deletions(-) diff --git a/src/com/projectkorra/projectkorra/airbending/AirBlast.java b/src/com/projectkorra/projectkorra/airbending/AirBlast.java index 938f841b..986d15b9 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirBlast.java +++ b/src/com/projectkorra/projectkorra/airbending/AirBlast.java @@ -217,60 +217,58 @@ public class AirBlast extends AirAbility { return; } } - - if (!affectedEntities.contains(entity)) { - final boolean isUser = entity.getUniqueId() == this.player.getUniqueId(); - double knockback = this.pushFactorForOthers; - - if (isUser) { - if (isFromOtherOrigin) { - knockback = this.pushFactor; - } else { - return; - } - } - - final double max = this.speed / this.speedFactor; - - final Vector push = this.direction.clone(); - if (Math.abs(push.getY()) > max && !isUser) { - if (push.getY() < 0) { - push.setY(-max); - } else { - push.setY(max); - } - } - - if (this.location.getWorld().equals(this.origin.getWorld())) { - knockback *= 1 - this.location.distance(this.origin) / (2 * this.range); - } - if (GeneralMethods.isSolid(entity.getLocation().add(0, -.5, 0).getBlock())) { - knockback *= .5; - } - - push.normalize().multiply(knockback); - - if (Math.abs(entity.getVelocity().dot(push)) > knockback) { - push.normalize().add(entity.getVelocity()).multiply(knockback); - } - - GeneralMethods.setVelocity(entity, push); - - if (this.source != null) { - new HorizontalVelocityTracker(entity, this.player, 200l, this.source); + final boolean isUser = entity.getUniqueId() == this.player.getUniqueId(); + double knockback = this.pushFactorForOthers; + + if (isUser) { + if (isFromOtherOrigin) { + knockback = this.pushFactor; } else { - new HorizontalVelocityTracker(entity, this.player, 200l, this); + return; } - - if (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(this.player)) { - if (this.source != null) { - DamageHandler.damageEntity(entity, this.damage, this.source); - } else { - DamageHandler.damageEntity(entity, this.damage, this); - } + } + + final double max = this.speed / this.speedFactor; + + final Vector push = this.direction.clone(); + if (Math.abs(push.getY()) > max && !isUser) { + if (push.getY() < 0) { + push.setY(-max); + } else { + push.setY(max); } - + } + + if (this.location.getWorld().equals(this.origin.getWorld())) { + knockback *= 1 - this.location.distance(this.origin) / (2 * this.range); + } + + if (GeneralMethods.isSolid(entity.getLocation().add(0, -0.5, 0).getBlock()) && source == null) { + knockback *= 0.85; + } + + push.normalize().multiply(knockback); + + if (Math.abs(entity.getVelocity().dot(push)) > knockback && entity.getVelocity().angle(push) > Math.PI / 3) { + push.normalize().add(entity.getVelocity()).multiply(knockback); + } + + GeneralMethods.setVelocity(entity, push); + + if (this.source != null) { + new HorizontalVelocityTracker(entity, this.player, 200l, this.source); + } else { + new HorizontalVelocityTracker(entity, this.player, 200l, this); + } + + if (this.damage > 0 && entity instanceof LivingEntity && !entity.equals(this.player) && !this.affectedEntities.contains(entity)) { + if (this.source != null) { + DamageHandler.damageEntity(entity, this.damage, this.source); + } else { + DamageHandler.damageEntity(entity, this.damage, this); + } + this.affectedEntities.add(entity); } diff --git a/src/com/projectkorra/projectkorra/airbending/AirBurst.java b/src/com/projectkorra/projectkorra/airbending/AirBurst.java index d7633877..031fed78 100644 --- a/src/com/projectkorra/projectkorra/airbending/AirBurst.java +++ b/src/com/projectkorra/projectkorra/airbending/AirBurst.java @@ -321,8 +321,4 @@ public class AirBurst extends AirAbility { public ArrayList getBlasts() { return this.blasts; } - - public ArrayList getAffectedEntities() { - return this.affectedEntities; - } } diff --git a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java index 871f4ada..231d9b9f 100644 --- a/src/com/projectkorra/projectkorra/configuration/ConfigManager.java +++ b/src/com/projectkorra/projectkorra/configuration/ConfigManager.java @@ -811,7 +811,7 @@ public class ConfigManager { config.addDefault("Abilities.Air.AirBurst.Enabled", true); config.addDefault("Abilities.Air.AirBurst.FallThreshold", 10); - config.addDefault("Abilities.Air.AirBurst.PushFactor", 1.5); + config.addDefault("Abilities.Air.AirBurst.PushFactor", 2.8); config.addDefault("Abilities.Air.AirBurst.ChargeTime", 1750); config.addDefault("Abilities.Air.AirBurst.Damage", 0); config.addDefault("Abilities.Air.AirBurst.Cooldown", 0); From da76d0ac120e5c8cc19be6dc0a4c74e86ba5aeb5 Mon Sep 17 00:00:00 2001 From: Josh Date: Tue, 10 Sep 2019 21:54:18 -0400 Subject: [PATCH 10/22] Fix Preset command not being able to list page numbers higher than 1 (#1024) ## Fixes * Fixes listing preset pages. Previously doing "/b preset list 2" would just return the help message --- .../projectkorra/command/PresetCommand.java | 66 ++++++++++--------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/src/com/projectkorra/projectkorra/command/PresetCommand.java b/src/com/projectkorra/projectkorra/command/PresetCommand.java index efa04582..97708f6e 100644 --- a/src/com/projectkorra/projectkorra/command/PresetCommand.java +++ b/src/com/projectkorra/projectkorra/command/PresetCommand.java @@ -77,41 +77,45 @@ public class PresetCommand extends PKCommand { bPlayer = BendingPlayer.getBendingPlayer(player); } - // bending preset list. - if (args.size() == 1) { - 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 (final Preset preset : presets) { - presetNames.add(preset.getName()); - } - - 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; + int page = 1; + String name = null; + if (args.size() == 1 && !Arrays.asList(listaliases).contains(args.get(0))){ + this.help(sender, false); + } else if (args.size() >= 2) { + if (Arrays.asList(listaliases).contains(args.get(0))) { + page = Integer.parseInt(args.get(1)); } else { - this.help(sender, false); - return; + name = args.get(1); } } - final String name = args.get(1); - if (Arrays.asList(deletealiases).contains(args.get(0)) && this.hasPermission(sender, "delete")) { // bending preset delete name. + // bending preset list. + 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 (final Preset preset : presets) { + presetNames.add(preset.getName()); + } + + for (final String s : this.getPage(presetNames, ChatColor.GOLD + "Presets: ", page, false)) { + if (firstMessage) { + GeneralMethods.sendBrandingMessage(sender, s); + firstMessage = false; + } else { + sender.sendMessage(ChatColor.YELLOW + s); + } + } + + return; + } else 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; From a8a8daa6d0ac25cb505e864e58e81abe40c246f4 Mon Sep 17 00:00:00 2001 From: Josh Date: Sat, 28 Sep 2019 15:00:31 -0400 Subject: [PATCH 11/22] Fix catapult and metalclips not respecting invincible or region protection (#1027) ## Fixes * Fixes catapult launching player with invincible toggled or protected region * Fixes metalclip working on players with invincible toggled --- src/com/projectkorra/projectkorra/earthbending/Catapult.java | 4 ++++ .../projectkorra/earthbending/metal/MetalClips.java | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/com/projectkorra/projectkorra/earthbending/Catapult.java b/src/com/projectkorra/projectkorra/earthbending/Catapult.java index 838c8abc..78bfe6bd 100644 --- a/src/com/projectkorra/projectkorra/earthbending/Catapult.java +++ b/src/com/projectkorra/projectkorra/earthbending/Catapult.java @@ -11,6 +11,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.command.Commands; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.EarthAbility; import com.projectkorra.projectkorra.attribute.Attribute; @@ -69,6 +70,9 @@ public class Catapult extends EarthAbility { private void moveEarth(final Vector apply, final Vector direction) { for (final Entity entity : GeneralMethods.getEntitiesAroundPoint(this.origin, 2)) { if (entity.getEntityId() != this.player.getEntityId()) { + if (GeneralMethods.isRegionProtectedFromBuild(this, entity.getLocation()) || ((entity instanceof Player) && Commands.invincible.contains(((Player) entity).getName()))) { + continue; + } entity.setVelocity(apply); } } diff --git a/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java b/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java index c3b95ca0..d535e137 100644 --- a/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java +++ b/src/com/projectkorra/projectkorra/earthbending/metal/MetalClips.java @@ -18,6 +18,7 @@ import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; +import com.projectkorra.projectkorra.command.Commands; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.MetalAbility; @@ -165,7 +166,7 @@ public class MetalClips extends MetalAbility { return; } else if (this.metalClipsCount == 3 && !this.canUse4Clips) { return; - } else if (this.targetEntity != null && GeneralMethods.isRegionProtectedFromBuild(this, this.targetEntity.getLocation())) { + } else if (this.targetEntity != null && (GeneralMethods.isRegionProtectedFromBuild(this, this.targetEntity.getLocation()) || ((targetEntity instanceof Player) && Commands.invincible.contains(((Player) targetEntity).getName())))) { return; } From 299cec824e9fd3ba2acd418a325f651a54eba73b Mon Sep 17 00:00:00 2001 From: jayoevans Date: Tue, 22 Oct 2019 11:49:47 +1000 Subject: [PATCH 12/22] Initial rework of the BendingPlayer back-end --- pom.xml | 14 +- .../projectkorra/ProjectKorra.java | 2 + .../projectkorra/database/DatabaseConfig.java | 14 ++ .../database/DatabaseManager.java | 57 ++++++++ .../projectkorra/database/DatabaseQuery.java | 63 ++++++++ .../database/DatabaseRepository.java | 19 +++ .../database/engine/MySQLDatabase.java | 48 +++++++ .../database/engine/SQLDatabase.java | 10 ++ .../database/engine/SQLiteDatabase.java | 83 +++++++++++ .../projectkorra/module/DatabaseModule.java | 20 +++ .../projectkorra/module/Module.java | 92 ++++++++++++ .../projectkorra/module/ModuleManager.java | 74 ++++++++++ .../projectkorra/player/BendingPlayer.java | 29 ++++ .../player/BendingPlayerManager.java | 52 +++++++ .../player/BendingPlayerRepository.java | 135 ++++++++++++++++++ 15 files changed, 711 insertions(+), 1 deletion(-) create mode 100644 src/com/projectkorra/projectkorra/database/DatabaseConfig.java create mode 100644 src/com/projectkorra/projectkorra/database/DatabaseManager.java create mode 100644 src/com/projectkorra/projectkorra/database/DatabaseQuery.java create mode 100644 src/com/projectkorra/projectkorra/database/DatabaseRepository.java create mode 100644 src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java create mode 100644 src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java create mode 100644 src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java create mode 100644 src/com/projectkorra/projectkorra/module/DatabaseModule.java create mode 100644 src/com/projectkorra/projectkorra/module/Module.java create mode 100644 src/com/projectkorra/projectkorra/module/ModuleManager.java create mode 100644 src/com/projectkorra/projectkorra/player/BendingPlayer.java create mode 100644 src/com/projectkorra/projectkorra/player/BendingPlayerManager.java create mode 100644 src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java diff --git a/pom.xml b/pom.xml index eace9821..413e2dae 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,18 @@ commons-lang3 3.8.1 + + + com.zaxxer + HikariCP + 3.4.1 + + + + mysql + mysql-connector-java + 8.0.18 + me.markeh @@ -244,4 +256,4 @@ ${project.build.directory} UTF-8 - \ No newline at end of file + diff --git a/src/com/projectkorra/projectkorra/ProjectKorra.java b/src/com/projectkorra/projectkorra/ProjectKorra.java index 4ddfe988..2b4b601e 100644 --- a/src/com/projectkorra/projectkorra/ProjectKorra.java +++ b/src/com/projectkorra/projectkorra/ProjectKorra.java @@ -8,6 +8,7 @@ import com.bekvon.bukkit.residence.protection.FlagPermissions; import co.aikar.timings.lib.MCTiming; import co.aikar.timings.lib.TimingManager; +import com.projectkorra.projectkorra.module.ModuleManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Statistic; @@ -77,6 +78,7 @@ public class ProjectKorra extends JavaPlugin { } Manager.startup(); + ModuleManager.startup(); this.getServer().getPluginManager().registerEvents(new PKListener(this), this); this.getServer().getScheduler().scheduleSyncRepeatingTask(this, new BendingManager(), 0, 1); diff --git a/src/com/projectkorra/projectkorra/database/DatabaseConfig.java b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java new file mode 100644 index 00000000..8c6504d4 --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java @@ -0,0 +1,14 @@ +package com.projectkorra.projectkorra.database; + +public class DatabaseConfig +{ + public final DatabaseManager.Engine Engine = DatabaseManager.Engine.SQLITE; + + public final String SQLite_File = "projectkorra.sql"; + + public final String MySQL_IP = "localhost"; + public final String MySQL_Port = "3306"; + public final String MySQL_DatabaseName = "projectkorra"; + public final String MySQL_Username = "root"; + public final String MySQL_Password = "password"; +} diff --git a/src/com/projectkorra/projectkorra/database/DatabaseManager.java b/src/com/projectkorra/projectkorra/database/DatabaseManager.java new file mode 100644 index 00000000..fddcac07 --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/DatabaseManager.java @@ -0,0 +1,57 @@ +package com.projectkorra.projectkorra.database; + +import com.projectkorra.projectkorra.database.engine.MySQLDatabase; +import com.projectkorra.projectkorra.database.engine.SQLDatabase; +import com.projectkorra.projectkorra.database.engine.SQLiteDatabase; +import com.projectkorra.projectkorra.module.Module; + +import java.util.logging.Level; + +public class DatabaseManager extends Module +{ + private final DatabaseConfig _config; + private final SQLDatabase _database; + + private DatabaseManager() + { + super("Database"); + + // TODO Pull from new ConfigManager + _config = new DatabaseConfig(); + + switch (_config.Engine) + { + case MYSQL: + _database = new MySQLDatabase(_config); + break; + case SQLITE: + _database = new SQLiteDatabase(this, _config); + break; + default: + log(Level.SEVERE, "Unknown database engine."); + _database = null; + break; + } + } + + public DatabaseConfig getConfig() + { + return _config; + } + + public SQLDatabase getDatabase() + { + return _database; + } + + @Override + public void onDisable() + { + _database.close(); + } + + public enum Engine + { + MYSQL, SQLITE; + } +} diff --git a/src/com/projectkorra/projectkorra/database/DatabaseQuery.java b/src/com/projectkorra/projectkorra/database/DatabaseQuery.java new file mode 100644 index 00000000..7b2446d1 --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/DatabaseQuery.java @@ -0,0 +1,63 @@ +package com.projectkorra.projectkorra.database; + +import com.projectkorra.projectkorra.module.ModuleManager; + +public class DatabaseQuery +{ + private final String _mysql; + private final String _sqlite; + + private DatabaseQuery(String mysql, String sqlite) + { + _mysql = mysql; + _sqlite = sqlite; + } + + public String getQuery() + { + switch (ModuleManager.getModule(DatabaseManager.class).getConfig().Engine) + { + case MYSQL: + return _mysql; + case SQLITE: + return _sqlite; + } + + return null; + } + + public static Builder newBuilder() + { + return new Builder(); + } + + public static final class Builder + { + private String _mysql; + private String _sqlite; + + public Builder mysql(String mysql) + { + _mysql = mysql; + return this; + } + + public Builder sqlite(String sqlite) + { + _sqlite = sqlite; + return this; + } + + public Builder query(String query) + { + _mysql = query; + _sqlite = query; + return this; + } + + public DatabaseQuery build() + { + return new DatabaseQuery(_mysql, _sqlite); + } + } +} diff --git a/src/com/projectkorra/projectkorra/database/DatabaseRepository.java b/src/com/projectkorra/projectkorra/database/DatabaseRepository.java new file mode 100644 index 00000000..77db1e86 --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/DatabaseRepository.java @@ -0,0 +1,19 @@ +package com.projectkorra.projectkorra.database; + +import com.projectkorra.projectkorra.database.engine.SQLDatabase; +import com.projectkorra.projectkorra.module.ModuleManager; + +public abstract class DatabaseRepository +{ + private final DatabaseManager databaseManager; + + public DatabaseRepository() + { + this.databaseManager = ModuleManager.getModule(DatabaseManager.class); + } + + protected SQLDatabase getDatabase() + { + return databaseManager.getDatabase(); + } +} diff --git a/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java b/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java new file mode 100644 index 00000000..5080fb0c --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java @@ -0,0 +1,48 @@ +package com.projectkorra.projectkorra.database.engine; + +import com.projectkorra.projectkorra.database.DatabaseConfig; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import java.sql.Connection; +import java.sql.SQLException; + +public class MySQLDatabase implements SQLDatabase +{ + private final HikariDataSource _hikari; + + public MySQLDatabase(DatabaseConfig databaseConfig) + { + HikariConfig hikariConfig = new HikariConfig(); + + hikariConfig.setJdbcUrl("jdbc:mysql://" + databaseConfig.MySQL_IP + ":" + databaseConfig.MySQL_Port + "/" + databaseConfig.MySQL_DatabaseName); + hikariConfig.setDriverClassName("com.mysql.jdbc.Driver"); + hikariConfig.setUsername(databaseConfig.MySQL_Username); + hikariConfig.setPassword(databaseConfig.MySQL_Password); + hikariConfig.setMinimumIdle(1); + hikariConfig.setMaximumPoolSize(10); + hikariConfig.setConnectionTimeout(10000); + + _hikari = new HikariDataSource(hikariConfig); + } + + @Override + public Connection getConnection() + { + try (Connection connection = _hikari.getConnection()) + { + return connection; + } + catch (SQLException e) + { + e.printStackTrace(); + return null; + } + } + + @Override + public void close() + { + _hikari.close(); + } +} diff --git a/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java b/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java new file mode 100644 index 00000000..b0645666 --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java @@ -0,0 +1,10 @@ +package com.projectkorra.projectkorra.database.engine; + +import java.sql.Connection; + +public interface SQLDatabase +{ + Connection getConnection(); + + void close(); +} diff --git a/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java b/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java new file mode 100644 index 00000000..29ee909d --- /dev/null +++ b/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java @@ -0,0 +1,83 @@ +package com.projectkorra.projectkorra.database.engine; + +import com.projectkorra.projectkorra.database.DatabaseConfig; +import com.projectkorra.projectkorra.database.DatabaseManager; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class SQLiteDatabase implements SQLDatabase +{ + private final File _databaseFile; + private Connection _connection; + + public SQLiteDatabase(DatabaseManager databaseManager, DatabaseConfig databaseConfig) + { + _databaseFile = new File(databaseManager.getPlugin().getDataFolder(), databaseConfig.SQLite_File); + + if (!_databaseFile.getParentFile().exists()) + { + _databaseFile.getParentFile().mkdirs(); + } + + if (!_databaseFile.exists()) + { + try + { + _databaseFile.createNewFile(); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + + open(); + } + + public void open() + { + try + { + _connection = DriverManager.getConnection("jdbc:sqlite:" + _databaseFile.getAbsolutePath()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + @Override + public Connection getConnection() + { + try + { + if (_connection == null || _connection.isClosed()) + { + open(); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + + return _connection; + } + + @Override + public void close() + { + try + { + _connection.close(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } +} diff --git a/src/com/projectkorra/projectkorra/module/DatabaseModule.java b/src/com/projectkorra/projectkorra/module/DatabaseModule.java new file mode 100644 index 00000000..221e40b7 --- /dev/null +++ b/src/com/projectkorra/projectkorra/module/DatabaseModule.java @@ -0,0 +1,20 @@ +package com.projectkorra.projectkorra.module; + +import com.projectkorra.projectkorra.database.DatabaseRepository; + +public abstract class DatabaseModule extends Module +{ + private final T repository; + + protected DatabaseModule(String name, T repository) + { + super(name); + + this.repository = repository; + } + + protected T getRepository() + { + return this.repository; + } +} diff --git a/src/com/projectkorra/projectkorra/module/Module.java b/src/com/projectkorra/projectkorra/module/Module.java new file mode 100644 index 00000000..692a8292 --- /dev/null +++ b/src/com/projectkorra/projectkorra/module/Module.java @@ -0,0 +1,92 @@ +package com.projectkorra.projectkorra.module; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.projectkorra.projectkorra.ProjectKorra; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.logging.Level; + +public abstract class Module implements Listener +{ + private static final String LOG_FORMAT = "(%s) %s"; + + private final String name; + private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + + protected Module(String name) + { + this.name = name; + } + + protected final void enable() + { + long startTime = System.currentTimeMillis(); + log("Enabling..."); + + getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin()); + onEnable(); + + long finishTime = System.currentTimeMillis(); + log(String.format("Enabled! [%sms]", finishTime - startTime)); + } + + public void onEnable() + { + + } + + protected final void disable() + { + long startTime = System.currentTimeMillis(); + log("Disabling..."); + + HandlerList.unregisterAll(this); + onDisable(); + + long finishTime = System.currentTimeMillis(); + log(String.format("Disabled! [%sms]", finishTime - startTime)); + } + + public void onDisable() + { + + } + + protected final void runSync(Runnable runnable) + { + getPlugin().getServer().getScheduler().runTask(getPlugin(), runnable); + } + + protected final void runAsync(Runnable runnable) + { + getPlugin().getServer().getScheduler().runTaskAsynchronously(getPlugin(), runnable); + } + + public String getName() + { + return this.name; + } + + protected Gson getGson() + { + return this.gson; + } + + public final void log(String message) + { + log(Level.INFO, message); + } + + public final void log(Level level, String message) + { + getPlugin().getLogger().log(level, String.format(LOG_FORMAT, getName(), message)); + } + + public ProjectKorra getPlugin() + { + return JavaPlugin.getPlugin(ProjectKorra.class); + } +} diff --git a/src/com/projectkorra/projectkorra/module/ModuleManager.java b/src/com/projectkorra/projectkorra/module/ModuleManager.java new file mode 100644 index 00000000..afbc9531 --- /dev/null +++ b/src/com/projectkorra/projectkorra/module/ModuleManager.java @@ -0,0 +1,74 @@ +package com.projectkorra.projectkorra.module; + +import com.google.common.base.Preconditions; +import com.projectkorra.projectkorra.database.DatabaseManager; +import com.projectkorra.projectkorra.player.BendingPlayerManager; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +public class ModuleManager { + + private static final Map, Module> MODULES = new HashMap<>(); + + /** + * Registers a new {@link Module} instance. + * + * @param moduleClass {@link Class} of the {@link Module} to be registered + * @throws NullPointerException if moduleClass is null + * @throws IllegalArgumentException if moduleClass has already been registered + */ + public static void registerModule(Class moduleClass) { + Preconditions.checkNotNull(moduleClass, "moduleClass cannot be null"); + Preconditions.checkArgument(!MODULES.containsKey(moduleClass), "moduleClass has already been registered"); + + try { + Constructor constructor = moduleClass.getDeclaredConstructor(); + boolean accessible = constructor.isAccessible(); + constructor.setAccessible(true); + + Module module = constructor.newInstance(); + + MODULES.put(moduleClass, module); + module.enable(); + + constructor.setAccessible(accessible); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + + /** + * Returns a registered {@link Module} by its {@link Class}. + * + * @param moduleClass {@link Class} of the registered {@link Module} + * @return instance of the {@link Module} class + * @throws NullPointerException if moduleClass is null + * @throws IllegalArgumentException if moduleClass has not been registered + */ + public static T getModule(Class moduleClass) { + Preconditions.checkNotNull(moduleClass, "moduleClass cannot be null"); + Preconditions.checkArgument(MODULES.containsKey(moduleClass), "moduleClass has not been registered"); + + return moduleClass.cast(MODULES.get(moduleClass)); + } + + /** + * Register all our core {@link Module}s onEnable. + */ + public static void startup() { + registerModule(DatabaseManager.class); + registerModule(BendingPlayerManager.class); + } + + /** + * Disable all our core {@link Module}s onDisable. + */ + public static void shutdown() { + getModule(BendingPlayerManager.class).disable(); + getModule(DatabaseManager.class).disable(); + } + +} diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java new file mode 100644 index 00000000..7985c7ed --- /dev/null +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -0,0 +1,29 @@ +package com.projectkorra.projectkorra.player; + +import java.util.UUID; + +public class BendingPlayer +{ + private final int _playerId; + private final UUID _uuid; + private final String _playerName; + private long _firstLogin; + + public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) + { + _playerId = playerId; + _uuid = uuid; + _playerName = playerName; + _firstLogin = firstLogin; + } + + public int getId() + { + return _playerId; + } + + public long getFirstLogin() + { + return _firstLogin; + } +} diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java new file mode 100644 index 00000000..7a1fa3b6 --- /dev/null +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -0,0 +1,52 @@ +package com.projectkorra.projectkorra.player; + +import com.projectkorra.projectkorra.module.DatabaseModule; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerLoginEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class BendingPlayerManager extends DatabaseModule +{ + private final Map _players = new HashMap<>(); + + private BendingPlayerManager() + { + super("Bending Player", new BendingPlayerRepository()); + + runAsync(() -> + { + getRepository().createTable(); + + runSync(() -> + { + log("Created database table."); + }); + }); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onLogin(PlayerLoginEvent event) + { + Player player = event.getPlayer(); + + runAsync(() -> + { + BendingPlayer bendingPlayer = getRepository().selectPlayer(player); + + runSync(() -> + { + _players.put(player.getUniqueId(), bendingPlayer); + }); + }); + } + + public BendingPlayer getBendingPlayer(Player player) + { + return _players.get(player.getUniqueId()); + } +} diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java new file mode 100644 index 00000000..557a8934 --- /dev/null +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java @@ -0,0 +1,135 @@ +package com.projectkorra.projectkorra.player; + +import com.projectkorra.projectkorra.database.DatabaseQuery; +import com.projectkorra.projectkorra.database.DatabaseRepository; +import org.bukkit.entity.Player; + +import java.nio.ByteBuffer; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +public class BendingPlayerRepository extends DatabaseRepository +{ + private static final DatabaseQuery CREATE_TABLE_BENDING_PLAYERS = DatabaseQuery.newBuilder() + .mysql("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTO_INCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, INDEX uuid_index (uuid));") + .sqlite("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL); CREATE INDEX uuid_index ON pk_bending_players (uuid);") + .build(); + + private static final DatabaseQuery SELECT_BENDING_PLAYER = DatabaseQuery.newBuilder() + .query("SELECT player_id, player_name, first_login FROM pk_bending_players WHERE uuid = ?;") + .build(); + + private static final DatabaseQuery INSERT_BENDING_PLAYER = DatabaseQuery.newBuilder() + .query("INSERT INTO pk_bending_players (uuid, player_name, first_login) VALUES (?, ?, ?);") + .build(); + + private static final DatabaseQuery UPDATE_BENDING_PLAYER = DatabaseQuery.newBuilder() + .query("UPDATE pk_bending_players SET player_name = ? WHERE player_id = ?;") + .build(); + + protected void createTable() + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_BENDING_PLAYERS.getQuery())) + { + statement.executeUpdate(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + + protected BendingPlayer selectPlayer(Player player) + { + UUID uuid = player.getUniqueId(); + byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); + + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(SELECT_BENDING_PLAYER.getQuery())) + { + statement.setBytes(1, binaryUUID); + + try (ResultSet rs = statement.executeQuery()) + { + if (!rs.next()) + { + return insertPlayer(player.getUniqueId(), player.getName()); + } + + int playerId = rs.getInt("player_id"); + String playerName = rs.getString("player_name"); + long firstLogin = rs.getLong("first_login"); + + if (!player.getName().equals(playerName)) + { + updatePlayer(playerId, player.getName()); + } + + return new BendingPlayer(playerId, uuid, playerName, firstLogin); + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + + return null; + } + + private BendingPlayer insertPlayer(UUID uuid, String playerName) + { + byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); + + Connection connection = getDatabase().getConnection(); + long firstLogin = System.currentTimeMillis(); + + try (PreparedStatement statement = connection.prepareStatement(INSERT_BENDING_PLAYER.getQuery(), Statement.RETURN_GENERATED_KEYS)) + { + statement.setBytes(1, binaryUUID); + statement.setString(2, playerName); + statement.setLong(3, firstLogin); + + statement.executeUpdate(); + + try (ResultSet rs = statement.getGeneratedKeys()) + { + if (rs.next()) + { + int playerId = rs.getInt(1); + + return new BendingPlayer(playerId, uuid, playerName, firstLogin); + } + } + } + catch (SQLException e) + { + e.printStackTrace(); + } + + return null; + } + + protected void updatePlayer(int playerId, String playerName) + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_PLAYER.getQuery())) + { + statement.setInt(1, playerId); + statement.setString(2, playerName); + + statement.executeUpdate(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } +} From 3641f4ab9b556f9b593050af1fb6315ec7a211cb Mon Sep 17 00:00:00 2001 From: jayoevans Date: Tue, 22 Oct 2019 14:44:05 +1000 Subject: [PATCH 13/22] Setup Element back-end --- .../projectkorra/element/Element.java | 44 +++++ .../projectkorra/element/ElementManager.java | 155 ++++++++++++++++++ .../element/ElementRepository.java | 146 +++++++++++++++++ .../projectkorra/element/SubElement.java | 20 +++ .../projectkorra/module/ModuleManager.java | 3 + .../projectkorra/player/BendingPlayer.java | 29 +++- .../player/BendingPlayerLoadedEvent.java | 35 ++++ .../player/BendingPlayerManager.java | 30 +++- .../player/BendingPlayerRepository.java | 37 +---- 9 files changed, 463 insertions(+), 36 deletions(-) create mode 100644 src/com/projectkorra/projectkorra/element/Element.java create mode 100644 src/com/projectkorra/projectkorra/element/ElementManager.java create mode 100644 src/com/projectkorra/projectkorra/element/ElementRepository.java create mode 100644 src/com/projectkorra/projectkorra/element/SubElement.java create mode 100644 src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java diff --git a/src/com/projectkorra/projectkorra/element/Element.java b/src/com/projectkorra/projectkorra/element/Element.java new file mode 100644 index 00000000..bf25d0a9 --- /dev/null +++ b/src/com/projectkorra/projectkorra/element/Element.java @@ -0,0 +1,44 @@ +package com.projectkorra.projectkorra.element; + +import org.bukkit.ChatColor; + +public class Element +{ + private final int _elementId; + private final String _elementName; + private final String _displayName; + private final ChatColor _color; + + public Element(int elementId, String elementName, String displayName, ChatColor color) + { + _elementId = elementId; + _elementName = elementName; + _displayName = displayName; + _color = color; + } + + public int getId() + { + return _elementId; + } + + public String getName() + { + return _elementName; + } + + public String getDisplayName() + { + return _displayName; + } + + public ChatColor getColor() + { + return _color; + } + + public String getColoredName() + { + return _color + _displayName; + } +} diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java new file mode 100644 index 00000000..e01638ea --- /dev/null +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -0,0 +1,155 @@ +package com.projectkorra.projectkorra.element; + +import com.google.common.base.Preconditions; +import com.projectkorra.projectkorra.module.DatabaseModule; +import com.projectkorra.projectkorra.module.ModuleManager; +import com.projectkorra.projectkorra.player.BendingPlayer; +import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; +import com.projectkorra.projectkorra.player.BendingPlayerManager; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public class ElementManager extends DatabaseModule +{ + private static final String WATER = "water"; + private static final String BLOOD = "blood"; + private static final String HEALING = "healing"; + private static final String EARTH = "earth"; + private static final String LAVA = "lava"; + private static final String METAL = "metal"; + private static final String SAND = "sand"; + private static final String FIRE = "fire"; + private static final String COMBUSTION = "combustion"; + private static final String LIGHTNING = "lightning"; + private static final String AIR = "air"; + private static final String FLIGHT = "flight"; + private static final String SPIRITUAL = "spiritual"; + private static final String CHI = "chi"; + + private final BendingPlayerManager _bendingPlayerManager; + + private final Map _elements = new HashMap<>(); + private final Map _names = new HashMap<>(); + + private final String _nameRegex = "[a-zA-Z]+"; + + private ElementManager() + { + super("Element", new ElementRepository()); + + _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + + runAsync(() -> + { + try + { + getRepository().createTables(); + + // Waterbending + Element water = addElement(WATER, "Water", ChatColor.AQUA); + addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water); + addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water); + + // Earthbending + Element earth = addElement(EARTH, "Earth", ChatColor.AQUA); + addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, earth); + addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, earth); + addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, earth); + + // Firebending + Element fire = addElement(FIRE, "Fire", ChatColor.RED); + addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, fire); + addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, fire); + + // Airbending + Element air = addElement(AIR, "Air", ChatColor.GRAY); + addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, air); + addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, air); + + // Chiblocking + Element chi = addElement(CHI, "Chi", ChatColor.GOLD); + } + catch (SQLException e) + { + e.printStackTrace(); + } + + runSync(() -> + { + log("Populated element database tables."); + }); + }); + } + + @EventHandler + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) + { + Player player = event.getPlayer(); + BendingPlayer bendingPlayer = event.getBendingPlayer(); + + runAsync(() -> + { + try + { + List elements = getRepository().selectPlayerElements(bendingPlayer.getId()).stream() + .map(_elements::get) + .collect(Collectors.toList()); + + bendingPlayer.addElements(elements); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + + private Element addElement(String elementName, String displayName, ChatColor color) + { + int elementId = registerElement(elementName); + + Element element = new Element(elementId, elementName, displayName, color); + + _elements.put(elementId, element); + _names.put(elementName, element); + + return element; + } + + private SubElement addSubElement(String elementName, String displayName, ChatColor color, Element parent) + { + int elementId = registerElement(elementName); + + SubElement element = new SubElement(elementId, elementName, displayName, color, parent); + + _elements.put(elementId, element); + _names.put(elementName, element); + + return element; + } + + private int registerElement(String elementName) + { + Preconditions.checkNotNull(elementName, "Element name cannot be null"); + + Preconditions.checkArgument(Pattern.matches(_nameRegex, elementName), "Element name must only contain letters and spaces"); + + try + { + return getRepository().selectElemenetId(elementName); + } + catch (SQLException e) + { + e.printStackTrace(); + return -1; + } + } +} diff --git a/src/com/projectkorra/projectkorra/element/ElementRepository.java b/src/com/projectkorra/projectkorra/element/ElementRepository.java new file mode 100644 index 00000000..b658381a --- /dev/null +++ b/src/com/projectkorra/projectkorra/element/ElementRepository.java @@ -0,0 +1,146 @@ +package com.projectkorra.projectkorra.element; + +import com.projectkorra.projectkorra.database.DatabaseQuery; +import com.projectkorra.projectkorra.database.DatabaseRepository; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashSet; +import java.util.Set; + +public class ElementRepository extends DatabaseRepository +{ + private static final DatabaseQuery CREATE_TABLE_ELEMENTS = DatabaseQuery.newBuilder() + .mysql("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTO_INCREMENT, element_name VARCHAR(50) NOT NULL, UNIQUE INDEX name_index (element_name));") + .sqlite("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTOINCREMENT, element_name VARCHAR(50) NOT NULL); CREATE UNIQUE INDEX name_index ON pk_elements (element_name);") + .build(); + private static final DatabaseQuery CREATE_TABLE_PLAYER_ELEMENTS = DatabaseQuery.newBuilder() + .mysql("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)), INDEX player_index (player_id), INDEX element_index (element_id));") + .sqlite("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)); CREATE INDEX player_index ON pk_player_elements (player_id); CREATE INDEX element_index ON pk_player_elements (element_id);") + .build(); + + private static final DatabaseQuery SELECT_ELEMENT_ID = DatabaseQuery.newBuilder() + .query("SELECT element_id FROM pk_elements WHERE element_name = ?;") + .build(); + + private static final DatabaseQuery INSERT_ELEMENT_ID = DatabaseQuery.newBuilder() + .query("INSERT INTO pk_elements (element_name) VALUES (?);") + .build(); + + private static final DatabaseQuery SELECT_PLAYER_ELEMENTS = DatabaseQuery.newBuilder() + .query("SELECT element_id FROM pk_player_elements WHERE player_id = ?;") + .build(); + + private static final DatabaseQuery INSERT_PLAYER_ELEMENT = DatabaseQuery.newBuilder() + .query("INSERT INTO pk_player_elements VALUES (?, ?);") + .build(); + + private static final DatabaseQuery DELETE_PLAYER_ELEMENT = DatabaseQuery.newBuilder() + .query("DELETE FROM pk_player_elements WHERE player_id = ? AND element_id = ?;") + .build(); + + protected void createTables() throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try + ( + PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); + PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery()) + ) + { + elements.executeUpdate(); + playerElements.executeUpdate(); + } + } + + protected int selectElemenetId(String elementName) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(SELECT_ELEMENT_ID.getQuery())) + { + statement.setString(1, elementName); + + try (ResultSet rs = statement.executeQuery()) + { + if (!rs.next()) + { + return insertElementId(elementName); + } + + return rs.getInt("element_id"); + } + } + } + + private int insertElementId(String elementName) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(INSERT_ELEMENT_ID.getQuery(), Statement.RETURN_GENERATED_KEYS)) + { + statement.setString(1, elementName); + + statement.executeUpdate(); + + try (ResultSet rs = statement.getGeneratedKeys()) + { + rs.next(); + + return rs.getInt(1); + } + } + } + + protected Set selectPlayerElements(int playerId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ELEMENTS.getQuery())) + { + statement.setInt(1, playerId); + + Set elements = new HashSet<>(); + + try (ResultSet rs = statement.executeQuery()) + { + while (rs.next()) + { + elements.add(rs.getInt("element_id")); + } + + return elements; + } + } + } + + protected void insertPlayerElement(int playerId, int elementId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ELEMENT.getQuery())) + { + statement.setInt(1, playerId); + statement.setInt(2, elementId); + + statement.executeUpdate(); + } + } + + protected void deletePlayerElement(int playerId, int elementId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENT.getQuery())) + { + statement.setInt(1, playerId); + statement.setInt(2, elementId); + + statement.executeUpdate(); + } + } +} diff --git a/src/com/projectkorra/projectkorra/element/SubElement.java b/src/com/projectkorra/projectkorra/element/SubElement.java new file mode 100644 index 00000000..68421cc2 --- /dev/null +++ b/src/com/projectkorra/projectkorra/element/SubElement.java @@ -0,0 +1,20 @@ +package com.projectkorra.projectkorra.element; + +import org.bukkit.ChatColor; + +public class SubElement extends Element +{ + private final Element _parent; + + public SubElement(int elementId, String elementName, String displayName, ChatColor color, Element parent) + { + super(elementId, elementName, displayName, color); + + _parent = parent; + } + + public Element getParent() + { + return _parent; + } +} diff --git a/src/com/projectkorra/projectkorra/module/ModuleManager.java b/src/com/projectkorra/projectkorra/module/ModuleManager.java index afbc9531..e7ab42e9 100644 --- a/src/com/projectkorra/projectkorra/module/ModuleManager.java +++ b/src/com/projectkorra/projectkorra/module/ModuleManager.java @@ -2,6 +2,7 @@ package com.projectkorra.projectkorra.module; import com.google.common.base.Preconditions; import com.projectkorra.projectkorra.database.DatabaseManager; +import com.projectkorra.projectkorra.element.ElementManager; import com.projectkorra.projectkorra.player.BendingPlayerManager; import java.lang.reflect.Constructor; @@ -61,12 +62,14 @@ public class ModuleManager { public static void startup() { registerModule(DatabaseManager.class); registerModule(BendingPlayerManager.class); + registerModule(ElementManager.class); } /** * Disable all our core {@link Module}s onDisable. */ public static void shutdown() { + registerModule(ElementManager.class); getModule(BendingPlayerManager.class).disable(); getModule(DatabaseManager.class).disable(); } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index 7985c7ed..6d288c4b 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -1,5 +1,11 @@ package com.projectkorra.projectkorra.player; +import com.projectkorra.projectkorra.element.Element; +import com.projectkorra.projectkorra.element.SubElement; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import java.util.UUID; public class BendingPlayer @@ -7,7 +13,10 @@ public class BendingPlayer private final int _playerId; private final UUID _uuid; private final String _playerName; - private long _firstLogin; + private final long _firstLogin; + + private final List _elements; + private final List _subElements; public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) { @@ -15,6 +24,9 @@ public class BendingPlayer _uuid = uuid; _playerName = playerName; _firstLogin = firstLogin; + + _elements = new ArrayList<>(); + _subElements = new ArrayList<>(); } public int getId() @@ -26,4 +38,19 @@ public class BendingPlayer { return _firstLogin; } + + public void addElements(Collection elements) + { + for (Element element : elements) + { + if (element instanceof SubElement) + { + _subElements.add((SubElement) element); + } + else + { + _elements.add(element); + } + } + } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java b/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java new file mode 100644 index 00000000..f1fb08be --- /dev/null +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java @@ -0,0 +1,35 @@ +package com.projectkorra.projectkorra.player; + +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class BendingPlayerLoadedEvent extends PlayerEvent +{ + private static final HandlerList HANDLER_LIST = new HandlerList(); + + private final BendingPlayer _bendingPlayer; + + public BendingPlayerLoadedEvent(Player player, BendingPlayer bendingPlayer) + { + super(player); + + _bendingPlayer = bendingPlayer; + } + + public BendingPlayer getBendingPlayer() + { + return _bendingPlayer; + } + + @Override + public HandlerList getHandlers() + { + return HANDLER_LIST; + } + + public static HandlerList getHandlerList() + { + return HANDLER_LIST; + } +} diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java index 7a1fa3b6..346edeca 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -6,6 +6,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerLoginEvent; +import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -20,7 +21,14 @@ public class BendingPlayerManager extends DatabaseModule { - getRepository().createTable(); + try + { + getRepository().createTables(); + } + catch (SQLException e) + { + e.printStackTrace(); + } runSync(() -> { @@ -36,12 +44,22 @@ public class BendingPlayerManager extends DatabaseModule { - BendingPlayer bendingPlayer = getRepository().selectPlayer(player); - - runSync(() -> + try { - _players.put(player.getUniqueId(), bendingPlayer); - }); + BendingPlayer bendingPlayer = getRepository().selectPlayer(player); + + runSync(() -> + { + _players.put(player.getUniqueId(), bendingPlayer); + + BendingPlayerLoadedEvent bendingPlayerLoadedEvent = new BendingPlayerLoadedEvent(player, bendingPlayer); + getPlugin().getServer().getPluginManager().callEvent(bendingPlayerLoadedEvent); + }); + } + catch (SQLException e) + { + e.printStackTrace(); + } }); } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java index 557a8934..deea5133 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java @@ -31,7 +31,7 @@ public class BendingPlayerRepository extends DatabaseRepository .query("UPDATE pk_bending_players SET player_name = ? WHERE player_id = ?;") .build(); - protected void createTable() + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); @@ -39,13 +39,9 @@ public class BendingPlayerRepository extends DatabaseRepository { statement.executeUpdate(); } - catch (SQLException e) - { - e.printStackTrace(); - } } - protected BendingPlayer selectPlayer(Player player) + protected BendingPlayer selectPlayer(Player player) throws SQLException { UUID uuid = player.getUniqueId(); byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); @@ -75,15 +71,9 @@ public class BendingPlayerRepository extends DatabaseRepository return new BendingPlayer(playerId, uuid, playerName, firstLogin); } } - catch (SQLException e) - { - e.printStackTrace(); - } - - return null; } - private BendingPlayer insertPlayer(UUID uuid, String playerName) + private BendingPlayer insertPlayer(UUID uuid, String playerName) throws SQLException { byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); @@ -100,23 +90,16 @@ public class BendingPlayerRepository extends DatabaseRepository try (ResultSet rs = statement.getGeneratedKeys()) { - if (rs.next()) - { - int playerId = rs.getInt(1); + rs.next(); - return new BendingPlayer(playerId, uuid, playerName, firstLogin); - } + int playerId = rs.getInt(1); + + return new BendingPlayer(playerId, uuid, playerName, firstLogin); } } - catch (SQLException e) - { - e.printStackTrace(); - } - - return null; } - protected void updatePlayer(int playerId, String playerName) + protected void updatePlayer(int playerId, String playerName) throws SQLException { Connection connection = getDatabase().getConnection(); @@ -127,9 +110,5 @@ public class BendingPlayerRepository extends DatabaseRepository statement.executeUpdate(); } - catch (SQLException e) - { - e.printStackTrace(); - } } } From aee46d53c3ff8f8e8fe35894e7dff8d7196d3f35 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Tue, 22 Oct 2019 18:25:21 +1000 Subject: [PATCH 14/22] Added new cooldown system --- .../projectkorra/BendingManager.java | 5 + .../cooldown/CooldownManager.java | 230 ++++++++++++++++++ .../cooldown/CooldownRepository.java | 92 +++++++ .../projectkorra/element/ElementManager.java | 2 +- .../projectkorra/module/Module.java | 10 + .../projectkorra/module/ModuleManager.java | 3 + .../projectkorra/player/BendingPlayer.java | 19 -- .../player/BendingPlayerManager.java | 78 ++++-- 8 files changed, 395 insertions(+), 44 deletions(-) create mode 100644 src/com/projectkorra/projectkorra/cooldown/CooldownManager.java create mode 100644 src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java diff --git a/src/com/projectkorra/projectkorra/BendingManager.java b/src/com/projectkorra/projectkorra/BendingManager.java index b75514ef..4882d45a 100644 --- a/src/com/projectkorra/projectkorra/BendingManager.java +++ b/src/com/projectkorra/projectkorra/BendingManager.java @@ -5,6 +5,7 @@ import java.util.UUID; import co.aikar.timings.lib.MCTiming; +import com.projectkorra.projectkorra.cooldown.CooldownManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; @@ -49,6 +50,10 @@ public class BendingManager implements Runnable { return instance; } + /** + * @deprecated handled by {@link CooldownManager}. + */ + @Deprecated public void handleCooldowns() { for (final UUID uuid : BendingPlayer.getPlayers().keySet()) { final BendingPlayer bPlayer = BendingPlayer.getPlayers().get(uuid); diff --git a/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java new file mode 100644 index 00000000..c4267fc4 --- /dev/null +++ b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java @@ -0,0 +1,230 @@ +package com.projectkorra.projectkorra.cooldown; + +import com.projectkorra.projectkorra.event.PlayerCooldownChangeEvent; +import com.projectkorra.projectkorra.module.DatabaseModule; +import com.projectkorra.projectkorra.module.ModuleManager; +import com.projectkorra.projectkorra.player.BendingPlayer; +import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; +import com.projectkorra.projectkorra.player.BendingPlayerManager; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.sql.SQLException; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.UUID; +import java.util.function.Function; + +public class CooldownManager extends DatabaseModule +{ + private final BendingPlayerManager _bendingPlayerManager; + + private final Map> _cooldownMap = new HashMap<>(); + private final Map> _cooldownQueue = new HashMap<>(); + + private final Function> _queueFunction = uuid -> new PriorityQueue<>(Comparator.comparing(cooldown -> cooldown.ExpireTime)); + + private CooldownManager() + { + super("Cooldown", new CooldownRepository()); + + _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + + runAsync(() -> + { + try + { + getRepository().createTables(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + + runTimer(() -> + { + _cooldownQueue.forEach((uuid, cooldowns) -> + { + long currentTime = System.currentTimeMillis(); + + while (!cooldowns.isEmpty()) + { + Cooldown cooldown = cooldowns.peek(); + + if (currentTime < cooldown.ExpireTime) + { + break; + } + + _cooldownMap.get(uuid).remove(cooldown.AbilityName); + cooldowns.poll(); + + if (cooldown.Permanent) + { + int playerId = _bendingPlayerManager.getBendingPlayer(uuid).getId(); + + runAsync(() -> + { + try + { + getRepository().deleteCooldown(playerId, cooldown.AbilityName); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + } + }); + + _cooldownMap.values().removeIf(Map::isEmpty); + _cooldownQueue.values().removeIf(PriorityQueue::isEmpty); + }, 1, 1); + } + + @EventHandler + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) + { + Player player = event.getPlayer(); + BendingPlayer bendingPlayer = event.getBendingPlayer(); + + runAsync(() -> + { + try + { + Map cooldowns = getRepository().selectCooldowns(bendingPlayer.getId()); + + _cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).putAll(cooldowns); + _cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).addAll(cooldowns.values()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) + { + _cooldownMap.remove(event.getPlayer().getUniqueId()); + _cooldownQueue.remove(event.getPlayer().getUniqueId()); + } + + public void addCooldown(Player player, String abilityName, long duration, boolean permanent) + { + if (duration <= 0) + { + return; + } + + PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(player, abilityName, duration, PlayerCooldownChangeEvent.Result.ADDED); + getPlugin().getServer().getPluginManager().callEvent(event); + + if (event.isCancelled()) + { + return; + } + + long expireTime = System.currentTimeMillis() + duration; + Cooldown cooldown = new Cooldown(abilityName, expireTime, permanent); + + _cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).put(abilityName, cooldown); + _cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).add(cooldown); + + if (permanent) + { + int playerId = _bendingPlayerManager.getBendingPlayer(player).getId(); + + runAsync(() -> + { + try + { + getRepository().insertCooldown(playerId, abilityName, expireTime); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + } + + public long getCooldown(Player player, String abilityName) + { + Map cooldowns = _cooldownMap.get(player.getUniqueId()); + + if (cooldowns != null && cooldowns.containsKey(abilityName)) + { + return cooldowns.get(abilityName).ExpireTime; + } + + return -1L; + } + + public boolean isOnCooldown(Player player, String abilityName) + { + Map cooldowns = _cooldownMap.get(player.getUniqueId()); + + return cooldowns != null && cooldowns.containsKey(abilityName); + } + + public void removeCooldown(Player player, Cooldown cooldown) + { + UUID uuid = player.getUniqueId(); + + if (_cooldownMap.containsKey(uuid)) + { + _cooldownMap.get(uuid).remove(cooldown.AbilityName); + } + + if (_cooldownQueue.containsKey(uuid)) + { + _cooldownQueue.get(uuid).remove(cooldown); + } + + if (cooldown.Permanent) + { + int playerId = _bendingPlayerManager.getBendingPlayer(player).getId(); + + runAsync(() -> + { + try + { + getRepository().deleteCooldown(playerId, cooldown.AbilityName); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + } + + public static class Cooldown + { + final String AbilityName; + final long ExpireTime; + final boolean Permanent; + + public Cooldown(String abilityName, long expireTime) + { + this(abilityName, expireTime, false); + } + + public Cooldown(String abilityName, long expireTime, boolean permanent) + { + AbilityName = abilityName; + ExpireTime = expireTime; + Permanent = permanent; + } + + + } +} diff --git a/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java b/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java new file mode 100644 index 00000000..3783d4ed --- /dev/null +++ b/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java @@ -0,0 +1,92 @@ +package com.projectkorra.projectkorra.cooldown; + +import com.projectkorra.projectkorra.database.DatabaseQuery; +import com.projectkorra.projectkorra.database.DatabaseRepository; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +public class CooldownRepository extends DatabaseRepository +{ + private static final DatabaseQuery CREATE_TABLE_COOLDOWNS = DatabaseQuery.newBuilder() + .query("CREATE TABLE IF NOT EXISTS pk_cooldowns (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(100) NOT NULL, expire_time BIGINT NOT NULL, PRIMARY KEY (player_id, ability_name));") + .build(); + + private static final DatabaseQuery SELECT_COOLDOWNS = DatabaseQuery.newBuilder() + .query("SELECT * FROM pk_cooldowns WHERE player_id = ?") + .build(); + + private static final DatabaseQuery INSERT_COOLDOWN = DatabaseQuery.newBuilder() + .query("INSERT INTO pk_cooldowns VALUES (?, ?, ?);") + .build(); + + private static final DatabaseQuery DELETE_COOLDOWN = DatabaseQuery.newBuilder() + .query("DELETE FROM pk_cooldowns WHERE player_id = ? AND ability_name = ?;") + .build(); + + protected void createTables() throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_COOLDOWNS.getQuery())) + { + statement.executeUpdate(); + } + } + + protected Map selectCooldowns(int playerId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(SELECT_COOLDOWNS.getQuery())) + { + statement.setInt(1, playerId); + + Map cooldowns = new HashMap<>(); + + try (ResultSet rs = statement.executeQuery()) + { + while (rs.next()) + { + String abilityName = rs.getString("ability_name"); + long expireTime = rs.getLong("expire_time"); + + cooldowns.put(abilityName, new CooldownManager.Cooldown(abilityName, expireTime, true)); + } + + return cooldowns; + } + } + } + + protected void insertCooldown(int playerId, String abilityName, long expireTime) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(INSERT_COOLDOWN.getQuery())) + { + statement.setInt(1, playerId); + statement.setString(2, abilityName); + statement.setLong(3, expireTime); + + statement.executeUpdate(); + } + } + + protected void deleteCooldown(int playerId, String abilityName) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(DELETE_COOLDOWN.getQuery())) + { + statement.setInt(1, playerId); + statement.setString(2, abilityName); + + statement.executeUpdate(); + } + } +} diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java index e01638ea..83665e52 100644 --- a/src/com/projectkorra/projectkorra/element/ElementManager.java +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -103,7 +103,7 @@ public class ElementManager extends DatabaseModule .map(_elements::get) .collect(Collectors.toList()); - bendingPlayer.addElements(elements); +// bendingPlayer.addElements(elements); } catch (SQLException e) { diff --git a/src/com/projectkorra/projectkorra/module/Module.java b/src/com/projectkorra/projectkorra/module/Module.java index 692a8292..4ba9642c 100644 --- a/src/com/projectkorra/projectkorra/module/Module.java +++ b/src/com/projectkorra/projectkorra/module/Module.java @@ -65,6 +65,16 @@ public abstract class Module implements Listener getPlugin().getServer().getScheduler().runTaskAsynchronously(getPlugin(), runnable); } + protected final void runTimer(Runnable runnable, long delay, long period) + { + getPlugin().getServer().getScheduler().runTaskTimer(getPlugin(), runnable, delay, period); + } + + protected final void runAsyncTimer(Runnable runnable, long delay, long period) + { + getPlugin().getServer().getScheduler().runTaskTimerAsynchronously(getPlugin(), runnable, delay, period); + } + public String getName() { return this.name; diff --git a/src/com/projectkorra/projectkorra/module/ModuleManager.java b/src/com/projectkorra/projectkorra/module/ModuleManager.java index e7ab42e9..6f867f92 100644 --- a/src/com/projectkorra/projectkorra/module/ModuleManager.java +++ b/src/com/projectkorra/projectkorra/module/ModuleManager.java @@ -1,6 +1,7 @@ package com.projectkorra.projectkorra.module; import com.google.common.base.Preconditions; +import com.projectkorra.projectkorra.cooldown.CooldownManager; import com.projectkorra.projectkorra.database.DatabaseManager; import com.projectkorra.projectkorra.element.ElementManager; import com.projectkorra.projectkorra.player.BendingPlayerManager; @@ -63,12 +64,14 @@ public class ModuleManager { registerModule(DatabaseManager.class); registerModule(BendingPlayerManager.class); registerModule(ElementManager.class); + registerModule(CooldownManager.class); } /** * Disable all our core {@link Module}s onDisable. */ public static void shutdown() { + registerModule(CooldownManager.class); registerModule(ElementManager.class); getModule(BendingPlayerManager.class).disable(); getModule(DatabaseManager.class).disable(); diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index 6d288c4b..8236d1ba 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -1,10 +1,8 @@ package com.projectkorra.projectkorra.player; import com.projectkorra.projectkorra.element.Element; -import com.projectkorra.projectkorra.element.SubElement; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.UUID; @@ -16,7 +14,6 @@ public class BendingPlayer private final long _firstLogin; private final List _elements; - private final List _subElements; public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) { @@ -26,7 +23,6 @@ public class BendingPlayer _firstLogin = firstLogin; _elements = new ArrayList<>(); - _subElements = new ArrayList<>(); } public int getId() @@ -38,19 +34,4 @@ public class BendingPlayer { return _firstLogin; } - - public void addElements(Collection elements) - { - for (Element element : elements) - { - if (element instanceof SubElement) - { - _subElements.add((SubElement) element); - } - else - { - _elements.add(element); - } - } - } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java index 346edeca..2b1e5c43 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -1,10 +1,13 @@ package com.projectkorra.projectkorra.player; +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.event.PlayerCooldownChangeEvent; import com.projectkorra.projectkorra.module.DatabaseModule; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerQuitEvent; import java.sql.SQLException; import java.util.HashMap; @@ -24,47 +27,74 @@ public class BendingPlayerManager extends DatabaseModule - { - log("Created database table."); - }); }); } @EventHandler(priority = EventPriority.LOWEST) public void onLogin(PlayerLoginEvent event) { - Player player = event.getPlayer(); - runAsync(() -> { - try - { - BendingPlayer bendingPlayer = getRepository().selectPlayer(player); - - runSync(() -> - { - _players.put(player.getUniqueId(), bendingPlayer); - - BendingPlayerLoadedEvent bendingPlayerLoadedEvent = new BendingPlayerLoadedEvent(player, bendingPlayer); - getPlugin().getServer().getPluginManager().callEvent(bendingPlayerLoadedEvent); - }); - } - catch (SQLException e) - { - e.printStackTrace(); - } + loadBendingPlayer(event.getPlayer()); }); } + @EventHandler + public void onQuit(PlayerQuitEvent event) + { + // TODO Queue disconnected players and execute in a batch + _players.remove(event.getPlayer().getUniqueId()); + } + + @EventHandler + public void onCooldownChange(PlayerCooldownChangeEvent event) + { + Player player = event.getPlayer(); + BendingPlayer bendingPlayer = _players.get(player.getUniqueId()); + + String ability = event.getAbility(); + + // TODO Check bound ability + GeneralMethods.displayMovePreview(player); + } + + private void loadBendingPlayer(Player player) + { + try + { + BendingPlayer bendingPlayer = getRepository().selectPlayer(player); + + runSync(() -> + { + _players.put(player.getUniqueId(), bendingPlayer); + + BendingPlayerLoadedEvent bendingPlayerLoadedEvent = new BendingPlayerLoadedEvent(player, bendingPlayer); + getPlugin().getServer().getPluginManager().callEvent(bendingPlayerLoadedEvent); + }); + } + catch (SQLException e) + { + e.printStackTrace(); + } + } + public BendingPlayer getBendingPlayer(Player player) { - return _players.get(player.getUniqueId()); + return getBendingPlayer(player.getUniqueId()); + } + + public BendingPlayer getBendingPlayer(UUID uuid) + { + return _players.get(uuid); } } From 87b6186bee7532bab764dd9baa3de182866ff4a9 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Tue, 22 Oct 2019 23:10:40 +1000 Subject: [PATCH 15/22] Added methods to BendingPlayer --- .../cooldown/CooldownManager.java | 15 +- .../projectkorra/element/ElementManager.java | 112 +++++++++++- .../projectkorra/player/BendingPlayer.java | 164 ++++++++++++++++-- 3 files changed, 272 insertions(+), 19 deletions(-) diff --git a/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java index c4267fc4..cd2c79d2 100644 --- a/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java +++ b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java @@ -8,7 +8,6 @@ import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; import com.projectkorra.projectkorra.player.BendingPlayerManager; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.sql.SQLException; @@ -175,13 +174,21 @@ public class CooldownManager extends DatabaseModule return cooldowns != null && cooldowns.containsKey(abilityName); } - public void removeCooldown(Player player, Cooldown cooldown) + public void removeCooldown(Player player, String abilityName) { UUID uuid = player.getUniqueId(); + Map cooldowns = _cooldownMap.get(player.getUniqueId()); - if (_cooldownMap.containsKey(uuid)) + if (cooldowns == null) { - _cooldownMap.get(uuid).remove(cooldown.AbilityName); + return; + } + + Cooldown cooldown = cooldowns.remove(abilityName); + + if (cooldown == null) + { + return; } if (_cooldownQueue.containsKey(uuid)) diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java index 83665e52..29140c32 100644 --- a/src/com/projectkorra/projectkorra/element/ElementManager.java +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -22,6 +22,8 @@ public class ElementManager extends DatabaseModule private static final String WATER = "water"; private static final String BLOOD = "blood"; private static final String HEALING = "healing"; + private static final String ICE = "ice"; + private static final String PLANT = "plant"; private static final String EARTH = "earth"; private static final String LAVA = "lava"; private static final String METAL = "metal"; @@ -33,6 +35,7 @@ public class ElementManager extends DatabaseModule private static final String FLIGHT = "flight"; private static final String SPIRITUAL = "spiritual"; private static final String CHI = "chi"; + private static final String AVATAR = "avatar"; private final BendingPlayerManager _bendingPlayerManager; @@ -57,6 +60,8 @@ public class ElementManager extends DatabaseModule Element water = addElement(WATER, "Water", ChatColor.AQUA); addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water); addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water); + addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, water); + addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, water); // Earthbending Element earth = addElement(EARTH, "Earth", ChatColor.AQUA); @@ -76,6 +81,9 @@ public class ElementManager extends DatabaseModule // Chiblocking Element chi = addElement(CHI, "Chi", ChatColor.GOLD); + + // Avatar + Element avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE); } catch (SQLException e) { @@ -103,7 +111,7 @@ public class ElementManager extends DatabaseModule .map(_elements::get) .collect(Collectors.toList()); -// bendingPlayer.addElements(elements); + elements.forEach(bendingPlayer::addElement); } catch (SQLException e) { @@ -152,4 +160,106 @@ public class ElementManager extends DatabaseModule return -1; } } + + private Element getElement(String elementName) + { + return _names.get(elementName); + } + + private SubElement getSubElement(String elementName) + { + Element element = getElement(elementName); + + if (element instanceof SubElement) + { + return (SubElement) element; + } + + return null; + } + + public Element getWater() + { + return getElement(WATER); + } + + public SubElement getBlood() + { + return getSubElement(BLOOD); + } + + public SubElement getHealing() + { + return getSubElement(HEALING); + } + + public SubElement getIce() + { + return getSubElement(ICE); + } + + public SubElement getPlant() + { + return getSubElement(PLANT); + } + + public Element getEarth() + { + return getElement(EARTH); + } + + public SubElement getLava() + { + return getSubElement(LAVA); + } + + public SubElement getMetal() + { + return getSubElement(METAL); + } + + public SubElement getSand() + { + return getSubElement(SAND); + } + + public Element getFire() + { + return getElement(FIRE); + } + + public SubElement getCombustion() + { + return getSubElement(COMBUSTION); + } + + public SubElement getLightning() + { + return getSubElement(LIGHTNING); + } + + public Element getAir() + { + return getElement(AIR); + } + + public SubElement getFlight() + { + return getSubElement(FLIGHT); + } + + public SubElement getSpiritual() + { + return getSubElement(SPIRITUAL); + } + + public Element getChi() + { + return getElement(CHI); + } + + public Element getAvatar() + { + return getElement(AVATAR); + } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index 8236d1ba..e85b85cf 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -1,37 +1,173 @@ package com.projectkorra.projectkorra.player; +import com.projectkorra.projectkorra.ability.Ability; +import com.projectkorra.projectkorra.cooldown.CooldownManager; import com.projectkorra.projectkorra.element.Element; +import com.projectkorra.projectkorra.element.ElementManager; +import com.projectkorra.projectkorra.module.ModuleManager; +import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; +import java.util.Set; import java.util.UUID; public class BendingPlayer { - private final int _playerId; - private final UUID _uuid; - private final String _playerName; - private final long _firstLogin; + private final BendingPlayerManager manager; + private final ElementManager elementManager; + private final CooldownManager cooldownManager; - private final List _elements; + private final int playerId; + private final UUID uuid; + private final Player player; + private final String playerName; + private final long firstLogin; + + private final Set elements; public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) { - _playerId = playerId; - _uuid = uuid; - _playerName = playerName; - _firstLogin = firstLogin; + this.manager = ModuleManager.getModule(BendingPlayerManager.class); + this.elementManager = ModuleManager.getModule(ElementManager.class); + this.cooldownManager = ModuleManager.getModule(CooldownManager.class); - _elements = new ArrayList<>(); + this.playerId = playerId; + this.uuid = uuid; + this.player = manager.getPlugin().getServer().getPlayer(uuid); + this.playerName = playerName; + this.firstLogin = firstLogin; + + this.elements = new HashSet<>(); + } + + public void addElement(Element element) + { + this.elements.add(element); + } + + public void setElement(Element element) + { + this.elements.clear(); + this.elements.add(element); + } + + public boolean hasElement(Element element) + { + if (element.equals(elementManager.getAvatar())) + { + return this.player.hasPermission("bending.avatar"); + } + + return this.elements.contains(element); + } + + public boolean canBloodbend() + { + return this.elements.contains(elementManager.getBlood()); + } + + public boolean canUseHealing() + { + return this.elements.contains(elementManager.getHealing()); + } + + public boolean canIcebend() + { + return this.elements.contains(elementManager.getIce()); + } + + public boolean canPlantbend() + { + return this.elements.contains(elementManager.getPlant()); + } + + public boolean canLavabend() + { + return this.elements.contains(elementManager.getLava()); + } + + public boolean canMetalbend() + { + return this.elements.contains(elementManager.getMetal()); + } + + public boolean canSandbend() + { + return this.elements.contains(elementManager.getSand()); + } + + public boolean canCombustionbend() + { + return this.elements.contains(elementManager.getCombustion()); + } + + public boolean canUseLightning() + { + return this.elements.contains(elementManager.getLightning()); + } + + public boolean canUseFlight() + { + return this.elements.contains(elementManager.getFlight()); + } + + public boolean canUseSpiritual() + { + return this.elements.contains(elementManager.getSpiritual()); + } + + public void addCooldown(Ability ability) + { + addCooldown(ability, ability.getCooldown()); + } + + public void addCooldown(Ability ability, long duration) + { + addCooldown(ability.getName(), duration); + } + + public void addCooldown(Ability ability, long duration, boolean permanent) + { + addCooldown(ability.getName(), duration, permanent); + } + + public void addCooldown(String abilityName, long duration) + { + addCooldown(abilityName, duration, false); + } + + public void addCooldown(String abilityName, long duration, boolean permanent) + { + cooldownManager.addCooldown(this.player, abilityName, duration, permanent); + } + + public boolean isOnCooldown(Ability ability) + { + return isOnCooldown(ability.getName()); + } + + public boolean isOnCooldown(String abilityName) + { + return cooldownManager.isOnCooldown(this.player, abilityName); + } + + public void removeCooldown(Ability ability) + { + removeCoolldown(ability.getName()); + } + + public void removeCoolldown(String abilityName) + { + cooldownManager.removeCooldown(this.player, abilityName); } public int getId() { - return _playerId; + return this.playerId; } public long getFirstLogin() { - return _firstLogin; + return this.firstLogin; } } From 64b138a6c1ff36069291953eea1fe49ac3f18c81 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 09:12:18 +1000 Subject: [PATCH 16/22] Cleaned ElementManager + added more BendingPlayer methods --- .../projectkorra/BendingPlayer.java | 3 + .../projectkorra/GeneralMethods.java | 7 + .../projectkorra/element/ElementManager.java | 122 +++++++----------- .../projectkorra/player/BendingPlayer.java | 119 +++++++++++++++++ 4 files changed, 174 insertions(+), 77 deletions(-) diff --git a/src/com/projectkorra/projectkorra/BendingPlayer.java b/src/com/projectkorra/projectkorra/BendingPlayer.java index ce1aed51..5b0faf68 100644 --- a/src/com/projectkorra/projectkorra/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/BendingPlayer.java @@ -40,7 +40,10 @@ import com.projectkorra.projectkorra.waterbending.blood.Bloodbending; /** * Class that presents a player and stores all bending information about the * player. + * + * @deprecated use {@link com.projectkorra.projectkorra.player.BendingPlayer}. */ +@Deprecated public class BendingPlayer { /** diff --git a/src/com/projectkorra/projectkorra/GeneralMethods.java b/src/com/projectkorra/projectkorra/GeneralMethods.java index d16fa96d..dbbe24dc 100644 --- a/src/com/projectkorra/projectkorra/GeneralMethods.java +++ b/src/com/projectkorra/projectkorra/GeneralMethods.java @@ -52,6 +52,9 @@ import com.palmergames.bukkit.towny.object.WorldCoord; import com.palmergames.bukkit.towny.utils.PlayerCacheUtil; import com.palmergames.bukkit.towny.war.flagwar.TownyWar; import com.palmergames.bukkit.towny.war.flagwar.TownyWarConfig; +import com.projectkorra.projectkorra.cooldown.CooldownManager; +import com.projectkorra.projectkorra.element.ElementManager; +import com.projectkorra.projectkorra.player.BendingPlayerManager; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; @@ -323,7 +326,10 @@ public class GeneralMethods { * @param uuid The UUID of the player * @param player The player name * @throws SQLException + * + * @deprecated use {@link BendingPlayerManager} and {@link ElementManager}. */ + @Deprecated public static void createBendingPlayer(final UUID uuid, final String player) { new BukkitRunnable() { @@ -335,6 +341,7 @@ public class GeneralMethods { }.runTaskAsynchronously(ProjectKorra.plugin); } + @Deprecated private static void createBendingPlayerAsynchronously(final UUID uuid, final String player) { final ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM pk_players WHERE uuid = '" + uuid.toString() + "'"); try { diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java index 29140c32..3d3efd4e 100644 --- a/src/com/projectkorra/projectkorra/element/ElementManager.java +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -2,10 +2,8 @@ package com.projectkorra.projectkorra.element; import com.google.common.base.Preconditions; import com.projectkorra.projectkorra.module.DatabaseModule; -import com.projectkorra.projectkorra.module.ModuleManager; import com.projectkorra.projectkorra.player.BendingPlayer; import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; -import com.projectkorra.projectkorra.player.BendingPlayerManager; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -19,37 +17,26 @@ import java.util.stream.Collectors; public class ElementManager extends DatabaseModule { - private static final String WATER = "water"; - private static final String BLOOD = "blood"; - private static final String HEALING = "healing"; - private static final String ICE = "ice"; - private static final String PLANT = "plant"; - private static final String EARTH = "earth"; - private static final String LAVA = "lava"; - private static final String METAL = "metal"; - private static final String SAND = "sand"; - private static final String FIRE = "fire"; - private static final String COMBUSTION = "combustion"; - private static final String LIGHTNING = "lightning"; - private static final String AIR = "air"; - private static final String FLIGHT = "flight"; - private static final String SPIRITUAL = "spiritual"; - private static final String CHI = "chi"; - private static final String AVATAR = "avatar"; - - private final BendingPlayerManager _bendingPlayerManager; + private static final String WATER = "water", EARTH = "earth", FIRE = "fire", AIR = "air", CHI = "chi", AVATAR = "avatar"; + private static final String BLOOD = "blood", HEALING = "healing", ICE = "ice", PLANT = "plant"; + private static final String LAVA = "lava", METAL = "metal", SAND = "sand"; + private static final String COMBUSTION = "combustion", LIGHTNING = "lightning"; + private static final String FLIGHT = "flight", SPIRITUAL = "spiritual"; private final Map _elements = new HashMap<>(); - private final Map _names = new HashMap<>(); private final String _nameRegex = "[a-zA-Z]+"; + private Element water, earth, fire, air, chi, avatar; + private SubElement blood, healing, ice, plant; + private SubElement lava, metal, sand; + private SubElement combustion, lightning; + private SubElement flight, spiritual; + private ElementManager() { super("Element", new ElementRepository()); - _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); - runAsync(() -> { try @@ -57,33 +44,33 @@ public class ElementManager extends DatabaseModule getRepository().createTables(); // Waterbending - Element water = addElement(WATER, "Water", ChatColor.AQUA); - addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water); - addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water); - addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, water); - addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, water); + water = addElement(WATER, "Water", ChatColor.AQUA); + blood = addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water); + healing = addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water); + ice = addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, water); + plant = addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, water); // Earthbending - Element earth = addElement(EARTH, "Earth", ChatColor.AQUA); - addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, earth); - addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, earth); - addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, earth); + earth = addElement(EARTH, "Earth", ChatColor.AQUA); + lava =addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, earth); + metal = addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, earth); + sand = addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, earth); // Firebending - Element fire = addElement(FIRE, "Fire", ChatColor.RED); - addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, fire); - addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, fire); + fire = addElement(FIRE, "Fire", ChatColor.RED); + combustion = addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, fire); + lightning = addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, fire); // Airbending - Element air = addElement(AIR, "Air", ChatColor.GRAY); - addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, air); - addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, air); + air = addElement(AIR, "Air", ChatColor.GRAY); + flight = addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, air); + spiritual = addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, air); // Chiblocking - Element chi = addElement(CHI, "Chi", ChatColor.GOLD); + chi = addElement(CHI, "Chi", ChatColor.GOLD); // Avatar - Element avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE); + avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE); } catch (SQLException e) { @@ -127,7 +114,6 @@ public class ElementManager extends DatabaseModule Element element = new Element(elementId, elementName, displayName, color); _elements.put(elementId, element); - _names.put(elementName, element); return element; } @@ -139,7 +125,6 @@ public class ElementManager extends DatabaseModule SubElement element = new SubElement(elementId, elementName, displayName, color, parent); _elements.put(elementId, element); - _names.put(elementName, element); return element; } @@ -161,105 +146,88 @@ public class ElementManager extends DatabaseModule } } - private Element getElement(String elementName) - { - return _names.get(elementName); - } - - private SubElement getSubElement(String elementName) - { - Element element = getElement(elementName); - - if (element instanceof SubElement) - { - return (SubElement) element; - } - - return null; - } - public Element getWater() { - return getElement(WATER); + return water; } public SubElement getBlood() { - return getSubElement(BLOOD); + return blood; } public SubElement getHealing() { - return getSubElement(HEALING); + return healing; } public SubElement getIce() { - return getSubElement(ICE); + return ice; } public SubElement getPlant() { - return getSubElement(PLANT); + return plant; } public Element getEarth() { - return getElement(EARTH); + return earth; } public SubElement getLava() { - return getSubElement(LAVA); + return lava; } public SubElement getMetal() { - return getSubElement(METAL); + return metal; } public SubElement getSand() { - return getSubElement(SAND); + return sand; } public Element getFire() { - return getElement(FIRE); + return fire; } public SubElement getCombustion() { - return getSubElement(COMBUSTION); + return combustion; } public SubElement getLightning() { - return getSubElement(LIGHTNING); + return lightning; } public Element getAir() { - return getElement(AIR); + return air; } public SubElement getFlight() { - return getSubElement(FLIGHT); + return flight; } public SubElement getSpiritual() { - return getSubElement(SPIRITUAL); + return spiritual; } public Element getChi() { - return getElement(CHI); + return chi; } public Element getAvatar() { - return getElement(AVATAR); + return avatar; } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index e85b85cf..b072f20c 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -1,6 +1,9 @@ package com.projectkorra.projectkorra.player; import com.projectkorra.projectkorra.ability.Ability; +import com.projectkorra.projectkorra.ability.ChiAbility; +import com.projectkorra.projectkorra.ability.CoreAbility; +import com.projectkorra.projectkorra.ability.util.PassiveManager; import com.projectkorra.projectkorra.cooldown.CooldownManager; import com.projectkorra.projectkorra.element.Element; import com.projectkorra.projectkorra.element.ElementManager; @@ -24,6 +27,16 @@ public class BendingPlayer private final long firstLogin; private final Set elements; + private final Set toggledElements; + private final String[] abilities; + + private ChiAbility stance; + private boolean permanentlyRemoved; + private boolean toggled; + private boolean tremorSense; + private boolean illumination; + private boolean chiBlocked; + private long slowTime; public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) { @@ -38,6 +51,8 @@ public class BendingPlayer this.firstLogin = firstLogin; this.elements = new HashSet<>(); + this.toggledElements = new HashSet<>(); + this.abilities = new String[9]; } public void addElement(Element element) @@ -116,6 +131,34 @@ public class BendingPlayer return this.elements.contains(elementManager.getSpiritual()); } + public boolean isElementToggled(Element element) + { + return this.toggledElements.contains(element); + } + + public void toggleElement(Element element) + { + if (this.toggledElements.contains(element)) + { + this.toggledElements.remove(element); + } + else + { + this.toggledElements.add(element); + } + } + + public CoreAbility getBoundAbility() + { + return CoreAbility.getAbility(getBoundAbilityName()); + } + + public String getBoundAbilityName() + { + int slot = this.player.getInventory().getHeldItemSlot(); + return this.abilities[slot]; + } + public void addCooldown(Ability ability) { addCooldown(ability, ability.getCooldown()); @@ -161,6 +204,82 @@ public class BendingPlayer cooldownManager.removeCooldown(this.player, abilityName); } + public ChiAbility getStance() + { + return this.stance; + } + + public void setStance(ChiAbility stance) + { + this.stance = stance; + } + + public boolean isPermanentlyRemoved() + { + return this.permanentlyRemoved; + } + + public void setPermanentlyRemoved(boolean permanentlyRemoved) + { + this.permanentlyRemoved = permanentlyRemoved; + } + + public boolean isToggled() + { + return this.toggled; + } + + public void toggleBending() + { + this.toggled = !this.toggled; + PassiveManager.registerPassives(this.player); // TODO redo this passive system + } + + public boolean isTremorSensing() + { + return this.tremorSense; + } + + public void toggleTremorSense() + { + this.tremorSense = !this.tremorSense; + } + + public boolean isIlluminating() + { + return this.illumination; + } + + public void toggleIllumination() + { + this.illumination = !this.illumination; + } + + public boolean isChiBlocked() + { + return this.chiBlocked; + } + + public void blockChi() + { + this.chiBlocked = true; + } + + public void unblockChi() + { + this.chiBlocked = false; + } + + public boolean canBeSlowed() + { + return System.currentTimeMillis() > this.slowTime; + } + + public void slow(long cooldown) + { + this.slowTime = System.currentTimeMillis() + cooldown; + } + public int getId() { return this.playerId; From 7fd3186d40c12602dea07eeb0cf2da8d4cabd9a8 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 16:31:22 +1000 Subject: [PATCH 17/22] Updated conflicting config values --- .../configuration/configs/abilities/air/AirBlastConfig.java | 6 +++--- .../configuration/configs/abilities/air/AirBurstConfig.java | 4 ++-- .../configs/abilities/air/AirSuctionConfig.java | 5 +++-- .../configs/abilities/air/SuffocateConfig.java | 4 ++-- 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBlastConfig.java b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBlastConfig.java index c70855cf..07240eef 100644 --- a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBlastConfig.java +++ b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBlastConfig.java @@ -7,8 +7,8 @@ public class AirBlastConfig extends AbilityConfig { public final long Cooldown = 500; public final int AnimationParticleAmount = 5; public final int SelectionParticleAmount = 5; - public final double PushFactor_Self = 2.5; - public final double PushFactor_Others = 2.5; + public final double PushFactor_Self = 2.0; + public final double PushFactor_Others = 1.6; public final double Speed = 25; public final double Range = 20; public final double SelectionRange = 10; @@ -36,4 +36,4 @@ public class AirBlastConfig extends AbilityConfig { return new String[] { "Abilities", "Air" }; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBurstConfig.java b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBurstConfig.java index fb938b15..f12ec6b2 100644 --- a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBurstConfig.java +++ b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirBurstConfig.java @@ -7,7 +7,7 @@ public class AirBurstConfig extends AbilityConfig { public final long Cooldown = 0; public final long ChargeTime = 1750; public final double FallHeightThreshold = 15; - public final double PushFactor = 2.0; + public final double PushFactor = 2.8; public final double Damage = 0; public final double AnglePhi = 10; public final double AngleTheta = 10; @@ -31,4 +31,4 @@ public class AirBurstConfig extends AbilityConfig { return new String[] { "Abilities", "Air" }; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirSuctionConfig.java b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirSuctionConfig.java index cb2a0bb6..46b9aa60 100644 --- a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirSuctionConfig.java +++ b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/AirSuctionConfig.java @@ -7,7 +7,8 @@ public class AirSuctionConfig extends AbilityConfig { public final long Cooldown = 500; public final int AnimationParticleAmount = 5; public final int SelectionParticleAmount = 5; - public final double PushFactor = 2.5; + public final double PushFactor_Self = 2.0; + public final double PushFactor_Others = 1.3; public final double Speed = 25; public final double Range = 20; public final double SelectionRange = 10; @@ -29,4 +30,4 @@ public class AirSuctionConfig extends AbilityConfig { return new String[] { "Abilities", "Air" }; } -} \ No newline at end of file +} diff --git a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/SuffocateConfig.java b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/SuffocateConfig.java index 6c5a8c95..28c20d85 100644 --- a/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/SuffocateConfig.java +++ b/src/com/projectkorra/projectkorra/configuration/configs/abilities/air/SuffocateConfig.java @@ -4,7 +4,7 @@ import com.projectkorra.projectkorra.configuration.configs.abilities.AbilityConf public class SuffocateConfig extends AbilityConfig { - public final long Cooldown = 0; + public final long Cooldown = 6500; public final boolean RequireConstantAim = true; public final double ConstantAimRadius = 3; public final boolean CanSuffocateUndead = false; @@ -42,4 +42,4 @@ public class SuffocateConfig extends AbilityConfig { return new String[] { "Abilities", "Air" }; } -} \ No newline at end of file +} From 060f3e34b334277b4a56dfcea2e64f20be1e53f7 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 17:21:39 +1000 Subject: [PATCH 18/22] Setup AbilityManager with refactored back-end --- .../projectkorra/ability/AbilityManager.java | 139 ++++++++++++++++++ .../ability/AbilityRepository.java | 113 ++++++++++++++ .../projectkorra/element/ElementManager.java | 98 +++++++++++- .../element/ElementRepository.java | 26 +++- .../projectkorra/module/ModuleManager.java | 3 + .../projectkorra/player/BendingPlayer.java | 42 +++++- 6 files changed, 411 insertions(+), 10 deletions(-) create mode 100644 src/com/projectkorra/projectkorra/ability/AbilityManager.java create mode 100644 src/com/projectkorra/projectkorra/ability/AbilityRepository.java diff --git a/src/com/projectkorra/projectkorra/ability/AbilityManager.java b/src/com/projectkorra/projectkorra/ability/AbilityManager.java new file mode 100644 index 00000000..7884cbca --- /dev/null +++ b/src/com/projectkorra/projectkorra/ability/AbilityManager.java @@ -0,0 +1,139 @@ +package com.projectkorra.projectkorra.ability; + +import com.projectkorra.projectkorra.GeneralMethods; +import com.projectkorra.projectkorra.ability.util.MultiAbilityManager; +import com.projectkorra.projectkorra.module.DatabaseModule; +import com.projectkorra.projectkorra.module.ModuleManager; +import com.projectkorra.projectkorra.player.BendingPlayer; +import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; +import com.projectkorra.projectkorra.player.BendingPlayerManager; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; + +import java.sql.SQLException; + +public class AbilityManager extends DatabaseModule +{ + private final BendingPlayerManager _bendingPlayerManager; + + private AbilityManager() + { + super("Ability", new AbilityRepository()); + + _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + + runAsync(() -> + { + try + { + getRepository().createTables(); + } + catch (SQLException e) + { + e.printStackTrace(); + } + + runSync(() -> + { + log("Created database tables."); + }); + }); + } + + @EventHandler + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) + { + BendingPlayer bendingPlayer = event.getBendingPlayer(); + + runAsync(() -> + { + try + { + String[] abilities = getRepository().selectPlayerAbilities(bendingPlayer.getId()); + + bendingPlayer.setAbilities(abilities); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + + public boolean bindAbility(Player player, String abilityName, int slot) + { + // TODO Call event, let MultiAbilityManager cancel + if (MultiAbilityManager.playerAbilities.containsKey(player)) + { + GeneralMethods.sendBrandingMessage(player, ChatColor.RED + "You can't edit your binds right now!"); + return false; + } + + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + bendingPlayer.setAbility(slot, abilityName); + + runAsync(() -> + { + try + { + getRepository().insertPlayerAbility(bendingPlayer.getId(), abilityName, slot); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + + return true; + } + + public boolean unbindAbility(Player player, int slot) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + String abilityName = bendingPlayer.getAbility(slot); + + if (abilityName == null) + { + player.sendMessage("No ability bound"); + return false; + } + + bendingPlayer.setAbility(slot, null); + + runAsync(() -> + { + try + { + getRepository().deletePlayerAbility(bendingPlayer.getId(), abilityName); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + + return true; + } + + public void clearBinds(Player player) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + bendingPlayer.setAbilities(new String[9]); + + runAsync(() -> + { + try + { + getRepository().deletePlayerAbilities(bendingPlayer.getId()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } +} diff --git a/src/com/projectkorra/projectkorra/ability/AbilityRepository.java b/src/com/projectkorra/projectkorra/ability/AbilityRepository.java new file mode 100644 index 00000000..347fee74 --- /dev/null +++ b/src/com/projectkorra/projectkorra/ability/AbilityRepository.java @@ -0,0 +1,113 @@ +package com.projectkorra.projectkorra.ability; + +import com.projectkorra.projectkorra.database.DatabaseQuery; +import com.projectkorra.projectkorra.database.DatabaseRepository; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class AbilityRepository extends DatabaseRepository +{ + private static final DatabaseQuery CREATE_TABLE_PLAYER_ABILITIES = DatabaseQuery.newBuilder() + .mysql("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name), INDEX player_index (player_id), INDEX ability_index (ability_name));") + .sqlite("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name)); CREATE INDEX player_index ON pk_player_abilities (player_id); CREATE INDEX ability_index ON pk_player_abilities (ability_name);") + .build(); + + private static final DatabaseQuery SELECT_PLAYER_ABILITIES = DatabaseQuery.newBuilder() + .query("SELECT ability_name, slot FROM pk_player_abilities WHERE player_id = ?;") + .build(); + + private static final DatabaseQuery INSERT_PLAYER_ABILITY = DatabaseQuery.newBuilder() + .query("INSERT INTO pk_player_abilities VALUES (?, ?, ?);") + .build(); + + private static final DatabaseQuery DELETE_PLAYER_ABILITIES = DatabaseQuery.newBuilder() + .query("DELETE FROM pk_player_abilities WHERE player_id = ?") + .build(); + + private static final DatabaseQuery DELETE_PLAYER_ABILITY = DatabaseQuery.newBuilder() + .query("DELETE FROM pk_player_abilities WHERE player_id = ? AND ability_name = ?;") + .build(); + + protected void createTables() throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_PLAYER_ABILITIES.getQuery())) + { + statement.executeUpdate(); + } + } + + protected String[] selectPlayerAbilities(int playerId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ABILITIES.getQuery())) + { + statement.setInt(1, playerId); + + String[] abilities = new String[9]; + + try (ResultSet rs = statement.executeQuery()) + { + while (rs.next()) + { + String abilityName = rs.getString("ability_name"); + int slot = rs.getInt("slot"); + + if (slot < 0 || slot >= abilities.length) + { + // TODO Log illegal slot + continue; + } + + abilities[slot] = abilityName; + } + + return abilities; + } + } + } + + protected void insertPlayerAbility(int playerId, String abilityName, int slot) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ABILITY.getQuery())) + { + statement.setInt(1, playerId); + statement.setString(2, abilityName); + statement.setInt(3, slot); + + statement.executeUpdate(); + } + } + + protected void deletePlayerAbilities(int playerId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITIES.getQuery())) + { + statement.setInt(1, playerId); + + statement.executeUpdate(); + } + } + + protected void deletePlayerAbility(int playerId, String abilityName) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITY.getQuery())) + { + statement.setInt(1, playerId); + statement.setString(2, abilityName); + + statement.executeUpdate(); + } + } +} diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java index 3d3efd4e..a5ba11b5 100644 --- a/src/com/projectkorra/projectkorra/element/ElementManager.java +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -2,8 +2,10 @@ package com.projectkorra.projectkorra.element; import com.google.common.base.Preconditions; import com.projectkorra.projectkorra.module.DatabaseModule; +import com.projectkorra.projectkorra.module.ModuleManager; import com.projectkorra.projectkorra.player.BendingPlayer; import com.projectkorra.projectkorra.player.BendingPlayerLoadedEvent; +import com.projectkorra.projectkorra.player.BendingPlayerManager; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -23,7 +25,10 @@ public class ElementManager extends DatabaseModule private static final String COMBUSTION = "combustion", LIGHTNING = "lightning"; private static final String FLIGHT = "flight", SPIRITUAL = "spiritual"; + private final BendingPlayerManager _bendingPlayerManager; + private final Map _elements = new HashMap<>(); + private final Map _names = new HashMap<>(); private final String _nameRegex = "[a-zA-Z]+"; @@ -37,6 +42,8 @@ public class ElementManager extends DatabaseModule { super("Element", new ElementRepository()); + _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + runAsync(() -> { try @@ -87,7 +94,6 @@ public class ElementManager extends DatabaseModule @EventHandler public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) { - Player player = event.getPlayer(); BendingPlayer bendingPlayer = event.getBendingPlayer(); runAsync(() -> @@ -107,6 +113,94 @@ public class ElementManager extends DatabaseModule }); } + public boolean addElement(Player player, Element element) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + if (!bendingPlayer.addElement(element)) + { + return false; + } + + runAsync(() -> + { + try + { + getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + + return true; + } + + public void setElement(Player player, Element element) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + bendingPlayer.clearElements(); + bendingPlayer.addElement(element); + + runAsync(() -> + { + try + { + getRepository().deletePlayerElements(bendingPlayer.getId()); + getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + + public boolean removeElement(Player player, Element element) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + if (!bendingPlayer.removeElement(element)) + { + return false; + } + + runAsync(() -> + { + try + { + getRepository().deletePlayerElement(bendingPlayer.getId(), element.getId()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + + return true; + } + + public void clearElements(Player player) + { + BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + + bendingPlayer.clearElements(); + + runAsync(() -> + { + try + { + getRepository().deletePlayerElements(bendingPlayer.getId()); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); + } + private Element addElement(String elementName, String displayName, ChatColor color) { int elementId = registerElement(elementName); @@ -114,6 +208,7 @@ public class ElementManager extends DatabaseModule Element element = new Element(elementId, elementName, displayName, color); _elements.put(elementId, element); + _names.put(elementName, element); return element; } @@ -125,6 +220,7 @@ public class ElementManager extends DatabaseModule SubElement element = new SubElement(elementId, elementName, displayName, color, parent); _elements.put(elementId, element); + _names.put(elementName, element); return element; } diff --git a/src/com/projectkorra/projectkorra/element/ElementRepository.java b/src/com/projectkorra/projectkorra/element/ElementRepository.java index b658381a..1d592389 100644 --- a/src/com/projectkorra/projectkorra/element/ElementRepository.java +++ b/src/com/projectkorra/projectkorra/element/ElementRepository.java @@ -18,7 +18,7 @@ public class ElementRepository extends DatabaseRepository .sqlite("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTOINCREMENT, element_name VARCHAR(50) NOT NULL); CREATE UNIQUE INDEX name_index ON pk_elements (element_name);") .build(); private static final DatabaseQuery CREATE_TABLE_PLAYER_ELEMENTS = DatabaseQuery.newBuilder() - .mysql("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)), INDEX player_index (player_id), INDEX element_index (element_id));") + .mysql("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id), INDEX player_index (player_id), INDEX element_index (element_id));") .sqlite("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)); CREATE INDEX player_index ON pk_player_elements (player_id); CREATE INDEX element_index ON pk_player_elements (element_id);") .build(); @@ -38,6 +38,10 @@ public class ElementRepository extends DatabaseRepository .query("INSERT INTO pk_player_elements VALUES (?, ?);") .build(); + private static final DatabaseQuery DELETE_PLAYER_ELEMENTS = DatabaseQuery.newBuilder() + .query("DELETE FROM pk_player_elements WHERE player_id = ?;") + .build(); + private static final DatabaseQuery DELETE_PLAYER_ELEMENT = DatabaseQuery.newBuilder() .query("DELETE FROM pk_player_elements WHERE player_id = ? AND element_id = ?;") .build(); @@ -47,10 +51,10 @@ public class ElementRepository extends DatabaseRepository Connection connection = getDatabase().getConnection(); try - ( - PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); - PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery()) - ) + ( + PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); + PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery()) + ) { elements.executeUpdate(); playerElements.executeUpdate(); @@ -131,6 +135,18 @@ public class ElementRepository extends DatabaseRepository } } + protected void deletePlayerElements(int playerId) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENTS.getQuery())) + { + statement.setInt(1, playerId); + + statement.executeUpdate(); + } + } + protected void deletePlayerElement(int playerId, int elementId) throws SQLException { Connection connection = getDatabase().getConnection(); diff --git a/src/com/projectkorra/projectkorra/module/ModuleManager.java b/src/com/projectkorra/projectkorra/module/ModuleManager.java index 6f867f92..f8f0dd97 100644 --- a/src/com/projectkorra/projectkorra/module/ModuleManager.java +++ b/src/com/projectkorra/projectkorra/module/ModuleManager.java @@ -1,6 +1,7 @@ package com.projectkorra.projectkorra.module; import com.google.common.base.Preconditions; +import com.projectkorra.projectkorra.ability.AbilityManager; import com.projectkorra.projectkorra.cooldown.CooldownManager; import com.projectkorra.projectkorra.database.DatabaseManager; import com.projectkorra.projectkorra.element.ElementManager; @@ -64,6 +65,7 @@ public class ModuleManager { registerModule(DatabaseManager.class); registerModule(BendingPlayerManager.class); registerModule(ElementManager.class); + registerModule(AbilityManager.class); registerModule(CooldownManager.class); } @@ -72,6 +74,7 @@ public class ModuleManager { */ public static void shutdown() { registerModule(CooldownManager.class); + registerModule(AbilityManager.class); registerModule(ElementManager.class); getModule(BendingPlayerManager.class).disable(); getModule(DatabaseManager.class).disable(); diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index b072f20c..669be722 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -1,6 +1,7 @@ package com.projectkorra.projectkorra.player; import com.projectkorra.projectkorra.ability.Ability; +import com.projectkorra.projectkorra.ability.AbilityManager; import com.projectkorra.projectkorra.ability.ChiAbility; import com.projectkorra.projectkorra.ability.CoreAbility; import com.projectkorra.projectkorra.ability.util.PassiveManager; @@ -10,7 +11,9 @@ import com.projectkorra.projectkorra.element.ElementManager; import com.projectkorra.projectkorra.module.ModuleManager; import org.bukkit.entity.Player; +import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.UUID; @@ -18,6 +21,7 @@ public class BendingPlayer { private final BendingPlayerManager manager; private final ElementManager elementManager; + private final AbilityManager abilityManager; private final CooldownManager cooldownManager; private final int playerId; @@ -42,6 +46,7 @@ public class BendingPlayer { this.manager = ModuleManager.getModule(BendingPlayerManager.class); this.elementManager = ModuleManager.getModule(ElementManager.class); + this.abilityManager = ModuleManager.getModule(AbilityManager.class); this.cooldownManager = ModuleManager.getModule(CooldownManager.class); this.playerId = playerId; @@ -55,15 +60,24 @@ public class BendingPlayer this.abilities = new String[9]; } - public void addElement(Element element) + public Set getElements() { - this.elements.add(element); + return new HashSet<>(this.elements); } - public void setElement(Element element) + public boolean addElement(Element element) + { + return this.elements.add(element); + } + + public boolean removeElement(Element element) + { + return this.elements.remove(element); + } + + public void clearElements() { this.elements.clear(); - this.elements.add(element); } public boolean hasElement(Element element) @@ -159,6 +173,26 @@ public class BendingPlayer return this.abilities[slot]; } + public String getAbility(int slot) + { + return this.abilities[slot]; + } + + public List getAbilities() + { + return Arrays.asList(this.abilities); + } + + public void setAbilities(String[] abilities) + { + System.arraycopy(abilities, 0, this.abilities, 0, 9); + } + + public void setAbility(int slot, String abilityName) + { + this.abilities[slot] = abilityName; + } + public void addCooldown(Ability ability) { addCooldown(ability, ability.getCooldown()); From 6a5c963ec2cd4e9033a49c4e3eff4febc27c4936 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 17:29:22 +1000 Subject: [PATCH 19/22] Use new configuration system --- .../projectkorra/database/DatabaseConfig.java | 16 +++++++++++++++- .../projectkorra/database/DatabaseManager.java | 4 ++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/com/projectkorra/projectkorra/database/DatabaseConfig.java b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java index 8c6504d4..c6c7b0ca 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseConfig.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java @@ -1,6 +1,8 @@ package com.projectkorra.projectkorra.database; -public class DatabaseConfig +import com.projectkorra.projectkorra.configuration.Config; + +public class DatabaseConfig implements Config { public final DatabaseManager.Engine Engine = DatabaseManager.Engine.SQLITE; @@ -11,4 +13,16 @@ public class DatabaseConfig public final String MySQL_DatabaseName = "projectkorra"; public final String MySQL_Username = "root"; public final String MySQL_Password = "password"; + + @Override + public String getName() + { + return "Database"; + } + + @Override + public String[] getParents() + { + return new String[0]; + } } diff --git a/src/com/projectkorra/projectkorra/database/DatabaseManager.java b/src/com/projectkorra/projectkorra/database/DatabaseManager.java index fddcac07..a13df835 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseManager.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseManager.java @@ -1,5 +1,6 @@ package com.projectkorra.projectkorra.database; +import com.projectkorra.projectkorra.configuration.ConfigManager; import com.projectkorra.projectkorra.database.engine.MySQLDatabase; import com.projectkorra.projectkorra.database.engine.SQLDatabase; import com.projectkorra.projectkorra.database.engine.SQLiteDatabase; @@ -16,8 +17,7 @@ public class DatabaseManager extends Module { super("Database"); - // TODO Pull from new ConfigManager - _config = new DatabaseConfig(); + _config = ConfigManager.getConfig(DatabaseConfig.class); switch (_config.Engine) { From 29f6056b1cd8ada93003f4bc06f6ab49fd46a231 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 19:05:11 +1000 Subject: [PATCH 20/22] Read and write permaremoved to/from database, added PlayerBindAbilityEvent --- .../projectkorra/ability/AbilityManager.java | 14 ++++- .../ability/PlayerBindAbilityEvent.java | 61 +++++++++++++++++++ .../ability/util/MultiAbilityManager.java | 18 +++++- .../projectkorra/player/BendingPlayer.java | 10 +-- .../player/BendingPlayerManager.java | 41 ++++++++++++- .../player/BendingPlayerRepository.java | 38 +++++++++--- 6 files changed, 162 insertions(+), 20 deletions(-) create mode 100644 src/com/projectkorra/projectkorra/ability/PlayerBindAbilityEvent.java diff --git a/src/com/projectkorra/projectkorra/ability/AbilityManager.java b/src/com/projectkorra/projectkorra/ability/AbilityManager.java index 7884cbca..2092f533 100644 --- a/src/com/projectkorra/projectkorra/ability/AbilityManager.java +++ b/src/com/projectkorra/projectkorra/ability/AbilityManager.java @@ -63,10 +63,18 @@ public class AbilityManager extends DatabaseModule public boolean bindAbility(Player player, String abilityName, int slot) { - // TODO Call event, let MultiAbilityManager cancel - if (MultiAbilityManager.playerAbilities.containsKey(player)) + PlayerBindAbilityEvent playerBindAbilityEvent = new PlayerBindAbilityEvent(player, abilityName); + getPlugin().getServer().getPluginManager().callEvent(playerBindAbilityEvent); + + if (playerBindAbilityEvent.isCancelled()) { - GeneralMethods.sendBrandingMessage(player, ChatColor.RED + "You can't edit your binds right now!"); + String cancelMessage = playerBindAbilityEvent.getCancelMessage(); + + if (cancelMessage != null) + { + GeneralMethods.sendBrandingMessage(player, cancelMessage); + } + return false; } diff --git a/src/com/projectkorra/projectkorra/ability/PlayerBindAbilityEvent.java b/src/com/projectkorra/projectkorra/ability/PlayerBindAbilityEvent.java new file mode 100644 index 00000000..0317ee46 --- /dev/null +++ b/src/com/projectkorra/projectkorra/ability/PlayerBindAbilityEvent.java @@ -0,0 +1,61 @@ +package com.projectkorra.projectkorra.ability; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class PlayerBindAbilityEvent extends PlayerEvent implements Cancellable +{ + private static final HandlerList HANDLER_LIST = new HandlerList(); + + private final String abilityName; + + private boolean cancelled; + private String cancelMessage; + + public PlayerBindAbilityEvent(Player player, String abilityName) + { + super(player); + + this.abilityName = abilityName; + } + + public String getAbilityName() + { + return this.abilityName; + } + + @Override + public boolean isCancelled() + { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) + { + this.cancelled = cancelled; + } + + public String getCancelMessage() + { + return this.cancelMessage; + } + + public void setCancelMessage(String cancelMessage) + { + this.cancelMessage = cancelMessage; + } + + @Override + public HandlerList getHandlers() + { + return HANDLER_LIST; + } + + public static HandlerList getHandlerList() + { + return HANDLER_LIST; + } +} diff --git a/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java b/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java index 1317c01c..38943ff7 100644 --- a/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java +++ b/src/com/projectkorra/projectkorra/ability/util/MultiAbilityManager.java @@ -6,9 +6,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import com.projectkorra.projectkorra.ability.PlayerBindAbilityEvent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; import org.bukkit.scheduler.BukkitRunnable; import com.projectkorra.projectkorra.BendingPlayer; @@ -17,7 +20,7 @@ import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ProjectKorra; import com.projectkorra.projectkorra.event.PlayerBindChangeEvent; -public class MultiAbilityManager { +public class MultiAbilityManager implements Listener { public static Map playerAbilities = new ConcurrentHashMap<>(); public static Map playerSlot = new ConcurrentHashMap<>(); @@ -34,6 +37,19 @@ public class MultiAbilityManager { waterArms.add(new MultiAbilityInfoSub("Spear", Element.ICE)); multiAbilityList.add(new MultiAbilityInfo("WaterArms", waterArms)); manage(); + + // TODO Properly set this up as a Module + ProjectKorra.plugin.getServer().getPluginManager().registerEvents(this, ProjectKorra.plugin); + } + + @EventHandler + public void onPlayerBindAbility(PlayerBindAbilityEvent event) + { + if (playerAbilities.containsKey(event.getPlayer())) + { + event.setCancelled(true); + event.setCancelMessage(ChatColor.RED + "You can't edit your binds right now!"); + } } /** diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index 669be722..be7d69a4 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -35,7 +35,7 @@ public class BendingPlayer private final String[] abilities; private ChiAbility stance; - private boolean permanentlyRemoved; + private boolean bendingRemoved; private boolean toggled; private boolean tremorSense; private boolean illumination; @@ -248,14 +248,14 @@ public class BendingPlayer this.stance = stance; } - public boolean isPermanentlyRemoved() + public boolean isBendingRemoved() { - return this.permanentlyRemoved; + return this.bendingRemoved; } - public void setPermanentlyRemoved(boolean permanentlyRemoved) + protected void setBendingRemoved(boolean bendingRemoved) { - this.permanentlyRemoved = permanentlyRemoved; + this.bendingRemoved = bendingRemoved; } public boolean isToggled() diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java index 2b1e5c43..b698a399 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -62,10 +62,45 @@ public class BendingPlayerManager extends DatabaseModule + { + try + { + getRepository().updateBendingRemoved(bendingPlayer); + } + catch (SQLException e) + { + e.printStackTrace(); + } + }); } private void loadBendingPlayer(Player player) diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java index deea5133..cb760b64 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java @@ -15,22 +15,26 @@ import java.util.UUID; public class BendingPlayerRepository extends DatabaseRepository { private static final DatabaseQuery CREATE_TABLE_BENDING_PLAYERS = DatabaseQuery.newBuilder() - .mysql("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTO_INCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, INDEX uuid_index (uuid));") - .sqlite("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL); CREATE INDEX uuid_index ON pk_bending_players (uuid);") + .mysql("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTO_INCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN, INDEX uuid_index (uuid));") + .sqlite("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN); CREATE INDEX uuid_index ON pk_bending_players (uuid);") .build(); private static final DatabaseQuery SELECT_BENDING_PLAYER = DatabaseQuery.newBuilder() - .query("SELECT player_id, player_name, first_login FROM pk_bending_players WHERE uuid = ?;") + .query("SELECT player_id, player_name, first_login, bending_removed FROM pk_bending_players WHERE uuid = ?;") .build(); private static final DatabaseQuery INSERT_BENDING_PLAYER = DatabaseQuery.newBuilder() .query("INSERT INTO pk_bending_players (uuid, player_name, first_login) VALUES (?, ?, ?);") .build(); - private static final DatabaseQuery UPDATE_BENDING_PLAYER = DatabaseQuery.newBuilder() + private static final DatabaseQuery UPDATE_PLAYER_NAME = DatabaseQuery.newBuilder() .query("UPDATE pk_bending_players SET player_name = ? WHERE player_id = ?;") .build(); + private static final DatabaseQuery UPDATE_BENDING_REMOVED = DatabaseQuery.newBuilder() + .query("UPDATE pk_bending_players SET bending_removed = ? WHERE player_id = ?;") + .build(); + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); @@ -62,13 +66,18 @@ public class BendingPlayerRepository extends DatabaseRepository int playerId = rs.getInt("player_id"); String playerName = rs.getString("player_name"); long firstLogin = rs.getLong("first_login"); + boolean bendingRemoved = rs.getBoolean("bending_removed"); if (!player.getName().equals(playerName)) { - updatePlayer(playerId, player.getName()); + updatePlayerName(playerId, player.getName()); } - return new BendingPlayer(playerId, uuid, playerName, firstLogin); + BendingPlayer bendingPlayer = new BendingPlayer(playerId, uuid, playerName, firstLogin); + + bendingPlayer.setBendingRemoved(bendingRemoved); + + return bendingPlayer; } } } @@ -99,11 +108,11 @@ public class BendingPlayerRepository extends DatabaseRepository } } - protected void updatePlayer(int playerId, String playerName) throws SQLException + protected void updatePlayerName(int playerId, String playerName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_PLAYER.getQuery())) + try (PreparedStatement statement = connection.prepareStatement(UPDATE_PLAYER_NAME.getQuery())) { statement.setInt(1, playerId); statement.setString(2, playerName); @@ -111,4 +120,17 @@ public class BendingPlayerRepository extends DatabaseRepository statement.executeUpdate(); } } + + protected void updateBendingRemoved(BendingPlayer bendingPlayer) throws SQLException + { + Connection connection = getDatabase().getConnection(); + + try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_REMOVED.getQuery())) + { + statement.setInt(1, bendingPlayer.getId()); + statement.setBoolean(2, bendingPlayer.isBendingRemoved()); + + statement.executeUpdate(); + } + } } From 00093af01b9f29817b3cbccbef63ff226d479444 Mon Sep 17 00:00:00 2001 From: jayoevans Date: Wed, 23 Oct 2019 19:25:09 +1000 Subject: [PATCH 21/22] Cache bending players for 30 seconds after disconnect --- .../player/BendingPlayerManager.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java index b698a399..92e772c0 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -11,13 +11,18 @@ import org.bukkit.event.player.PlayerQuitEvent; import java.sql.SQLException; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.UUID; public class BendingPlayerManager extends DatabaseModule { private final Map _players = new HashMap<>(); + private final Set _disconnected = new HashSet<>(); + private final long _databaseSyncInterval = 20 * 30; + private BendingPlayerManager() { super("Bending Player", new BendingPlayerRepository()); @@ -38,11 +43,22 @@ public class BendingPlayerManager extends DatabaseModule + { + _disconnected.forEach(_players::remove); + _disconnected.clear(); + }, _databaseSyncInterval, _databaseSyncInterval); } @EventHandler(priority = EventPriority.LOWEST) public void onLogin(PlayerLoginEvent event) { + if (_disconnected.remove(event.getPlayer().getUniqueId())) + { + return; + } + runAsync(() -> { loadBendingPlayer(event.getPlayer()); @@ -52,8 +68,7 @@ public class BendingPlayerManager extends DatabaseModule Date: Thu, 24 Oct 2019 13:39:00 +1000 Subject: [PATCH 22/22] Reformatted to follow PK standards --- .../projectkorra/ability/AbilityManager.java | 102 +++---- .../ability/AbilityRepository.java | 43 +-- .../cooldown/CooldownManager.java | 168 +++++------- .../cooldown/CooldownRepository.java | 34 +-- .../projectkorra/database/DatabaseConfig.java | 10 +- .../database/DatabaseManager.java | 57 ++-- .../projectkorra/database/DatabaseQuery.java | 62 ++--- .../database/DatabaseRepository.java | 12 +- .../database/engine/MySQLDatabase.java | 26 +- .../database/engine/SQLDatabase.java | 4 +- .../database/engine/SQLiteDatabase.java | 69 ++--- .../projectkorra/element/Element.java | 48 ++-- .../projectkorra/element/ElementManager.java | 258 +++++++----------- .../element/ElementRepository.java | 72 ++--- .../projectkorra/element/SubElement.java | 16 +- .../projectkorra/module/DatabaseModule.java | 10 +- .../projectkorra/module/Module.java | 46 ++-- .../projectkorra/module/ModuleManager.java | 1 - .../projectkorra/player/BendingPlayer.java | 201 +++++--------- .../player/BendingPlayerLoadedEvent.java | 22 +- .../player/BendingPlayerManager.java | 109 +++----- .../player/BendingPlayerRepository.java | 52 ++-- 22 files changed, 537 insertions(+), 885 deletions(-) diff --git a/src/com/projectkorra/projectkorra/ability/AbilityManager.java b/src/com/projectkorra/projectkorra/ability/AbilityManager.java index 2092f533..4e43601c 100644 --- a/src/com/projectkorra/projectkorra/ability/AbilityManager.java +++ b/src/com/projectkorra/projectkorra/ability/AbilityManager.java @@ -2,6 +2,7 @@ package com.projectkorra.projectkorra.ability; import com.projectkorra.projectkorra.GeneralMethods; import com.projectkorra.projectkorra.ability.util.MultiAbilityManager; +import com.projectkorra.projectkorra.firebending.FireBlast; import com.projectkorra.projectkorra.module.DatabaseModule; import com.projectkorra.projectkorra.module.ModuleManager; import com.projectkorra.projectkorra.player.BendingPlayer; @@ -13,83 +14,75 @@ import org.bukkit.event.EventHandler; import java.sql.SQLException; -public class AbilityManager extends DatabaseModule -{ - private final BendingPlayerManager _bendingPlayerManager; +public class AbilityManager extends DatabaseModule { - private AbilityManager() - { + private final BendingPlayerManager bendingPlayerManager; + + private AbilityManager() { super("Ability", new AbilityRepository()); - _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().createTables(); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } - runSync(() -> - { + runSync(() -> { log("Created database tables."); }); }); + + registerAbilities(); + } + + private void registerAbilities() { + registerAbility(FireBlast.class); + } + + private void registerAbility(Class abilityClass) { + // TODO } @EventHandler - public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) - { + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) { BendingPlayer bendingPlayer = event.getBendingPlayer(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { String[] abilities = getRepository().selectPlayerAbilities(bendingPlayer.getId()); bendingPlayer.setAbilities(abilities); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } - public boolean bindAbility(Player player, String abilityName, int slot) - { + public boolean bindAbility(Player player, String abilityName, int slot) { PlayerBindAbilityEvent playerBindAbilityEvent = new PlayerBindAbilityEvent(player, abilityName); getPlugin().getServer().getPluginManager().callEvent(playerBindAbilityEvent); - if (playerBindAbilityEvent.isCancelled()) - { + if (playerBindAbilityEvent.isCancelled()) { String cancelMessage = playerBindAbilityEvent.getCancelMessage(); - if (cancelMessage != null) - { + if (cancelMessage != null) { GeneralMethods.sendBrandingMessage(player, cancelMessage); } return false; } - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); bendingPlayer.setAbility(slot, abilityName); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().insertPlayerAbility(bendingPlayer.getId(), abilityName, slot); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); @@ -97,28 +90,22 @@ public class AbilityManager extends DatabaseModule return true; } - public boolean unbindAbility(Player player, int slot) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public boolean unbindAbility(Player player, int slot) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); String abilityName = bendingPlayer.getAbility(slot); - if (abilityName == null) - { + if (abilityName == null) { player.sendMessage("No ability bound"); return false; } bendingPlayer.setAbility(slot, null); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deletePlayerAbility(bendingPlayer.getId(), abilityName); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); @@ -126,20 +113,15 @@ public class AbilityManager extends DatabaseModule return true; } - public void clearBinds(Player player) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public void clearBinds(Player player) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); bendingPlayer.setAbilities(new String[9]); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deletePlayerAbilities(bendingPlayer.getId()); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); diff --git a/src/com/projectkorra/projectkorra/ability/AbilityRepository.java b/src/com/projectkorra/projectkorra/ability/AbilityRepository.java index 347fee74..ad4ca5b2 100644 --- a/src/com/projectkorra/projectkorra/ability/AbilityRepository.java +++ b/src/com/projectkorra/projectkorra/ability/AbilityRepository.java @@ -8,8 +8,8 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -public class AbilityRepository extends DatabaseRepository -{ +public class AbilityRepository extends DatabaseRepository { + private static final DatabaseQuery CREATE_TABLE_PLAYER_ABILITIES = DatabaseQuery.newBuilder() .mysql("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name), INDEX player_index (player_id), INDEX ability_index (ability_name));") .sqlite("CREATE TABLE IF NOT EXISTS pk_player_abilities (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(50) NOT NULL, slot TINYINT NOT NULL, PRIMARY KEY (player_id, ability_name)); CREATE INDEX player_index ON pk_player_abilities (player_id); CREATE INDEX ability_index ON pk_player_abilities (ability_name);") @@ -31,35 +31,28 @@ public class AbilityRepository extends DatabaseRepository .query("DELETE FROM pk_player_abilities WHERE player_id = ? AND ability_name = ?;") .build(); - protected void createTables() throws SQLException - { + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_PLAYER_ABILITIES.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_PLAYER_ABILITIES.getQuery())) { statement.executeUpdate(); } } - protected String[] selectPlayerAbilities(int playerId) throws SQLException - { + protected String[] selectPlayerAbilities(int playerId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ABILITIES.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ABILITIES.getQuery())) { statement.setInt(1, playerId); String[] abilities = new String[9]; - try (ResultSet rs = statement.executeQuery()) - { - while (rs.next()) - { + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { String abilityName = rs.getString("ability_name"); int slot = rs.getInt("slot"); - if (slot < 0 || slot >= abilities.length) - { + if (slot < 0 || slot >= abilities.length) { // TODO Log illegal slot continue; } @@ -72,12 +65,10 @@ public class AbilityRepository extends DatabaseRepository } } - protected void insertPlayerAbility(int playerId, String abilityName, int slot) throws SQLException - { + protected void insertPlayerAbility(int playerId, String abilityName, int slot) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ABILITY.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ABILITY.getQuery())) { statement.setInt(1, playerId); statement.setString(2, abilityName); statement.setInt(3, slot); @@ -86,24 +77,20 @@ public class AbilityRepository extends DatabaseRepository } } - protected void deletePlayerAbilities(int playerId) throws SQLException - { + protected void deletePlayerAbilities(int playerId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITIES.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITIES.getQuery())) { statement.setInt(1, playerId); statement.executeUpdate(); } } - protected void deletePlayerAbility(int playerId, String abilityName) throws SQLException - { + protected void deletePlayerAbility(int playerId, String abilityName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITY.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ABILITY.getQuery())) { statement.setInt(1, playerId); statement.setString(2, abilityName); diff --git a/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java index cd2c79d2..bbd93822 100644 --- a/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java +++ b/src/com/projectkorra/projectkorra/cooldown/CooldownManager.java @@ -18,63 +18,49 @@ import java.util.PriorityQueue; import java.util.UUID; import java.util.function.Function; -public class CooldownManager extends DatabaseModule -{ - private final BendingPlayerManager _bendingPlayerManager; +public class CooldownManager extends DatabaseModule { - private final Map> _cooldownMap = new HashMap<>(); - private final Map> _cooldownQueue = new HashMap<>(); + private final BendingPlayerManager bendingPlayerManager; - private final Function> _queueFunction = uuid -> new PriorityQueue<>(Comparator.comparing(cooldown -> cooldown.ExpireTime)); + private final Map> cooldownMap = new HashMap<>(); + private final Map> cooldownQueue = new HashMap<>(); - private CooldownManager() - { + private final Function> queueFunction = uuid -> new PriorityQueue<>(Comparator.comparing(cooldown -> cooldown.ExpireTime)); + + private CooldownManager() { super("Cooldown", new CooldownRepository()); - _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().createTables(); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); - runTimer(() -> - { - _cooldownQueue.forEach((uuid, cooldowns) -> - { + runTimer(() -> { + this.cooldownQueue.forEach((uuid, cooldowns) -> { long currentTime = System.currentTimeMillis(); - while (!cooldowns.isEmpty()) - { + while (!cooldowns.isEmpty()) { Cooldown cooldown = cooldowns.peek(); - if (currentTime < cooldown.ExpireTime) - { + if (currentTime < cooldown.ExpireTime) { break; } - _cooldownMap.get(uuid).remove(cooldown.AbilityName); + this.cooldownMap.get(uuid).remove(cooldown.AbilityName); cooldowns.poll(); - if (cooldown.Permanent) - { - int playerId = _bendingPlayerManager.getBendingPlayer(uuid).getId(); + if (cooldown.Permanent) { + int playerId = this.bendingPlayerManager.getBendingPlayer(uuid).getId(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deleteCooldown(playerId, cooldown.AbilityName); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); @@ -82,156 +68,126 @@ public class CooldownManager extends DatabaseModule } }); - _cooldownMap.values().removeIf(Map::isEmpty); - _cooldownQueue.values().removeIf(PriorityQueue::isEmpty); + this.cooldownMap.values().removeIf(Map::isEmpty); + this.cooldownQueue.values().removeIf(PriorityQueue::isEmpty); }, 1, 1); } @EventHandler - public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) - { + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) { Player player = event.getPlayer(); BendingPlayer bendingPlayer = event.getBendingPlayer(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { Map cooldowns = getRepository().selectCooldowns(bendingPlayer.getId()); - _cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).putAll(cooldowns); - _cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).addAll(cooldowns.values()); - } - catch (SQLException e) - { + this.cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).putAll(cooldowns); + this.cooldownQueue.computeIfAbsent(player.getUniqueId(), queueFunction).addAll(cooldowns.values()); + } catch (SQLException e) { e.printStackTrace(); } }); } @EventHandler - public void onQuit(PlayerQuitEvent event) - { - _cooldownMap.remove(event.getPlayer().getUniqueId()); - _cooldownQueue.remove(event.getPlayer().getUniqueId()); + public void onQuit(PlayerQuitEvent event) { + this.cooldownMap.remove(event.getPlayer().getUniqueId()); + this.cooldownQueue.remove(event.getPlayer().getUniqueId()); } - public void addCooldown(Player player, String abilityName, long duration, boolean permanent) - { - if (duration <= 0) - { + public void addCooldown(Player player, String abilityName, long duration, boolean permanent) { + if (duration <= 0) { return; } PlayerCooldownChangeEvent event = new PlayerCooldownChangeEvent(player, abilityName, duration, PlayerCooldownChangeEvent.Result.ADDED); getPlugin().getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) - { + if (event.isCancelled()) { return; } long expireTime = System.currentTimeMillis() + duration; Cooldown cooldown = new Cooldown(abilityName, expireTime, permanent); - _cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).put(abilityName, cooldown); - _cooldownQueue.computeIfAbsent(player.getUniqueId(), _queueFunction).add(cooldown); + this.cooldownMap.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>()).put(abilityName, cooldown); + this.cooldownQueue.computeIfAbsent(player.getUniqueId(), queueFunction).add(cooldown); - if (permanent) - { - int playerId = _bendingPlayerManager.getBendingPlayer(player).getId(); + if (permanent) { + int playerId = this.bendingPlayerManager.getBendingPlayer(player).getId(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().insertCooldown(playerId, abilityName, expireTime); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } } - public long getCooldown(Player player, String abilityName) - { - Map cooldowns = _cooldownMap.get(player.getUniqueId()); + public long getCooldown(Player player, String abilityName) { + Map cooldowns = this.cooldownMap.get(player.getUniqueId()); - if (cooldowns != null && cooldowns.containsKey(abilityName)) - { + if (cooldowns != null && cooldowns.containsKey(abilityName)) { return cooldowns.get(abilityName).ExpireTime; } return -1L; } - public boolean isOnCooldown(Player player, String abilityName) - { - Map cooldowns = _cooldownMap.get(player.getUniqueId()); + public boolean isOnCooldown(Player player, String abilityName) { + Map cooldowns = this.cooldownMap.get(player.getUniqueId()); return cooldowns != null && cooldowns.containsKey(abilityName); } - public void removeCooldown(Player player, String abilityName) - { + public void removeCooldown(Player player, String abilityName) { UUID uuid = player.getUniqueId(); - Map cooldowns = _cooldownMap.get(player.getUniqueId()); + Map cooldowns = this.cooldownMap.get(player.getUniqueId()); - if (cooldowns == null) - { + if (cooldowns == null) { return; } Cooldown cooldown = cooldowns.remove(abilityName); - if (cooldown == null) - { + if (cooldown == null) { return; } - if (_cooldownQueue.containsKey(uuid)) - { - _cooldownQueue.get(uuid).remove(cooldown); + if (this.cooldownQueue.containsKey(uuid)) { + this.cooldownQueue.get(uuid).remove(cooldown); } - if (cooldown.Permanent) - { - int playerId = _bendingPlayerManager.getBendingPlayer(player).getId(); + if (cooldown.Permanent) { + int playerId = this.bendingPlayerManager.getBendingPlayer(player).getId(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deleteCooldown(playerId, cooldown.AbilityName); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } } - public static class Cooldown - { + public static class Cooldown { + final String AbilityName; final long ExpireTime; final boolean Permanent; - public Cooldown(String abilityName, long expireTime) - { + public Cooldown(String abilityName, long expireTime) { this(abilityName, expireTime, false); } - public Cooldown(String abilityName, long expireTime, boolean permanent) - { + public Cooldown(String abilityName, long expireTime, boolean permanent) { AbilityName = abilityName; ExpireTime = expireTime; Permanent = permanent; } - - } } diff --git a/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java b/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java index 3783d4ed..859237da 100644 --- a/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java +++ b/src/com/projectkorra/projectkorra/cooldown/CooldownRepository.java @@ -10,8 +10,8 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.Map; -public class CooldownRepository extends DatabaseRepository -{ +public class CooldownRepository extends DatabaseRepository { + private static final DatabaseQuery CREATE_TABLE_COOLDOWNS = DatabaseQuery.newBuilder() .query("CREATE TABLE IF NOT EXISTS pk_cooldowns (player_id INTEGER REFERENCES pk_bending_players (player_id), ability_name VARCHAR(100) NOT NULL, expire_time BIGINT NOT NULL, PRIMARY KEY (player_id, ability_name));") .build(); @@ -28,30 +28,24 @@ public class CooldownRepository extends DatabaseRepository .query("DELETE FROM pk_cooldowns WHERE player_id = ? AND ability_name = ?;") .build(); - protected void createTables() throws SQLException - { + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_COOLDOWNS.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_COOLDOWNS.getQuery())) { statement.executeUpdate(); } } - protected Map selectCooldowns(int playerId) throws SQLException - { + protected Map selectCooldowns(int playerId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(SELECT_COOLDOWNS.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(SELECT_COOLDOWNS.getQuery())) { statement.setInt(1, playerId); Map cooldowns = new HashMap<>(); - try (ResultSet rs = statement.executeQuery()) - { - while (rs.next()) - { + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { String abilityName = rs.getString("ability_name"); long expireTime = rs.getLong("expire_time"); @@ -63,12 +57,10 @@ public class CooldownRepository extends DatabaseRepository } } - protected void insertCooldown(int playerId, String abilityName, long expireTime) throws SQLException - { + protected void insertCooldown(int playerId, String abilityName, long expireTime) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(INSERT_COOLDOWN.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(INSERT_COOLDOWN.getQuery())) { statement.setInt(1, playerId); statement.setString(2, abilityName); statement.setLong(3, expireTime); @@ -77,12 +69,10 @@ public class CooldownRepository extends DatabaseRepository } } - protected void deleteCooldown(int playerId, String abilityName) throws SQLException - { + protected void deleteCooldown(int playerId, String abilityName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(DELETE_COOLDOWN.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(DELETE_COOLDOWN.getQuery())) { statement.setInt(1, playerId); statement.setString(2, abilityName); diff --git a/src/com/projectkorra/projectkorra/database/DatabaseConfig.java b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java index c6c7b0ca..c7c781e8 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseConfig.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseConfig.java @@ -2,8 +2,8 @@ package com.projectkorra.projectkorra.database; import com.projectkorra.projectkorra.configuration.Config; -public class DatabaseConfig implements Config -{ +public class DatabaseConfig implements Config { + public final DatabaseManager.Engine Engine = DatabaseManager.Engine.SQLITE; public final String SQLite_File = "projectkorra.sql"; @@ -15,14 +15,12 @@ public class DatabaseConfig implements Config public final String MySQL_Password = "password"; @Override - public String getName() - { + public String getName() { return "Database"; } @Override - public String[] getParents() - { + public String[] getParents() { return new String[0]; } } diff --git a/src/com/projectkorra/projectkorra/database/DatabaseManager.java b/src/com/projectkorra/projectkorra/database/DatabaseManager.java index a13df835..78748b8c 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseManager.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseManager.java @@ -8,50 +8,45 @@ import com.projectkorra.projectkorra.module.Module; import java.util.logging.Level; -public class DatabaseManager extends Module -{ - private final DatabaseConfig _config; - private final SQLDatabase _database; +public class DatabaseManager extends Module { - private DatabaseManager() - { + private final DatabaseConfig config; + private final SQLDatabase database; + + private DatabaseManager() { super("Database"); - _config = ConfigManager.getConfig(DatabaseConfig.class); + this.config = ConfigManager.getConfig(DatabaseConfig.class); - switch (_config.Engine) - { - case MYSQL: - _database = new MySQLDatabase(_config); - break; - case SQLITE: - _database = new SQLiteDatabase(this, _config); - break; - default: - log(Level.SEVERE, "Unknown database engine."); - _database = null; - break; + switch (this.config.Engine) { + case MYSQL: + this.database = new MySQLDatabase(this.config); + break; + case SQLITE: + this.database = new SQLiteDatabase(this, this.config); + break; + default: + log(Level.SEVERE, "Unknown database engine."); + this.database = null; + break; } } - public DatabaseConfig getConfig() - { - return _config; + public DatabaseConfig getConfig() { + return this.config; } - public SQLDatabase getDatabase() - { - return _database; + public SQLDatabase getDatabase() { + return this.database; } @Override - public void onDisable() - { - _database.close(); + public void onDisable() { + this.database.close(); } - public enum Engine - { - MYSQL, SQLITE; + public enum Engine { + MYSQL, + SQLITE; } } diff --git a/src/com/projectkorra/projectkorra/database/DatabaseQuery.java b/src/com/projectkorra/projectkorra/database/DatabaseQuery.java index 7b2446d1..9eb6f970 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseQuery.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseQuery.java @@ -2,62 +2,54 @@ package com.projectkorra.projectkorra.database; import com.projectkorra.projectkorra.module.ModuleManager; -public class DatabaseQuery -{ - private final String _mysql; - private final String _sqlite; +public class DatabaseQuery { - private DatabaseQuery(String mysql, String sqlite) - { - _mysql = mysql; - _sqlite = sqlite; + private final String mysql; + private final String sqlite; + + private DatabaseQuery(String mysql, String sqlite) { + this.mysql = mysql; + this.sqlite = sqlite; } - public String getQuery() - { - switch (ModuleManager.getModule(DatabaseManager.class).getConfig().Engine) - { - case MYSQL: - return _mysql; - case SQLITE: - return _sqlite; + public String getQuery() { + switch (ModuleManager.getModule(DatabaseManager.class).getConfig().Engine) { + case MYSQL: + return this.mysql; + case SQLITE: + return this.sqlite; } return null; } - public static Builder newBuilder() - { + public static Builder newBuilder() { return new Builder(); } - public static final class Builder - { - private String _mysql; - private String _sqlite; + public static final class Builder { - public Builder mysql(String mysql) - { - _mysql = mysql; + private String mysql; + private String sqlite; + + public Builder mysql(String mysql) { + this.mysql = mysql; return this; } - public Builder sqlite(String sqlite) - { - _sqlite = sqlite; + public Builder sqlite(String sqlite) { + this.sqlite = sqlite; return this; } - public Builder query(String query) - { - _mysql = query; - _sqlite = query; + public Builder query(String query) { + this.mysql = query; + this.sqlite = query; return this; } - public DatabaseQuery build() - { - return new DatabaseQuery(_mysql, _sqlite); + public DatabaseQuery build() { + return new DatabaseQuery(this.mysql, this.sqlite); } } } diff --git a/src/com/projectkorra/projectkorra/database/DatabaseRepository.java b/src/com/projectkorra/projectkorra/database/DatabaseRepository.java index 77db1e86..83a9859c 100644 --- a/src/com/projectkorra/projectkorra/database/DatabaseRepository.java +++ b/src/com/projectkorra/projectkorra/database/DatabaseRepository.java @@ -3,17 +3,15 @@ package com.projectkorra.projectkorra.database; import com.projectkorra.projectkorra.database.engine.SQLDatabase; import com.projectkorra.projectkorra.module.ModuleManager; -public abstract class DatabaseRepository -{ +public abstract class DatabaseRepository { + private final DatabaseManager databaseManager; - public DatabaseRepository() - { + public DatabaseRepository() { this.databaseManager = ModuleManager.getModule(DatabaseManager.class); } - protected SQLDatabase getDatabase() - { - return databaseManager.getDatabase(); + protected SQLDatabase getDatabase() { + return this.databaseManager.getDatabase(); } } diff --git a/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java b/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java index 5080fb0c..da2f07c7 100644 --- a/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java +++ b/src/com/projectkorra/projectkorra/database/engine/MySQLDatabase.java @@ -7,12 +7,11 @@ import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.SQLException; -public class MySQLDatabase implements SQLDatabase -{ - private final HikariDataSource _hikari; +public class MySQLDatabase implements SQLDatabase { - public MySQLDatabase(DatabaseConfig databaseConfig) - { + private final HikariDataSource hikari; + + public MySQLDatabase(DatabaseConfig databaseConfig) { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl("jdbc:mysql://" + databaseConfig.MySQL_IP + ":" + databaseConfig.MySQL_Port + "/" + databaseConfig.MySQL_DatabaseName); @@ -23,26 +22,21 @@ public class MySQLDatabase implements SQLDatabase hikariConfig.setMaximumPoolSize(10); hikariConfig.setConnectionTimeout(10000); - _hikari = new HikariDataSource(hikariConfig); + this.hikari = new HikariDataSource(hikariConfig); } @Override - public Connection getConnection() - { - try (Connection connection = _hikari.getConnection()) - { + public Connection getConnection() { + try (Connection connection = this.hikari.getConnection()) { return connection; - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); return null; } } @Override - public void close() - { - _hikari.close(); + public void close() { + this.hikari.close(); } } diff --git a/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java b/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java index b0645666..117dbb02 100644 --- a/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java +++ b/src/com/projectkorra/projectkorra/database/engine/SQLDatabase.java @@ -2,8 +2,8 @@ package com.projectkorra.projectkorra.database.engine; import java.sql.Connection; -public interface SQLDatabase -{ +public interface SQLDatabase { + Connection getConnection(); void close(); diff --git a/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java b/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java index 29ee909d..c86f9c5b 100644 --- a/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java +++ b/src/com/projectkorra/projectkorra/database/engine/SQLiteDatabase.java @@ -9,28 +9,22 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -public class SQLiteDatabase implements SQLDatabase -{ - private final File _databaseFile; - private Connection _connection; +public class SQLiteDatabase implements SQLDatabase { - public SQLiteDatabase(DatabaseManager databaseManager, DatabaseConfig databaseConfig) - { - _databaseFile = new File(databaseManager.getPlugin().getDataFolder(), databaseConfig.SQLite_File); + private final File databaseFile; + private Connection connection; - if (!_databaseFile.getParentFile().exists()) - { - _databaseFile.getParentFile().mkdirs(); + public SQLiteDatabase(DatabaseManager databaseManager, DatabaseConfig databaseConfig) { + this.databaseFile = new File(databaseManager.getPlugin().getDataFolder(), databaseConfig.SQLite_File); + + if (!this.databaseFile.getParentFile().exists()) { + this.databaseFile.getParentFile().mkdirs(); } - if (!_databaseFile.exists()) - { - try - { - _databaseFile.createNewFile(); - } - catch (IOException e) - { + if (!this.databaseFile.exists()) { + try { + this.databaseFile.createNewFile(); + } catch (IOException e) { e.printStackTrace(); } } @@ -38,45 +32,32 @@ public class SQLiteDatabase implements SQLDatabase open(); } - public void open() - { - try - { - _connection = DriverManager.getConnection("jdbc:sqlite:" + _databaseFile.getAbsolutePath()); - } - catch (SQLException e) - { + public void open() { + try { + this.connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFile.getAbsolutePath()); + } catch (SQLException e) { e.printStackTrace(); } } @Override - public Connection getConnection() - { - try - { - if (_connection == null || _connection.isClosed()) - { + public Connection getConnection() { + try { + if (this.connection == null || this.connection.isClosed()) { open(); } - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } - return _connection; + return this.connection; } @Override - public void close() - { - try - { - _connection.close(); - } - catch (SQLException e) - { + public void close() { + try { + this.connection.close(); + } catch (SQLException e) { e.printStackTrace(); } } diff --git a/src/com/projectkorra/projectkorra/element/Element.java b/src/com/projectkorra/projectkorra/element/Element.java index bf25d0a9..01d05579 100644 --- a/src/com/projectkorra/projectkorra/element/Element.java +++ b/src/com/projectkorra/projectkorra/element/Element.java @@ -2,43 +2,37 @@ package com.projectkorra.projectkorra.element; import org.bukkit.ChatColor; -public class Element -{ - private final int _elementId; - private final String _elementName; - private final String _displayName; - private final ChatColor _color; +public class Element { - public Element(int elementId, String elementName, String displayName, ChatColor color) - { - _elementId = elementId; - _elementName = elementName; - _displayName = displayName; - _color = color; + private final int elementId; + private final String elementName; + private final String displayName; + private final ChatColor color; + + public Element(int elementId, String elementName, String displayName, ChatColor color) { + this.elementId = elementId; + this.elementName = elementName; + this.displayName = displayName; + this.color = color; } - public int getId() - { - return _elementId; + public int getId() { + return this.elementId; } - public String getName() - { - return _elementName; + public String getName() { + return this.elementName; } - public String getDisplayName() - { - return _displayName; + public String getDisplayName() { + return this.displayName; } - public ChatColor getColor() - { - return _color; + public ChatColor getColor() { + return this.color; } - public String getColoredName() - { - return _color + _displayName; + public String getColoredName() { + return this.color + this.displayName; } } diff --git a/src/com/projectkorra/projectkorra/element/ElementManager.java b/src/com/projectkorra/projectkorra/element/ElementManager.java index a5ba11b5..7d638d80 100644 --- a/src/com/projectkorra/projectkorra/element/ElementManager.java +++ b/src/com/projectkorra/projectkorra/element/ElementManager.java @@ -17,20 +17,20 @@ import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; -public class ElementManager extends DatabaseModule -{ +public class ElementManager extends DatabaseModule { + private static final String WATER = "water", EARTH = "earth", FIRE = "fire", AIR = "air", CHI = "chi", AVATAR = "avatar"; private static final String BLOOD = "blood", HEALING = "healing", ICE = "ice", PLANT = "plant"; private static final String LAVA = "lava", METAL = "metal", SAND = "sand"; private static final String COMBUSTION = "combustion", LIGHTNING = "lightning"; private static final String FLIGHT = "flight", SPIRITUAL = "spiritual"; - private final BendingPlayerManager _bendingPlayerManager; + private final BendingPlayerManager bendingPlayerManager; - private final Map _elements = new HashMap<>(); - private final Map _names = new HashMap<>(); + private final Map elements = new HashMap<>(); + private final Map names = new HashMap<>(); - private final String _nameRegex = "[a-zA-Z]+"; + private final String nameRegex = "[a-zA-Z]+"; private Element water, earth, fire, air, chi, avatar; private SubElement blood, healing, ice, plant; @@ -38,98 +38,79 @@ public class ElementManager extends DatabaseModule private SubElement combustion, lightning; private SubElement flight, spiritual; - private ElementManager() - { + private ElementManager() { super("Element", new ElementRepository()); - _bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); + this.bendingPlayerManager = ModuleManager.getModule(BendingPlayerManager.class); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().createTables(); // Waterbending - water = addElement(WATER, "Water", ChatColor.AQUA); - blood = addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, water); - healing = addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, water); - ice = addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, water); - plant = addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, water); + this.water = addElement(WATER, "Water", ChatColor.AQUA); + this.blood = addSubElement(BLOOD, "Blood", ChatColor.DARK_AQUA, this.water); + this.healing = addSubElement(HEALING, "Healing", ChatColor.DARK_AQUA, this.water); + this.ice = addSubElement(ICE, "Ice", ChatColor.DARK_AQUA, this.water); + this.plant = addSubElement(PLANT, "Plant", ChatColor.DARK_AQUA, this.water); // Earthbending - earth = addElement(EARTH, "Earth", ChatColor.AQUA); - lava =addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, earth); - metal = addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, earth); - sand = addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, earth); + this.earth = addElement(EARTH, "Earth", ChatColor.AQUA); + this.lava = addSubElement(LAVA, "Lava", ChatColor.DARK_GREEN, this.earth); + this.metal = addSubElement(METAL, "Metal", ChatColor.DARK_GREEN, this.earth); + this.sand = addSubElement(SAND, "Sand", ChatColor.DARK_GREEN, this.earth); // Firebending - fire = addElement(FIRE, "Fire", ChatColor.RED); - combustion = addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, fire); - lightning = addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, fire); + this.fire = addElement(FIRE, "Fire", ChatColor.RED); + this.combustion = addSubElement(COMBUSTION, "Combustion", ChatColor.DARK_RED, this.fire); + this.lightning = addSubElement(LIGHTNING, "Lightning", ChatColor.DARK_RED, this.fire); // Airbending - air = addElement(AIR, "Air", ChatColor.GRAY); - flight = addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, air); - spiritual = addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, air); + this.air = addElement(AIR, "Air", ChatColor.GRAY); + this.flight = addSubElement(FLIGHT, "Flight", ChatColor.DARK_GRAY, this.air); + this.spiritual = addSubElement(SPIRITUAL, "Spiritual", ChatColor.DARK_GRAY, this.air); // Chiblocking - chi = addElement(CHI, "Chi", ChatColor.GOLD); + this.chi = addElement(CHI, "Chi", ChatColor.GOLD); // Avatar - avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE); - } - catch (SQLException e) - { + this.avatar = addElement(AVATAR, "Avatar", ChatColor.DARK_PURPLE); + } catch (SQLException e) { e.printStackTrace(); } - runSync(() -> - { + runSync(() -> { log("Populated element database tables."); }); }); } @EventHandler - public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) - { + public void onBendingPlayerLoaded(BendingPlayerLoadedEvent event) { BendingPlayer bendingPlayer = event.getBendingPlayer(); - runAsync(() -> - { - try - { - List elements = getRepository().selectPlayerElements(bendingPlayer.getId()).stream() - .map(_elements::get) - .collect(Collectors.toList()); + runAsync(() -> { + try { + List elements = getRepository().selectPlayerElements(bendingPlayer.getId()).stream().map(this.elements::get).collect(Collectors.toList()); elements.forEach(bendingPlayer::addElement); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } - public boolean addElement(Player player, Element element) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public boolean addElement(Player player, Element element) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); - if (!bendingPlayer.addElement(element)) - { + if (!bendingPlayer.addElement(element)) { return false; } - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId()); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); @@ -137,44 +118,33 @@ public class ElementManager extends DatabaseModule return true; } - public void setElement(Player player, Element element) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public void setElement(Player player, Element element) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); bendingPlayer.clearElements(); bendingPlayer.addElement(element); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deletePlayerElements(bendingPlayer.getId()); getRepository().insertPlayerElement(bendingPlayer.getId(), element.getId()); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } - public boolean removeElement(Player player, Element element) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public boolean removeElement(Player player, Element element) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); - if (!bendingPlayer.removeElement(element)) - { + if (!bendingPlayer.removeElement(element)) { return false; } - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deletePlayerElement(bendingPlayer.getId(), element.getId()); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); @@ -182,148 +152,120 @@ public class ElementManager extends DatabaseModule return true; } - public void clearElements(Player player) - { - BendingPlayer bendingPlayer = _bendingPlayerManager.getBendingPlayer(player); + public void clearElements(Player player) { + BendingPlayer bendingPlayer = this.bendingPlayerManager.getBendingPlayer(player); bendingPlayer.clearElements(); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().deletePlayerElements(bendingPlayer.getId()); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } - private Element addElement(String elementName, String displayName, ChatColor color) - { + private Element addElement(String elementName, String displayName, ChatColor color) { int elementId = registerElement(elementName); Element element = new Element(elementId, elementName, displayName, color); - _elements.put(elementId, element); - _names.put(elementName, element); + this.elements.put(elementId, element); + this.names.put(elementName, element); return element; } - private SubElement addSubElement(String elementName, String displayName, ChatColor color, Element parent) - { + private SubElement addSubElement(String elementName, String displayName, ChatColor color, Element parent) { int elementId = registerElement(elementName); SubElement element = new SubElement(elementId, elementName, displayName, color, parent); - _elements.put(elementId, element); - _names.put(elementName, element); + this.elements.put(elementId, element); + this.names.put(elementName, element); return element; } - private int registerElement(String elementName) - { + private int registerElement(String elementName) { Preconditions.checkNotNull(elementName, "Element name cannot be null"); - Preconditions.checkArgument(Pattern.matches(_nameRegex, elementName), "Element name must only contain letters and spaces"); + Preconditions.checkArgument(Pattern.matches(this.nameRegex, elementName), "Element name must only contain letters and spaces"); - try - { + try { return getRepository().selectElemenetId(elementName); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); return -1; } } - public Element getWater() - { - return water; + public Element getWater() { + return this.water; } - public SubElement getBlood() - { - return blood; + public SubElement getBlood() { + return this.blood; } - public SubElement getHealing() - { - return healing; + public SubElement getHealing() { + return this.healing; } - public SubElement getIce() - { - return ice; + public SubElement getIce() { + return this.ice; } - public SubElement getPlant() - { - return plant; + public SubElement getPlant() { + return this.plant; } - public Element getEarth() - { - return earth; + public Element getEarth() { + return this.earth; } - public SubElement getLava() - { - return lava; + public SubElement getLava() { + return this.lava; } - public SubElement getMetal() - { - return metal; + public SubElement getMetal() { + return this.metal; } - public SubElement getSand() - { - return sand; + public SubElement getSand() { + return this.sand; } - public Element getFire() - { - return fire; + public Element getFire() { + return this.fire; } - public SubElement getCombustion() - { - return combustion; + public SubElement getCombustion() { + return this.combustion; } - public SubElement getLightning() - { - return lightning; + public SubElement getLightning() { + return this.lightning; } - public Element getAir() - { - return air; + public Element getAir() { + return this.air; } - public SubElement getFlight() - { - return flight; + public SubElement getFlight() { + return this.flight; } - public SubElement getSpiritual() - { - return spiritual; + public SubElement getSpiritual() { + return this.spiritual; } - public Element getChi() - { - return chi; + public Element getChi() { + return this.chi; } - public Element getAvatar() - { - return avatar; + public Element getAvatar() { + return this.avatar; } } diff --git a/src/com/projectkorra/projectkorra/element/ElementRepository.java b/src/com/projectkorra/projectkorra/element/ElementRepository.java index 1d592389..2d35f9a1 100644 --- a/src/com/projectkorra/projectkorra/element/ElementRepository.java +++ b/src/com/projectkorra/projectkorra/element/ElementRepository.java @@ -3,20 +3,17 @@ package com.projectkorra.projectkorra.element; import com.projectkorra.projectkorra.database.DatabaseQuery; import com.projectkorra.projectkorra.database.DatabaseRepository; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.HashSet; import java.util.Set; -public class ElementRepository extends DatabaseRepository -{ +public class ElementRepository extends DatabaseRepository { + private static final DatabaseQuery CREATE_TABLE_ELEMENTS = DatabaseQuery.newBuilder() .mysql("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTO_INCREMENT, element_name VARCHAR(50) NOT NULL, UNIQUE INDEX name_index (element_name));") .sqlite("CREATE TABLE IF NOT EXISTS pk_elements (element_id INTEGER PRIMARY KEY AUTOINCREMENT, element_name VARCHAR(50) NOT NULL); CREATE UNIQUE INDEX name_index ON pk_elements (element_name);") .build(); + private static final DatabaseQuery CREATE_TABLE_PLAYER_ELEMENTS = DatabaseQuery.newBuilder() .mysql("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id), INDEX player_index (player_id), INDEX element_index (element_id));") .sqlite("CREATE TABLE IF NOT EXISTS pk_player_elements (player_id INTEGER REFERENCES pk_bending_players (player_id), element_id INTEGER REFERENCES pk_elements (element_id), PRIMARY KEY (player_id, element_id)); CREATE INDEX player_index ON pk_player_elements (player_id); CREATE INDEX element_index ON pk_player_elements (element_id);") @@ -46,33 +43,23 @@ public class ElementRepository extends DatabaseRepository .query("DELETE FROM pk_player_elements WHERE player_id = ? AND element_id = ?;") .build(); - protected void createTables() throws SQLException - { + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); - try - ( - PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); - PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery()) - ) - { + try (PreparedStatement elements = connection.prepareStatement(CREATE_TABLE_ELEMENTS.getQuery()); PreparedStatement playerElements = connection.prepareStatement(CREATE_TABLE_PLAYER_ELEMENTS.getQuery())) { elements.executeUpdate(); playerElements.executeUpdate(); } } - protected int selectElemenetId(String elementName) throws SQLException - { + protected int selectElemenetId(String elementName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(SELECT_ELEMENT_ID.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(SELECT_ELEMENT_ID.getQuery())) { statement.setString(1, elementName); - try (ResultSet rs = statement.executeQuery()) - { - if (!rs.next()) - { + try (ResultSet rs = statement.executeQuery()) { + if (!rs.next()) { return insertElementId(elementName); } @@ -81,18 +68,15 @@ public class ElementRepository extends DatabaseRepository } } - private int insertElementId(String elementName) throws SQLException - { + private int insertElementId(String elementName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(INSERT_ELEMENT_ID.getQuery(), Statement.RETURN_GENERATED_KEYS)) - { + try (PreparedStatement statement = connection.prepareStatement(INSERT_ELEMENT_ID.getQuery(), Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, elementName); statement.executeUpdate(); - try (ResultSet rs = statement.getGeneratedKeys()) - { + try (ResultSet rs = statement.getGeneratedKeys()) { rs.next(); return rs.getInt(1); @@ -100,20 +84,16 @@ public class ElementRepository extends DatabaseRepository } } - protected Set selectPlayerElements(int playerId) throws SQLException - { + protected Set selectPlayerElements(int playerId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ELEMENTS.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(SELECT_PLAYER_ELEMENTS.getQuery())) { statement.setInt(1, playerId); Set elements = new HashSet<>(); - try (ResultSet rs = statement.executeQuery()) - { - while (rs.next()) - { + try (ResultSet rs = statement.executeQuery()) { + while (rs.next()) { elements.add(rs.getInt("element_id")); } @@ -122,12 +102,10 @@ public class ElementRepository extends DatabaseRepository } } - protected void insertPlayerElement(int playerId, int elementId) throws SQLException - { + protected void insertPlayerElement(int playerId, int elementId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ELEMENT.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(INSERT_PLAYER_ELEMENT.getQuery())) { statement.setInt(1, playerId); statement.setInt(2, elementId); @@ -135,24 +113,20 @@ public class ElementRepository extends DatabaseRepository } } - protected void deletePlayerElements(int playerId) throws SQLException - { + protected void deletePlayerElements(int playerId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENTS.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENTS.getQuery())) { statement.setInt(1, playerId); statement.executeUpdate(); } } - protected void deletePlayerElement(int playerId, int elementId) throws SQLException - { + protected void deletePlayerElement(int playerId, int elementId) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENT.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(DELETE_PLAYER_ELEMENT.getQuery())) { statement.setInt(1, playerId); statement.setInt(2, elementId); diff --git a/src/com/projectkorra/projectkorra/element/SubElement.java b/src/com/projectkorra/projectkorra/element/SubElement.java index 68421cc2..6854740a 100644 --- a/src/com/projectkorra/projectkorra/element/SubElement.java +++ b/src/com/projectkorra/projectkorra/element/SubElement.java @@ -2,19 +2,17 @@ package com.projectkorra.projectkorra.element; import org.bukkit.ChatColor; -public class SubElement extends Element -{ - private final Element _parent; +public class SubElement extends Element { - public SubElement(int elementId, String elementName, String displayName, ChatColor color, Element parent) - { + private final Element parent; + + public SubElement(int elementId, String elementName, String displayName, ChatColor color, Element parent) { super(elementId, elementName, displayName, color); - _parent = parent; + this.parent = parent; } - public Element getParent() - { - return _parent; + public Element getParent() { + return this.parent; } } diff --git a/src/com/projectkorra/projectkorra/module/DatabaseModule.java b/src/com/projectkorra/projectkorra/module/DatabaseModule.java index 221e40b7..743f7b0b 100644 --- a/src/com/projectkorra/projectkorra/module/DatabaseModule.java +++ b/src/com/projectkorra/projectkorra/module/DatabaseModule.java @@ -2,19 +2,17 @@ package com.projectkorra.projectkorra.module; import com.projectkorra.projectkorra.database.DatabaseRepository; -public abstract class DatabaseModule extends Module -{ +public abstract class DatabaseModule extends Module { + private final T repository; - protected DatabaseModule(String name, T repository) - { + protected DatabaseModule(String name, T repository) { super(name); this.repository = repository; } - protected T getRepository() - { + protected T getRepository() { return this.repository; } } diff --git a/src/com/projectkorra/projectkorra/module/Module.java b/src/com/projectkorra/projectkorra/module/Module.java index 4ba9642c..f68e0f0a 100644 --- a/src/com/projectkorra/projectkorra/module/Module.java +++ b/src/com/projectkorra/projectkorra/module/Module.java @@ -9,20 +9,18 @@ import org.bukkit.plugin.java.JavaPlugin; import java.util.logging.Level; -public abstract class Module implements Listener -{ +public abstract class Module implements Listener { + private static final String LOG_FORMAT = "(%s) %s"; private final String name; private final Gson gson = new GsonBuilder().setPrettyPrinting().create(); - protected Module(String name) - { + protected Module(String name) { this.name = name; } - protected final void enable() - { + protected final void enable() { long startTime = System.currentTimeMillis(); log("Enabling..."); @@ -33,13 +31,11 @@ public abstract class Module implements Listener log(String.format("Enabled! [%sms]", finishTime - startTime)); } - public void onEnable() - { + public void onEnable() { } - protected final void disable() - { + protected final void disable() { long startTime = System.currentTimeMillis(); log("Disabling..."); @@ -50,53 +46,43 @@ public abstract class Module implements Listener log(String.format("Disabled! [%sms]", finishTime - startTime)); } - public void onDisable() - { + public void onDisable() { } - protected final void runSync(Runnable runnable) - { + protected final void runSync(Runnable runnable) { getPlugin().getServer().getScheduler().runTask(getPlugin(), runnable); } - protected final void runAsync(Runnable runnable) - { + protected final void runAsync(Runnable runnable) { getPlugin().getServer().getScheduler().runTaskAsynchronously(getPlugin(), runnable); } - protected final void runTimer(Runnable runnable, long delay, long period) - { + protected final void runTimer(Runnable runnable, long delay, long period) { getPlugin().getServer().getScheduler().runTaskTimer(getPlugin(), runnable, delay, period); } - protected final void runAsyncTimer(Runnable runnable, long delay, long period) - { + protected final void runAsyncTimer(Runnable runnable, long delay, long period) { getPlugin().getServer().getScheduler().runTaskTimerAsynchronously(getPlugin(), runnable, delay, period); } - public String getName() - { + public String getName() { return this.name; } - protected Gson getGson() - { + protected Gson getGson() { return this.gson; } - public final void log(String message) - { + public final void log(String message) { log(Level.INFO, message); } - public final void log(Level level, String message) - { + public final void log(Level level, String message) { getPlugin().getLogger().log(level, String.format(LOG_FORMAT, getName(), message)); } - public ProjectKorra getPlugin() - { + public ProjectKorra getPlugin() { return JavaPlugin.getPlugin(ProjectKorra.class); } } diff --git a/src/com/projectkorra/projectkorra/module/ModuleManager.java b/src/com/projectkorra/projectkorra/module/ModuleManager.java index f8f0dd97..20418125 100644 --- a/src/com/projectkorra/projectkorra/module/ModuleManager.java +++ b/src/com/projectkorra/projectkorra/module/ModuleManager.java @@ -79,5 +79,4 @@ public class ModuleManager { getModule(BendingPlayerManager.class).disable(); getModule(DatabaseManager.class).disable(); } - } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayer.java b/src/com/projectkorra/projectkorra/player/BendingPlayer.java index be7d69a4..67dae2a0 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayer.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayer.java @@ -11,14 +11,10 @@ import com.projectkorra.projectkorra.element.ElementManager; import com.projectkorra.projectkorra.module.ModuleManager; import org.bukkit.entity.Player; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; +import java.util.*; + +public class BendingPlayer { -public class BendingPlayer -{ private final BendingPlayerManager manager; private final ElementManager elementManager; private final AbilityManager abilityManager; @@ -42,8 +38,7 @@ public class BendingPlayer private boolean chiBlocked; private long slowTime; - public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) - { + public BendingPlayer(int playerId, UUID uuid, String playerName, long firstLogin) { this.manager = ModuleManager.getModule(BendingPlayerManager.class); this.elementManager = ModuleManager.getModule(ElementManager.class); this.abilityManager = ModuleManager.getModule(AbilityManager.class); @@ -60,267 +55,213 @@ public class BendingPlayer this.abilities = new String[9]; } - public Set getElements() - { + public Set getElements() { return new HashSet<>(this.elements); } - public boolean addElement(Element element) - { + public boolean addElement(Element element) { return this.elements.add(element); } - public boolean removeElement(Element element) - { + public boolean removeElement(Element element) { return this.elements.remove(element); } - public void clearElements() - { + public void clearElements() { this.elements.clear(); } - public boolean hasElement(Element element) - { - if (element.equals(elementManager.getAvatar())) - { + public boolean hasElement(Element element) { + if (element.equals(this.elementManager.getAvatar())) { return this.player.hasPermission("bending.avatar"); } return this.elements.contains(element); } - public boolean canBloodbend() - { - return this.elements.contains(elementManager.getBlood()); + public boolean canBloodbend() { + return this.elements.contains(this.elementManager.getBlood()); } - public boolean canUseHealing() - { - return this.elements.contains(elementManager.getHealing()); + public boolean canUseHealing() { + return this.elements.contains(this.elementManager.getHealing()); } - public boolean canIcebend() - { - return this.elements.contains(elementManager.getIce()); + public boolean canIcebend() { + return this.elements.contains(this.elementManager.getIce()); } - public boolean canPlantbend() - { - return this.elements.contains(elementManager.getPlant()); + public boolean canPlantbend() { + return this.elements.contains(this.elementManager.getPlant()); } - public boolean canLavabend() - { - return this.elements.contains(elementManager.getLava()); + public boolean canLavabend() { + return this.elements.contains(this.elementManager.getLava()); } - public boolean canMetalbend() - { - return this.elements.contains(elementManager.getMetal()); + public boolean canMetalbend() { + return this.elements.contains(this.elementManager.getMetal()); } - public boolean canSandbend() - { - return this.elements.contains(elementManager.getSand()); + public boolean canSandbend() { + return this.elements.contains(this.elementManager.getSand()); } - public boolean canCombustionbend() - { - return this.elements.contains(elementManager.getCombustion()); + public boolean canCombustionbend() { + return this.elements.contains(this.elementManager.getCombustion()); } - public boolean canUseLightning() - { - return this.elements.contains(elementManager.getLightning()); + public boolean canUseLightning() { + return this.elements.contains(this.elementManager.getLightning()); } - public boolean canUseFlight() - { - return this.elements.contains(elementManager.getFlight()); + public boolean canUseFlight() { + return this.elements.contains(this.elementManager.getFlight()); } - public boolean canUseSpiritual() - { - return this.elements.contains(elementManager.getSpiritual()); + public boolean canUseSpiritual() { + return this.elements.contains(this.elementManager.getSpiritual()); } - public boolean isElementToggled(Element element) - { + public boolean isElementToggled(Element element) { return this.toggledElements.contains(element); } - public void toggleElement(Element element) - { - if (this.toggledElements.contains(element)) - { + public void toggleElement(Element element) { + if (this.toggledElements.contains(element)) { this.toggledElements.remove(element); - } - else - { + } else { this.toggledElements.add(element); } } - public CoreAbility getBoundAbility() - { + public CoreAbility getBoundAbility() { return CoreAbility.getAbility(getBoundAbilityName()); } - public String getBoundAbilityName() - { + public String getBoundAbilityName() { int slot = this.player.getInventory().getHeldItemSlot(); return this.abilities[slot]; } - public String getAbility(int slot) - { + public String getAbility(int slot) { return this.abilities[slot]; } - public List getAbilities() - { + public List getAbilities() { return Arrays.asList(this.abilities); } - public void setAbilities(String[] abilities) - { + public void setAbilities(String[] abilities) { System.arraycopy(abilities, 0, this.abilities, 0, 9); } - public void setAbility(int slot, String abilityName) - { + public void setAbility(int slot, String abilityName) { this.abilities[slot] = abilityName; } - public void addCooldown(Ability ability) - { + public void addCooldown(Ability ability) { addCooldown(ability, ability.getCooldown()); } - public void addCooldown(Ability ability, long duration) - { + public void addCooldown(Ability ability, long duration) { addCooldown(ability.getName(), duration); } - public void addCooldown(Ability ability, long duration, boolean permanent) - { + public void addCooldown(Ability ability, long duration, boolean permanent) { addCooldown(ability.getName(), duration, permanent); } - public void addCooldown(String abilityName, long duration) - { + public void addCooldown(String abilityName, long duration) { addCooldown(abilityName, duration, false); } - public void addCooldown(String abilityName, long duration, boolean permanent) - { - cooldownManager.addCooldown(this.player, abilityName, duration, permanent); + public void addCooldown(String abilityName, long duration, boolean permanent) { + this.cooldownManager.addCooldown(this.player, abilityName, duration, permanent); } - public boolean isOnCooldown(Ability ability) - { + public boolean isOnCooldown(Ability ability) { return isOnCooldown(ability.getName()); } - public boolean isOnCooldown(String abilityName) - { - return cooldownManager.isOnCooldown(this.player, abilityName); + public boolean isOnCooldown(String abilityName) { + return this.cooldownManager.isOnCooldown(this.player, abilityName); } - public void removeCooldown(Ability ability) - { + public void removeCooldown(Ability ability) { removeCoolldown(ability.getName()); } - public void removeCoolldown(String abilityName) - { - cooldownManager.removeCooldown(this.player, abilityName); + public void removeCoolldown(String abilityName) { + this.cooldownManager.removeCooldown(this.player, abilityName); } - public ChiAbility getStance() - { + public ChiAbility getStance() { return this.stance; } - public void setStance(ChiAbility stance) - { + public void setStance(ChiAbility stance) { this.stance = stance; } - public boolean isBendingRemoved() - { + public boolean isBendingRemoved() { return this.bendingRemoved; } - protected void setBendingRemoved(boolean bendingRemoved) - { + protected void setBendingRemoved(boolean bendingRemoved) { this.bendingRemoved = bendingRemoved; } - public boolean isToggled() - { + public boolean isToggled() { return this.toggled; } - public void toggleBending() - { + public void toggleBending() { this.toggled = !this.toggled; PassiveManager.registerPassives(this.player); // TODO redo this passive system } - public boolean isTremorSensing() - { + public boolean isTremorSensing() { return this.tremorSense; } - public void toggleTremorSense() - { + public void toggleTremorSense() { this.tremorSense = !this.tremorSense; } - public boolean isIlluminating() - { + public boolean isIlluminating() { return this.illumination; } - public void toggleIllumination() - { + public void toggleIllumination() { this.illumination = !this.illumination; } - public boolean isChiBlocked() - { + public boolean isChiBlocked() { return this.chiBlocked; } - public void blockChi() - { + public void blockChi() { this.chiBlocked = true; } - public void unblockChi() - { + public void unblockChi() { this.chiBlocked = false; } - public boolean canBeSlowed() - { + public boolean canBeSlowed() { return System.currentTimeMillis() > this.slowTime; } - public void slow(long cooldown) - { + public void slow(long cooldown) { this.slowTime = System.currentTimeMillis() + cooldown; } - public int getId() - { + public int getId() { return this.playerId; } - public long getFirstLogin() - { + public long getFirstLogin() { return this.firstLogin; } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java b/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java index f1fb08be..85e8deeb 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerLoadedEvent.java @@ -4,32 +4,28 @@ import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; -public class BendingPlayerLoadedEvent extends PlayerEvent -{ +public class BendingPlayerLoadedEvent extends PlayerEvent { + private static final HandlerList HANDLER_LIST = new HandlerList(); - private final BendingPlayer _bendingPlayer; + private final BendingPlayer bendingPlayer; - public BendingPlayerLoadedEvent(Player player, BendingPlayer bendingPlayer) - { + public BendingPlayerLoadedEvent(Player player, BendingPlayer bendingPlayer) { super(player); - _bendingPlayer = bendingPlayer; + this.bendingPlayer = bendingPlayer; } - public BendingPlayer getBendingPlayer() - { - return _bendingPlayer; + public BendingPlayer getBendingPlayer() { + return this.bendingPlayer; } @Override - public HandlerList getHandlers() - { + public HandlerList getHandlers() { return HANDLER_LIST; } - public static HandlerList getHandlerList() - { + public static HandlerList getHandlerList() { return HANDLER_LIST; } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java index 92e772c0..321dc062 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerManager.java @@ -10,141 +10,110 @@ import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; -public class BendingPlayerManager extends DatabaseModule -{ - private final Map _players = new HashMap<>(); +public class BendingPlayerManager extends DatabaseModule { - private final Set _disconnected = new HashSet<>(); - private final long _databaseSyncInterval = 20 * 30; + private final Map players = new HashMap<>(); - private BendingPlayerManager() - { + private final Set disconnected = new HashSet<>(); + private final long databaseSyncInterval = 20 * 30; + + private BendingPlayerManager() { super("Bending Player", new BendingPlayerRepository()); - runAsync(() -> - { - try - { + runAsync(() -> { + try { getRepository().createTables(); - for (Player player : getPlugin().getServer().getOnlinePlayers()) - { + for (Player player : getPlugin().getServer().getOnlinePlayers()) { loadBendingPlayer(player); } - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); - runTimer(() -> - { - _disconnected.forEach(_players::remove); - _disconnected.clear(); - }, _databaseSyncInterval, _databaseSyncInterval); + runTimer(() -> { + this.disconnected.forEach(this.players::remove); + this.disconnected.clear(); + }, this.databaseSyncInterval, this.databaseSyncInterval); } @EventHandler(priority = EventPriority.LOWEST) - public void onLogin(PlayerLoginEvent event) - { - if (_disconnected.remove(event.getPlayer().getUniqueId())) - { + public void onLogin(PlayerLoginEvent event) { + if (this.disconnected.remove(event.getPlayer().getUniqueId())) { return; } - runAsync(() -> - { + runAsync(() -> { loadBendingPlayer(event.getPlayer()); }); } @EventHandler - public void onQuit(PlayerQuitEvent event) - { - _disconnected.add(event.getPlayer().getUniqueId()); + public void onQuit(PlayerQuitEvent event) { + this.disconnected.add(event.getPlayer().getUniqueId()); } @EventHandler - public void onCooldownChange(PlayerCooldownChangeEvent event) - { + public void onCooldownChange(PlayerCooldownChangeEvent event) { Player player = event.getPlayer(); - BendingPlayer bendingPlayer = _players.get(player.getUniqueId()); + BendingPlayer bendingPlayer = this.players.get(player.getUniqueId()); String ability = bendingPlayer.getBoundAbilityName(); - if (ability != null && ability.equals(event.getAbility())) - { + if (ability != null && ability.equals(event.getAbility())) { GeneralMethods.displayMovePreview(player); } } - public void removeBending(Player player) - { - BendingPlayer bendingPlayer = _players.get(player.getUniqueId()); + public void removeBending(Player player) { + BendingPlayer bendingPlayer = this.players.get(player.getUniqueId()); bendingPlayer.setBendingRemoved(true); updateBendingRemoved(bendingPlayer); } - public void returnBending(Player player) - { - BendingPlayer bendingPlayer = _players.get(player.getUniqueId()); + public void returnBending(Player player) { + BendingPlayer bendingPlayer = this.players.get(player.getUniqueId()); bendingPlayer.setBendingRemoved(false); updateBendingRemoved(bendingPlayer); } - private void updateBendingRemoved(BendingPlayer bendingPlayer) - { - runAsync(() -> - { - try - { + private void updateBendingRemoved(BendingPlayer bendingPlayer) { + runAsync(() -> { + try { getRepository().updateBendingRemoved(bendingPlayer); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } }); } - private void loadBendingPlayer(Player player) - { - try - { + private void loadBendingPlayer(Player player) { + try { BendingPlayer bendingPlayer = getRepository().selectPlayer(player); - runSync(() -> - { - _players.put(player.getUniqueId(), bendingPlayer); + runSync(() -> { + this.players.put(player.getUniqueId(), bendingPlayer); BendingPlayerLoadedEvent bendingPlayerLoadedEvent = new BendingPlayerLoadedEvent(player, bendingPlayer); getPlugin().getServer().getPluginManager().callEvent(bendingPlayerLoadedEvent); }); - } - catch (SQLException e) - { + } catch (SQLException e) { e.printStackTrace(); } } - public BendingPlayer getBendingPlayer(Player player) - { + public BendingPlayer getBendingPlayer(Player player) { return getBendingPlayer(player.getUniqueId()); } - public BendingPlayer getBendingPlayer(UUID uuid) - { - return _players.get(uuid); + public BendingPlayer getBendingPlayer(UUID uuid) { + return this.players.get(uuid); } } diff --git a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java index cb760b64..e59ac602 100644 --- a/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java +++ b/src/com/projectkorra/projectkorra/player/BendingPlayerRepository.java @@ -5,15 +5,11 @@ import com.projectkorra.projectkorra.database.DatabaseRepository; import org.bukkit.entity.Player; import java.nio.ByteBuffer; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; +import java.sql.*; import java.util.UUID; -public class BendingPlayerRepository extends DatabaseRepository -{ +public class BendingPlayerRepository extends DatabaseRepository { + private static final DatabaseQuery CREATE_TABLE_BENDING_PLAYERS = DatabaseQuery.newBuilder() .mysql("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTO_INCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN, INDEX uuid_index (uuid));") .sqlite("CREATE TABLE IF NOT EXISTS pk_bending_players (player_id INTEGER PRIMARY KEY AUTOINCREMENT, uuid BINARY(16) NOT NULL, player_name VARCHAR(16) NOT NULL, first_login BIGINT NOT NULL, bending_removed BOOLEAN); CREATE INDEX uuid_index ON pk_bending_players (uuid);") @@ -35,31 +31,25 @@ public class BendingPlayerRepository extends DatabaseRepository .query("UPDATE pk_bending_players SET bending_removed = ? WHERE player_id = ?;") .build(); - protected void createTables() throws SQLException - { + protected void createTables() throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_BENDING_PLAYERS.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(CREATE_TABLE_BENDING_PLAYERS.getQuery())) { statement.executeUpdate(); } } - protected BendingPlayer selectPlayer(Player player) throws SQLException - { + protected BendingPlayer selectPlayer(Player player) throws SQLException { UUID uuid = player.getUniqueId(); byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(SELECT_BENDING_PLAYER.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(SELECT_BENDING_PLAYER.getQuery())) { statement.setBytes(1, binaryUUID); - try (ResultSet rs = statement.executeQuery()) - { - if (!rs.next()) - { + try (ResultSet rs = statement.executeQuery()) { + if (!rs.next()) { return insertPlayer(player.getUniqueId(), player.getName()); } @@ -68,8 +58,7 @@ public class BendingPlayerRepository extends DatabaseRepository long firstLogin = rs.getLong("first_login"); boolean bendingRemoved = rs.getBoolean("bending_removed"); - if (!player.getName().equals(playerName)) - { + if (!player.getName().equals(playerName)) { updatePlayerName(playerId, player.getName()); } @@ -82,23 +71,20 @@ public class BendingPlayerRepository extends DatabaseRepository } } - private BendingPlayer insertPlayer(UUID uuid, String playerName) throws SQLException - { + private BendingPlayer insertPlayer(UUID uuid, String playerName) throws SQLException { byte[] binaryUUID = ByteBuffer.allocate(16).putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits()).array(); Connection connection = getDatabase().getConnection(); long firstLogin = System.currentTimeMillis(); - try (PreparedStatement statement = connection.prepareStatement(INSERT_BENDING_PLAYER.getQuery(), Statement.RETURN_GENERATED_KEYS)) - { + try (PreparedStatement statement = connection.prepareStatement(INSERT_BENDING_PLAYER.getQuery(), Statement.RETURN_GENERATED_KEYS)) { statement.setBytes(1, binaryUUID); statement.setString(2, playerName); statement.setLong(3, firstLogin); statement.executeUpdate(); - try (ResultSet rs = statement.getGeneratedKeys()) - { + try (ResultSet rs = statement.getGeneratedKeys()) { rs.next(); int playerId = rs.getInt(1); @@ -108,12 +94,10 @@ public class BendingPlayerRepository extends DatabaseRepository } } - protected void updatePlayerName(int playerId, String playerName) throws SQLException - { + protected void updatePlayerName(int playerId, String playerName) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(UPDATE_PLAYER_NAME.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(UPDATE_PLAYER_NAME.getQuery())) { statement.setInt(1, playerId); statement.setString(2, playerName); @@ -121,12 +105,10 @@ public class BendingPlayerRepository extends DatabaseRepository } } - protected void updateBendingRemoved(BendingPlayer bendingPlayer) throws SQLException - { + protected void updateBendingRemoved(BendingPlayer bendingPlayer) throws SQLException { Connection connection = getDatabase().getConnection(); - try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_REMOVED.getQuery())) - { + try (PreparedStatement statement = connection.prepareStatement(UPDATE_BENDING_REMOVED.getQuery())) { statement.setInt(1, bendingPlayer.getId()); statement.setBoolean(2, bendingPlayer.isBendingRemoved());