From 1068c22fe3485f3725fef8fe1dbcca9ee81f7999 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 6 Jan 2023 00:14:55 +0100 Subject: [PATCH 01/25] Fix apache commons bundling with plugin --- pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2cda239..026e45a 100644 --- a/pom.xml +++ b/pom.xml @@ -10,12 +10,12 @@ MIT License - https://raw.githubusercontent.com/DoggyCraftDK/MyDog/master/LICENSE + https://raw.githubusercontent.com/HeroGamers/MyDog/master/LICENSE - DoggyCraft/MyDog + HeroGamers/MyDog 1.19.2-R0.1-SNAPSHOT 8 ${jdk.version} @@ -79,6 +79,7 @@ org.apache.commons commons-lang3 3.12.0 + provided From e0f01334601aac8ad0c91c7c5ebcfb8e906dc659 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 6 Jan 2023 00:23:10 +0100 Subject: [PATCH 02/25] Change spigot version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 026e45a..d08270e 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ HeroGamers/MyDog - 1.19.2-R0.1-SNAPSHOT + 1.19.3-R0.1-SNAPSHOT 8 ${jdk.version} ${jdk.version} From 025d7d7f87c5b79e9193dbc32aff51112c70bb7a Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 20:43:31 +0200 Subject: [PATCH 03/25] Update to 1.19.4 --- pom.xml | 4 ++-- src/main/java/dk/fido2603/mydog/{api => }/MyDogAPI.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename src/main/java/dk/fido2603/mydog/{api => }/MyDogAPI.java (94%) diff --git a/pom.xml b/pom.xml index d08270e..572250b 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ HeroGamers/MyDog - 1.19.3-R0.1-SNAPSHOT + 1.19.4-R0.1-SNAPSHOT 8 ${jdk.version} ${jdk.version} @@ -71,7 +71,7 @@ org.junit.jupiter junit-jupiter-engine - 5.8.2 + 5.9.2 test diff --git a/src/main/java/dk/fido2603/mydog/api/MyDogAPI.java b/src/main/java/dk/fido2603/mydog/MyDogAPI.java similarity index 94% rename from src/main/java/dk/fido2603/mydog/api/MyDogAPI.java rename to src/main/java/dk/fido2603/mydog/MyDogAPI.java index d315882..65bbee4 100644 --- a/src/main/java/dk/fido2603/mydog/api/MyDogAPI.java +++ b/src/main/java/dk/fido2603/mydog/MyDogAPI.java @@ -1,4 +1,4 @@ -package dk.fido2603.mydog.api; +package dk.fido2603.mydog; import java.util.UUID; From eb0110d32b695301974682c0045ab616c8239c13 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 20:48:47 +0200 Subject: [PATCH 04/25] Move tasks to seperate package --- src/main/java/dk/fido2603/mydog/MyDog.java | 83 +------------------ .../fido2603/mydog/tasks/AttackModeTask.java | 56 +++++++++++++ .../dk/fido2603/mydog/tasks/DistanceTask.java | 53 ++++++++++++ 3 files changed, 113 insertions(+), 79 deletions(-) create mode 100644 src/main/java/dk/fido2603/mydog/tasks/AttackModeTask.java create mode 100644 src/main/java/dk/fido2603/mydog/tasks/DistanceTask.java diff --git a/src/main/java/dk/fido2603/mydog/MyDog.java b/src/main/java/dk/fido2603/mydog/MyDog.java index 894ae18..8fe31ec 100644 --- a/src/main/java/dk/fido2603/mydog/MyDog.java +++ b/src/main/java/dk/fido2603/mydog/MyDog.java @@ -1,7 +1,6 @@ package dk.fido2603.mydog; import dk.fido2603.mydog.listeners.WolfMainListener_1_18; -import dk.fido2603.mydog.objects.Dog; import dk.fido2603.mydog.objects.LevelFactory; import dk.fido2603.mydog.objects.LevelFactory.Level; import dk.fido2603.mydog.listeners.DamageListener; @@ -10,6 +9,8 @@ import dk.fido2603.mydog.managers.DogManager; import dk.fido2603.mydog.managers.PermissionsManager; import dk.fido2603.mydog.managers.TeleportationManager; +import dk.fido2603.mydog.tasks.AttackModeTask; +import dk.fido2603.mydog.tasks.DistanceTask; import dk.fido2603.mydog.utils.ParticleUtils; import dk.fido2603.mydog.utils.versioning.Version; import dk.fido2603.mydog.utils.versioning.VersionFactory; @@ -21,7 +22,6 @@ import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; import org.bukkit.Server; -import org.bukkit.block.BlockFace; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; @@ -244,87 +244,12 @@ public void onEnable() { // The dog distance checker, might take some extra powerrr. Checks every ~30 seconds. Starts after 1,5 minutes. if (playerDistanceCheck && automaticTeleportation) { - Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { - @Override - public void run() { - plugin.logDebug("Running the distance checker!"); - List entities = new ArrayList<>(); - - for (Player player : getServer().getOnlinePlayers()) { - for (Dog dog : MyDog.getDogManager().getAliveDogs((player.getUniqueId()))) { - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - if (wolf != null && !wolf.isSitting()) { - double distance = 0.0; - // if they are in two seperate worlds, it's safe to say that the distance is above 30 lol - if (!player.getWorld().getUID().equals(wolf.getWorld().getUID())) { - distance = 1000; - } else { - distance = player.getLocation().distance(wolf.getLocation()); - } - - // A quick dirty check for ground below player - if (distance >= 30.0 && player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().isSolid()) { - if (!experimentalTeleport) { - wolf.teleport(player); - } else { - entities.add(wolf); - } - } - } - } - } - - if (experimentalTeleport) { - MyDog.getTeleportationManager().teleportEntities(entities, null, "DistanceChecker"); - } - } - }, 20L * 60L, 20L * 10L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new DistanceTask(this), 20L * 60L, 20L * 10L); } // Attack mode / angry checker // keeps the dog on a target - Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { - @Override - public void run() { - plugin.logDebug("Running the angry dog target checker!"); - for (Player player : getServer().getOnlinePlayers()) { - for (Dog dog : MyDog.getDogManager().getAliveDogs((player.getUniqueId()))) { - if (dog.isAngry()) { - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - // If the dog has no target - if (wolf != null && !wolf.isSitting() && wolf.getTarget() == null) { - double distance; - - // if they are in two seperate worlds, it's safe to say that the distance is above 20 lol - if (!player.getWorld().getUID().equals(wolf.getWorld().getUID())) { - distance = 1000; - } else { - distance = player.getLocation().distance(wolf.getLocation()); - } - - // If distance is below or equal to 20, find a new target near the player - if (distance <= 20.0) { - List entities = player.getNearbyEntities(13, 13, 13); - // Get the closest target - double lastDistance = Double.MAX_VALUE; - Entity closest = null; - for (Entity entity : entities) { - double distanceToTarget = player.getLocation().distance(entity.getLocation()); - if (entity instanceof Monster && distanceToTarget < lastDistance) { - lastDistance = distanceToTarget; - closest = entity; - } - } - if (closest != null) { - wolf.setTarget((LivingEntity) closest); - } - } - } - } - } - } - } - }, 20L * 30L, 20L * 2L); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new AttackModeTask(this), 20L * 30L, 20L * 2L); } public void log(String message) { diff --git a/src/main/java/dk/fido2603/mydog/tasks/AttackModeTask.java b/src/main/java/dk/fido2603/mydog/tasks/AttackModeTask.java new file mode 100644 index 0000000..2dd085e --- /dev/null +++ b/src/main/java/dk/fido2603/mydog/tasks/AttackModeTask.java @@ -0,0 +1,56 @@ +package dk.fido2603.mydog.tasks; + +import dk.fido2603.mydog.MyDog; +import dk.fido2603.mydog.objects.Dog; +import org.bukkit.entity.*; + +import java.util.List; + +public class AttackModeTask implements Runnable { + private MyDog plugin; + + public AttackModeTask(MyDog instance) { + this.plugin = instance; + } + + @Override + public void run() { + plugin.logDebug("Running the angry dog target checker!"); + for (Player player : plugin.getServer().getOnlinePlayers()) { + for (Dog dog : MyDog.getDogManager().getAliveDogs((player.getUniqueId()))) { + if (dog.isAngry()) { + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + // If the dog has no target + if (wolf != null && !wolf.isSitting() && wolf.getTarget() == null) { + double distance; + + // if they are in two seperate worlds, it's safe to say that the distance is above 20 lol + if (!player.getWorld().getUID().equals(wolf.getWorld().getUID())) { + distance = 1000; + } else { + distance = player.getLocation().distance(wolf.getLocation()); + } + + // If distance is below or equal to 20, find a new target near the player + if (distance <= 20.0) { + List entities = player.getNearbyEntities(13, 13, 13); + // Get the closest target + double lastDistance = Double.MAX_VALUE; + Entity closest = null; + for (Entity entity : entities) { + double distanceToTarget = player.getLocation().distance(entity.getLocation()); + if (entity instanceof Monster && distanceToTarget < lastDistance) { + lastDistance = distanceToTarget; + closest = entity; + } + } + if (closest != null) { + wolf.setTarget((LivingEntity) closest); + } + } + } + } + } + } + } +} diff --git a/src/main/java/dk/fido2603/mydog/tasks/DistanceTask.java b/src/main/java/dk/fido2603/mydog/tasks/DistanceTask.java new file mode 100644 index 0000000..1443364 --- /dev/null +++ b/src/main/java/dk/fido2603/mydog/tasks/DistanceTask.java @@ -0,0 +1,53 @@ +package dk.fido2603.mydog.tasks; + +import dk.fido2603.mydog.MyDog; +import dk.fido2603.mydog.objects.Dog; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wolf; + +import java.util.ArrayList; +import java.util.List; + +public class DistanceTask implements Runnable { + private MyDog plugin; + + public DistanceTask(MyDog instance) { + this.plugin = instance; + } + + @Override + public void run() { + plugin.logDebug("Running the distance checker!"); + List entities = new ArrayList<>(); + + for (Player player : plugin.getServer().getOnlinePlayers()) { + for (Dog dog : MyDog.getDogManager().getAliveDogs((player.getUniqueId()))) { + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + if (wolf != null && !wolf.isSitting()) { + double distance = 0.0; + // if they are in two seperate worlds, it's safe to say that the distance is above 30 lol + if (!player.getWorld().getUID().equals(wolf.getWorld().getUID())) { + distance = 1000; + } else { + distance = player.getLocation().distance(wolf.getLocation()); + } + + // A quick dirty check for ground below player + if (distance >= 30.0 && player.getLocation().getBlock().getRelative(BlockFace.DOWN).getType().isSolid()) { + if (!plugin.experimentalTeleport) { + wolf.teleport(player); + } else { + entities.add(wolf); + } + } + } + } + } + + if (plugin.experimentalTeleport) { + MyDog.getTeleportationManager().teleportEntities(entities, null, "DistanceChecker"); + } + } +} From 9a4a9d61071ff526e740e99846ae1cb7e892ae19 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 20:52:30 +0200 Subject: [PATCH 05/25] Formatting --- .../java/dk/fido2603/mydog/managers/DogManager.java | 3 +-- src/main/java/dk/fido2603/mydog/objects/Dog.java | 10 ++++------ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/DogManager.java b/src/main/java/dk/fido2603/mydog/managers/DogManager.java index ed0aec1..06c7e10 100644 --- a/src/main/java/dk/fido2603/mydog/managers/DogManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/DogManager.java @@ -83,8 +83,7 @@ public void dogDied(UUID dogId) { if (dog != null) { dog.setDead(true); } - } - else { + } else { removeDog(dogId); } } diff --git a/src/main/java/dk/fido2603/mydog/objects/Dog.java b/src/main/java/dk/fido2603/mydog/objects/Dog.java index eb80ce8..30cc7ad 100644 --- a/src/main/java/dk/fido2603/mydog/objects/Dog.java +++ b/src/main/java/dk/fido2603/mydog/objects/Dog.java @@ -133,6 +133,7 @@ public Wolf getWolf() { /** * Reassigns the dog to another UUID. * NOTE: Deletes the old dog from the data! + * * @param dogID the new UUID */ public void setUUID(UUID dogID) { @@ -574,8 +575,7 @@ public void syncDog() { if (collarColor == null) { if (wolf != null) { this.collarColor = wolf.getCollarColor(); - } - else { + } else { if (MyDog.instance().randomCollarColor) { this.collarColor = ColorUtils.randomDyeColor(); } @@ -585,8 +585,7 @@ public void syncDog() { this.nameColor = ColorUtils.getChatColorFromDyeColor(collarColor); MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".NameChatColor", nameColor.name()); } - } - else { + } else { if (nameColor == null) { this.nameColor = ColorUtils.getChatColorFromDyeColor(collarColor); } @@ -596,8 +595,7 @@ public void syncDog() { // Save the Dog's last seen location if (this.location == null) { this.location = getDogLocation(); - } - else { + } else { MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".LastSeen.World", location.getWorld().getName()); MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".LastSeen.X", location.getX()); MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".LastSeen.Y", location.getY()); From dc673856801da52fd673016b9166caafc2f13415 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 20:57:15 +0200 Subject: [PATCH 06/25] Closes #61 --- .../dk/fido2603/mydog/managers/CommandManager.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 2c9f86c..5794a72 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -579,11 +579,13 @@ private boolean commandReviveDog(Player player, CommandSender sender, int dogIde return false; } - if (!MyDog.getEconomy().has(player, deadDog.getRevivalPrice())) { - sender.sendMessage(ChatColor.RED + "You don't have enough funds to resurrect the dog."); - return false; + if (MyDog.getEconomy() != null) { + if (!MyDog.getEconomy().has(player, deadDog.getRevivalPrice())) { + sender.sendMessage(ChatColor.RED + "You don't have enough funds to resurrect the dog."); + return false; + } + MyDog.getEconomy().withdrawPlayer(player, deadDog.getRevivalPrice()); } - MyDog.getEconomy().withdrawPlayer(player, deadDog.getRevivalPrice()); Wolf wolf = player.getWorld().spawn(player.getLocation(), Wolf.class); wolf.setOwner(player); From 780082d0dda4f6423632089aa69913b4e5e2af07 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 21:11:43 +0200 Subject: [PATCH 07/25] Don't teleport entities in async thread - closes #52 --- .../mydog/managers/TeleportationManager.java | 36 +++++++++---------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java b/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java index fb2d8dd..da1906f 100644 --- a/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java @@ -16,8 +16,6 @@ import java.util.HashMap; import java.util.List; import java.util.UUID; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; public class TeleportationManager { private MyDog plugin = null; @@ -44,27 +42,27 @@ public void teleportEntities(List entities, Location location, String re } // Create new threads to run the teleporting - plugin.logDebug("Creating a new threadpool! - " + reason); - ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1); +// plugin.logDebug("Creating a new threadpool! - " + reason); +// ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1); if (reason.equals("PlayerTeleport")) { // Do the teleport task 3 ticks after the player has teleported new BukkitRunnable() { @Override public void run() { - doTeleportEntities(entities, location, executor, reason); + doTeleportEntities(entities, location, reason); } }.runTaskLater(this.plugin, 3); } else { - doTeleportEntities(entities, location, executor, reason); + doTeleportEntities(entities, location, reason); } // Let's remove the entities we just teleported from the list of teleporting entities, once the thread pool has terminated new BukkitRunnable() { @Override public void run() { - if (executor.isTerminated()) { - plugin.logDebug("The thread pool is terminated successfully. Removing teleporting entities! - " + reason); +// if (executor.isTerminated()) { +// plugin.logDebug("The thread pool is terminated successfully. Removing teleporting entities! - " + reason); for (Entity e : entities) { teleportingEntities.remove(e.getUniqueId()); } @@ -74,20 +72,20 @@ public void run() { } this.cancel(); - } +// } } }.runTaskTimer(this.plugin, 20L * 10L, 20L); } // Experimental function - private void doTeleportEntities(List entities, Location location, ThreadPoolExecutor executor, String reason) { + private void doTeleportEntities(List entities, Location location, String reason) { Location safeLocation = null; for (Entity e : entities) { // All tameables if (e instanceof Sittable && e instanceof Tameable && !teleportingEntities.contains(e.getUniqueId()) && !((Sittable) e).isSitting()) { teleportingEntities.add(e.getUniqueId()); - HashMap teleportResult = teleportTameable(e, safeLocation, location, executor); + HashMap teleportResult = teleportTameableExperimental(e, safeLocation, location); // If the first entity didn't find a safe location Boolean triedTeleporting = (Boolean) teleportResult.keySet().toArray()[0]; @@ -99,13 +97,13 @@ private void doTeleportEntities(List entities, Location location, Thread } } - // Remember to shut down the executor! - executor.shutdown(); - plugin.logDebug("Shutdown of thread pool initiated! - " + reason); +// // Remember to shut down the executor! +// executor.shutdown(); +// plugin.logDebug("Shutdown of thread pool initiated! - " + reason); } // Experimental function - private HashMap teleportTameable(Entity e, Location safeLocation, Location searchLocation, ThreadPoolExecutor executor) { + private HashMap teleportTameableExperimental(Entity e, Location safeLocation, Location searchLocation) { // We use this map to store whether it even tried searching for a location, and then to return with a safe location, so we don't have to search again HashMap teleportResult = new HashMap<>(); @@ -117,7 +115,7 @@ private HashMap teleportTameable(Entity e, Location safeLocat if (player != null && player.isOnline() && MyDog.getPermissionsManager().hasPermission(player, "mydog.teleport")) { // If it's a dog, or if the config allows all tameables to teleport - Boolean isDog = (e.getType().equals(EntityType.WOLF) && MyDog.getDogManager().isDog(tameableEntity.getUniqueId())); + boolean isDog = (e.getType().equals(EntityType.WOLF) && MyDog.getDogManager().isDog(tameableEntity.getUniqueId())); if (isDog || plugin.teleportAllTameables) { // If the tameable is sitting, or is in another world if (!sittingEntity.isSitting() || (!tameableEntity.getWorld().equals(player.getWorld()) && plugin.teleportOnWorldChange)) { @@ -153,7 +151,7 @@ private HashMap teleportTameable(Entity e, Location safeLocat plugin.logDebug("Teleporting to a safe location! - X:" + safeLocation.getX() + " Y:" + safeLocation.getY() + " Z:" + safeLocation.getZ()); Location finalSafeLocation = safeLocation; - Runnable teleport = new Runnable() { + BukkitRunnable teleport = new BukkitRunnable() { public void run() { boolean teleported = true; @@ -197,8 +195,8 @@ public void run() { } }; - plugin.logDebug("Adding teleport runnable to the executor!"); - executor.execute(teleport); + plugin.logDebug("Adding teleport runnable to the bukkitrunnable!"); + teleport.runTask(this.plugin); // Return the found location teleportResult.put(true, safeLocation); From d33dfc70aa605703196019ce0f4238fe0584c3dd Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 21:20:19 +0200 Subject: [PATCH 08/25] Deny dogs from teleporting through portals, if teleporting is enabled. Closes #50 --- .../mydog/listeners/WolfMainListener.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java index ba5a889..cbb1c70 100644 --- a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java +++ b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java @@ -15,10 +15,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityBreedEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntityTameEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; +import org.bukkit.event.entity.*; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.world.*; @@ -472,4 +469,24 @@ public void onChunkUnload(ChunkUnloadEvent event) { MyDog.getTeleportationManager().doTeleportEntities(entities, null); } } + + // When a dog enters a portal, deny the teleport, since it's annoying + @EventHandler(priority = EventPriority.HIGHEST) + public void onPortalTeleport(EntityPortalEvent event) { + if (!plugin.automaticTeleportation) { + return; + } + + Entity entity = event.getEntity(); + + if (MyDog.getDogManager().isDog(entity.getUniqueId())) { + // Make sure that the portal isn't the end portal... pretty sure there's lava under that lol + if (event.getTo() != null && event.getTo().getWorld() != null) { + if (event.getTo().getWorld().getEnvironment() != World.Environment.THE_END) { + MyDog.instance().logDebug("Stopped a dog from teleporting through a portal."); + event.setCancelled(true); + } + } + } + } } From db47866c39dc674943d5417c52d480c1fe96fc84 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 21:23:02 +0200 Subject: [PATCH 09/25] Closes #60 --- src/main/java/dk/fido2603/mydog/objects/Dog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/dk/fido2603/mydog/objects/Dog.java b/src/main/java/dk/fido2603/mydog/objects/Dog.java index 30cc7ad..bbe5be5 100644 --- a/src/main/java/dk/fido2603/mydog/objects/Dog.java +++ b/src/main/java/dk/fido2603/mydog/objects/Dog.java @@ -75,7 +75,7 @@ public Dog(Wolf dog, Player dogOwner, String customName, DyeColor collarColorImp // Give the Dog a level if (MyDog.instance().useLevels) { - if (level == 0) { + if (level == null || level == 0) { this.level = 1; } else { this.level = level; From c5de5752797e00662d7768a412879b28165410e3 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 21:38:21 +0200 Subject: [PATCH 10/25] Fixes #76 --- .../mydog/managers/TeleportationManager.java | 76 ++++++++++++------- 1 file changed, 48 insertions(+), 28 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java b/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java index da1906f..f2f44f9 100644 --- a/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/TeleportationManager.java @@ -109,7 +109,7 @@ private HashMap teleportTameableExperimental(Entity e, Locati Tameable tameableEntity = (Tameable) e; - if (tameableEntity.getOwner() instanceof Player) { + if (tameableEntity != null && !tameableEntity.isDead() && tameableEntity.getOwner() instanceof Player) { Sittable sittingEntity = (Sittable) e; Player player = (Player) tameableEntity.getOwner(); @@ -157,41 +157,38 @@ public void run() { plugin.logDebug("Teleporting..."); - if (!tameableEntity.teleport(finalSafeLocation)) { - Chunk chunk = tameableEntity.getLocation().getChunk(); - if (!entityChunks.contains(chunk)) { - if (chunk.load(false)) { - plugin.logDebug("Loaded the chunk sucessfully, no generate!"); - entityChunks.add(chunk); - } else if (chunk.load(true)) { - plugin.logDebug("Loaded the chunk sucessfully, generated!"); - entityChunks.add(chunk); - } - - // Try teleporting again - if (!tameableEntity.teleport(finalSafeLocation)) { - teleported = false; + // Load the teleportation location and tameable entity location + Chunk teleportChunk = finalSafeLocation.getChunk(); + if (!teleportChunk.isLoaded()) { + if (teleportChunk.load(false)) { + plugin.logDebug("Loaded the teleportation chunk sucessfully, no generate!"); + } else if (teleportChunk.load(true)) { + plugin.logDebug("Loaded the teleportation chunk sucessfully, generated!"); + } + } + Chunk entityChunk = tameableEntity.getLocation().getChunk(); + if (!entityChunk.isLoaded()) { + if (!entityChunks.contains(entityChunk)) { + if (entityChunk.load(false)) { + plugin.logDebug("Loaded the entity chunk sucessfully, no generate!"); + entityChunks.add(entityChunk); + } else if (entityChunk.load(true)) { + plugin.logDebug("Loaded the entity chunk sucessfully, generated!"); + entityChunks.add(entityChunk); } - } else { - teleported = false; } } + if (!tameableEntity.teleport(finalSafeLocation)) { + teleported = false; + } + // If the entity got teleported if (teleported) { if (sittingEntity.isSitting()) { sittingEntity.setSitting(false); } - - // Sleep - try { - Thread.sleep(1000); - plugin.logDebug("Sleep over!"); - } catch (InterruptedException ex) { - plugin.logDebug("Error in thread!"); - } } - } }; @@ -235,13 +232,13 @@ private HashMap teleportTameable(Entity e, Location safeLocat Tameable tameableEntity = (Tameable) e; - if (tameableEntity.getOwner() instanceof Player) { + if (tameableEntity != null && !tameableEntity.isDead() && tameableEntity.getOwner() instanceof Player) { Sittable sittingEntity = (Sittable) e; Player player = (Player) tameableEntity.getOwner(); if (player != null && player.isOnline() && MyDog.getPermissionsManager().hasPermission(player, "mydog.teleport")) { // If it's a dog, or if the config allows all tameables to teleport - Boolean isDog = (e.getType().equals(EntityType.WOLF) && MyDog.getDogManager().isDog(tameableEntity.getUniqueId())); + boolean isDog = (e.getType().equals(EntityType.WOLF) && MyDog.getDogManager().isDog(tameableEntity.getUniqueId())); if (isDog || plugin.teleportAllTameables) { // If the tameable is sitting, or is in another world if (!sittingEntity.isSitting() || (!tameableEntity.getWorld().equals(player.getWorld()) && plugin.teleportOnWorldChange)) { @@ -270,6 +267,29 @@ private HashMap teleportTameable(Entity e, Location safeLocat } plugin.logDebug("It's a safe location, teleporting!"); + + // Load the teleportation location and tameable entity location + Chunk teleportChunk = safeLocation.getChunk(); + if (!teleportChunk.isLoaded()) { + if (teleportChunk.load(false)) { + plugin.logDebug("Loaded the teleportation chunk sucessfully, no generate!"); + } else if (teleportChunk.load(true)) { + plugin.logDebug("Loaded the teleportation chunk sucessfully, generated!"); + } + } + Chunk entityChunk = tameableEntity.getLocation().getChunk(); + if (!entityChunk.isLoaded()) { + if (!entityChunks.contains(entityChunk)) { + if (entityChunk.load(false)) { + plugin.logDebug("Loaded the entity chunk sucessfully, no generate!"); + entityChunks.add(entityChunk); + } else if (entityChunk.load(true)) { + plugin.logDebug("Loaded the entity chunk sucessfully, generated!"); + entityChunks.add(entityChunk); + } + } + } + tameableEntity.teleport(safeLocation); Dog wolf = MyDog.getDogManager().getDog(tameableEntity.getUniqueId()); From 65ee87c3773ce605837805b306948e9fb1ffa109 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Fri, 26 May 2023 22:11:30 +0200 Subject: [PATCH 11/25] Make it easier to see that you can release dead dogs - closes #77 --- .../mydog/managers/CommandManager.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 5794a72..d3cd5f5 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -112,10 +112,11 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - if ((args[0].equalsIgnoreCase("free")) || (args[0].equalsIgnoreCase("setfree"))) { + if ((args[0].equalsIgnoreCase("free")) || (args[0].equalsIgnoreCase("setfree")) || (args[0].equalsIgnoreCase("release"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.free"))) { return false; } + int dogIdentifier; try { dogIdentifier = Integer.parseInt(args[1]); @@ -265,10 +266,10 @@ private boolean commandList(CommandSender sender) { sender.sendMessage(ChatColor.AQUA + "/mydog list" + ChatColor.WHITE + " - View a list with your current Dogs"); } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.putdown"))) { - sender.sendMessage(ChatColor.AQUA + "/mydog putdown " + ChatColor.WHITE + " - Get rid of a Dog you own"); + sender.sendMessage(ChatColor.AQUA + "/mydog putdown " + ChatColor.WHITE + " - Kills a dog you own"); } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.free"))) { - sender.sendMessage(ChatColor.AQUA + "/mydog free " + ChatColor.WHITE + " - Set one of your Dogs free!"); + sender.sendMessage(ChatColor.AQUA + "/mydog release " + ChatColor.WHITE + " - Set one of your Dogs free!"); } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { sender.sendMessage(ChatColor.AQUA + "/mydog comehere " + ChatColor.WHITE + " - Forces your Dog to teleport to your location"); @@ -430,6 +431,7 @@ private boolean commandDogPutdown(CommandSender sender, int dogIdentifier) { private boolean commandDogFree(CommandSender sender, int dogIdentifier) { Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); + if (dog == null) { sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); return false; @@ -706,15 +708,18 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.putdown"))) { arg1.add("putdown"); + arg1.add("kill"); } if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { arg1.add("comehere"); } if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { arg1.add("info"); + arg1.add("stats"); } if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.free"))) { arg1.add("free"); + arg1.add("release"); } if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.rename"))) { arg1.add("rename"); @@ -743,13 +748,20 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("comehere") || args[0].equalsIgnoreCase("free") || args[0].equalsIgnoreCase("setfree") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("setid") || args[0].equalsIgnoreCase("stats"))) { + if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("comehere") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("stats"))) { List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); } } + if (player != null && (args[0].equalsIgnoreCase("release") || args[0].equalsIgnoreCase("free") || args[0].equalsIgnoreCase("setfree") || args[0].equalsIgnoreCase("setid"))) { + List dogs = MyDog.getDogManager().getDogs(player.getUniqueId()); + for (Dog dog : dogs) { + arg2.add(Integer.toString(dog.getIdentifier())); + } + } + if (player != null && ((plugin.allowRevival && args[0].equalsIgnoreCase("revive")))) { List dogs = MyDog.getDogManager().getDeadDogs(player.getUniqueId()); for (Dog dog : dogs) { From bd14aba5c0a4bc2fc6ff6934444a0dd6e6d292d7 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:06:49 +0200 Subject: [PATCH 12/25] Update README --- .travis.yml | 32 ++++++++++++-------------------- README.md | 12 ++++++------ 2 files changed, 18 insertions(+), 26 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9e5e879..a1dc162 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,28 +5,20 @@ before_install: - echo "Setting project environment variable." - export TRAVIS_REPO_OWNER=${TRAVIS_REPO_SLUG%/*} - export TRAVIS_REPO_NAME=${TRAVIS_REPO_SLUG#*/} -deploy: - provider: releases - api-key: - secure: ORbcFGH2yOAsutJzOzh62hAeC12kV935ctL1Gg6MvsoSOaRBasoQkDdGRfm6NVi2rYIsEBDR3vAYplF3AOiU6/7W4vqSFDm5xp2G4Mf2xg0wSRvWQR57SJ4CJopa6ZTYQGUQJ4MklDSUnZcOLA/SGrmoOG7ioRITs0LFvn9lS3vAO35RH030DfPSW4Luy5+FKlDubulUJPlYn0cr5N+00wYOifOwee5BAdM6ajm/LgZItaGWfZuNUI0iQwCutcLPWQrI0RXO+wpDv8XqEQoaIhyAPCEcuZSrzt0ltVVFkW5YtNcWKgEAJdh4LYZSyWQCqZlzSLTqbMqvQ9RrxVeY3mNAPcuxrf3yt5nRqshRZdcTA1OX2uMKNPFfrB6CkEhAm+Cy9yD62EPM24t24Q+8mLMm+x0jJ1ZJtTOcC+gq3yC86b57OS2BaytbEWHE/u915XnMpl5HjdauTc8QbuzDMxqRWnumDX2eEg35ZDldZ7OsOg4by9eE221BQlhHM8t820Oj0byCPDvIpITNaBjeOihq9xVO7BIaR+kt/0txB1kjHgCMLtA45GaRRIDG2VfMY9kVVcVlrT/7xf3xgL7ktYQNi9roQaxzJ5gInWcpecpqG54Ncf4dQtMXW+Gwl4pCJYJEJNz5ciptdqqfDJ9Je4nApaMnAIJJ7tGc6/HLV0E= - file_glob: true - file: target/MyDog-*.jar - skip_cleanup: true - on: - repo: DoggyCraftDK/MyDog - tags: true +#deploy: +# provider: releases +# api-key: +# secure: +# file_glob: true +# file: target/MyDog-*.jar +# skip_cleanup: true +# on: +# repo: HeroGamers/MyDog +# tags: true sudo: false -after_success: - - wget https://www.doggycraft.dk/travis/send.sh - - chmod +x send.sh - - ./send.sh success $WEBHOOK_URL -after_failure: - - wget https://www.doggycraft.dk/travis/send.sh - - chmod +x send.sh - - ./send.sh failure $WEBHOOK_URL addons: sonarcloud: - organization: "doggycraftdk" + organization: "herogamers" script: - - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install sonar:sonar -Dsonar.projectKey=DoggyCraftDK_MyDog \ No newline at end of file + - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install sonar:sonar -Dsonar.projectKey=HeroGamers_MyDog \ No newline at end of file diff --git a/README.md b/README.md index bce3084..4c77f0f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@

MyDog

-[![Build Status](https://travis-ci.com/DoggyCraftDK/MyDog.svg?branch=master)](https://travis-ci.com/DoggyCraftDK/MyDog) -[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=DoggyCraftDK_MyDog&metric=alert_status)](https://sonarcloud.io/dashboard?id=DoggyCraftDK_MyDog) -[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=DoggyCraftDK_MyDog&metric=ncloc)](https://sonarcloud.io/dashboard?id=DoggyCraftDK_MyDog) -[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=DoggyCraftDK_MyDog&metric=bugs)](https://sonarcloud.io/dashboard?id=DoggyCraftDK_MyDog) -[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=DoggyCraftDK_MyDog&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=DoggyCraftDK_MyDog) -[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=DoggyCraftDK_MyDog&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=DoggyCraftDK_MyDog) +[![Maven Test](https://github.com/HeroGamers/MyDog/actions/workflows/maven-test.yml/badge.svg)](https://github.com/HeroGamers/MyDog/actions/workflows/maven-test.yml) +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=HeroGamers_MyDog&metric=alert_status)](https://sonarcloud.io/dashboard?id=HeroGamers_MyDog) +[![Lines of Code](https://sonarcloud.io/api/project_badges/measure?project=HeroGamers_MyDog&metric=ncloc)](https://sonarcloud.io/dashboard?id=HeroGamers_MyDog) +[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=HeroGamers_MyDog&metric=bugs)](https://sonarcloud.io/dashboard?id=HeroGamers_MyDog) +[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=HeroGamers_MyDog&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=HeroGamers_MyDog) +[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=HeroGamers_MyDog&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=HeroGamers_MyDog)
Tamed wolves but at least 10x better. From 8af3661bec0edb1d88f63e74ab35cd90ea61b0d7 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:06:56 +0200 Subject: [PATCH 13/25] Update README --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4c77f0f..b02dc84 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,10 @@ ___ * The ability to add currently existing Tamed Wolves to the MyDog system, and register them as new Dogs (interact with them). * Configurable all the way from the sound on LevelUp to the messages displayed (excluding error messages for now...) -### TODO Feature-list -* Add inventory to Dogs, so they can wear armor and take less damage. -* Config with customizable experience values for entities. -* For the full list, visit the [TODO list](https://github.com/DoggyCraftDK/MyDog/projects/1). +### ToDo Feature-list +To view the list of features, please visit the [project page](https://github.com/users/HeroGamers/projects/1). + +For new feature requests, please open a GitHub Issue. ## Resources * Resource page on [Spigot](https://www.spigotmc.org/resources/mydog.70260/). From 8c179926fe146419ad35e20947e856d3889671bf Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:19:17 +0200 Subject: [PATCH 14/25] Add issue templates - kudos to EssentialsX as I used that for inspiration --- .github/ISSUE_TEMPLATE/config.yml | 5 ++ .github/ISSUE_TEMPLATE/report-a-bug.yml | 72 ++++++++++++++++++++ .github/ISSUE_TEMPLATE/request-a-feature.yml | 39 +++++++++++ 3 files changed, 116 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/report-a-bug.yml create mode 100644 .github/ISSUE_TEMPLATE/request-a-feature.yml diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..bb49bfc --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Discord Server + url: discord.gg/PvFPEfd + about: Personal Discord server, but you are welcome to join to discuss features or bugs. diff --git a/.github/ISSUE_TEMPLATE/report-a-bug.yml b/.github/ISSUE_TEMPLATE/report-a-bug.yml new file mode 100644 index 0000000..7954260 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/report-a-bug.yml @@ -0,0 +1,72 @@ +name: Report bug +description: Report a bug in MyDog. +labels: 'bug' +body: +- type: markdown + attributes: + value: | + Thanks for taking the time to report a MyDog bug! Fill out the form below to provide us with info to help fix the bug. + Only use this if you're 100% sure you've found a bug and can reproduce it. If you're looking for general help with MyDog, try reaching out to me on Discord or Spigot's Discord Server. +- type: dropdown + attributes: + label: Type of bug + description: What type of bug is this? Choose all that apply. + multiple: true + options: + - Performance issue or memory leak + - Data loss + - Exploit + - Compatibility issue + - Error in console + - Other unexpected behaviour + validations: + required: true + +- type: input + attributes: + label: Error log (if applicable) + description: If you are reporting a console error, upload any relevant log excerpts to either https://paste.gg or https://gist.github.com, save and the paste the link in this box. If you included those files in the same paste as your startup log, paste the same link here. + placeholder: "Example: https://paste.gg/p/anonymous/742cfe1a62b14a3fa34c566fb441c457" + +- type: textarea + attributes: + label: Bug description + description: Describe roughly what the bug is here. + placeholder: | + Example: "When running `/md revive` the dog is still not revived..." + validations: + required: true +- type: textarea + attributes: + label: Steps to reproduce + description: Provide an example of how to trigger the bug. + placeholder: | + Example: + 1. Get a dog + 2. Have the dog die (ohno) + 3. Run `/md revive` + validations: + required: true +- type: textarea + attributes: + label: Expected behaviour + description: Explain what you should expect to happen. + placeholder: | + Example: "The good boy should appear again!" + validations: + required: true +- type: textarea + attributes: + label: Actual behaviour + description: Explain what actually happens. + placeholder: | + Example: "The good boy is still gone :(" + validations: + required: true + +- type: markdown + attributes: + value: | + In the text box below, you can attach any relevant screenshots, files and links to Timings/spark profiler reports. + You can also include a link to a heapdump if necessary, but please make sure you don't include any private player data in the heapdump. + If you suspect this issue is related to a prior issue/PR/commit, please mention it here. diff --git a/.github/ISSUE_TEMPLATE/request-a-feature.yml b/.github/ISSUE_TEMPLATE/request-a-feature.yml new file mode 100644 index 0000000..a48776e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/request-a-feature.yml @@ -0,0 +1,39 @@ +name: Request a feature +description: Suggest a feature you want to see in MyDog! +labels: 'enhancement' +body: +- type: markdown + attributes: + value: | + If you have a feature suggestion for MyDog, read the following tips: + 1. Fill out the template. + This will help us understand what you're requesting and why you want us + to add it. + 2. Keep it simple. + Make sure it's easy to understand what you're requesting. A good way is + to keep it to one request per GitHub issue, as we can then easily track + feature requests. + 3. Check whether it has already been asked or added. + You can search the issue tracker to see if your feature has already been + requested at https://github.com/HeroGamers/MyDog/issues. You can + also check the changelogs to see if the feature was recently added: + https://github.com/HeroGamers/MyDog/releases + 4. Ask yourself: "Does this belong in MyDog?" + If your feature is very specific or already exists in another plugin, + it might not be a good fit for MyDog. +- type: textarea + attributes: + label: Feature description + description: Explain what you should expect to happen. + placeholder: | + What feature are you suggesting? + validations: + required: true +- type: textarea + attributes: + label: How the feature is useful + description: Explain what actually happens. + placeholder: | + How is the feature useful to players, server owners and/or developers? + validations: + required: true From 5d1e3ca47524f6805fdb4a581edd32e768c49fb1 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:20:07 +0200 Subject: [PATCH 15/25] Forgot to change the issues link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b02dc84..29152e4 100644 --- a/README.md +++ b/README.md @@ -76,4 +76,4 @@ mydog.save: ``` ## Bug reports and issues -Visit the [Issues Tab](https://github.com/DoggyCraftDK/MyDog/issues). +Visit the [Issues Tab](https://github.com/HeroGamers/MyDog/issues). From b88748bda537285cd522485bcc80546c7d2f6e54 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:39:09 +0200 Subject: [PATCH 16/25] Add a sit and stand command - closes #22 --- .../mydog/managers/CommandManager.java | 185 ++++++++++++++---- 1 file changed, 144 insertions(+), 41 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index d3cd5f5..7b4a6ed 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -34,8 +34,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String if ((cmd.getName().equalsIgnoreCase("mydog")) || (cmd.getName().equalsIgnoreCase("md")) || (cmd.getName().equalsIgnoreCase("dog")) || (cmd.getName().equalsIgnoreCase("dogs"))) { if ((args.length == 0) && (player != null)) { - commandHelp(sender); - return true; + return commandHelp(sender); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("reload")) { if (player == null) { @@ -74,26 +73,21 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return false; } - commandList(sender); - - return true; + return commandList(sender); } if (((args[0].equalsIgnoreCase("dogs")) || (args[0].equalsIgnoreCase("list"))) && (player != null)) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.dogs"))) { return false; } - commandDogList(sender); - - return true; + return commandDogList(sender); } if (args[0].equalsIgnoreCase("dead") && (player != null)) { if (!plugin.allowRevival || ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { return false; } - commandDogDead(sender); - return true; + return commandDogDead(sender); } } else if ((args.length == 2) && (player != null)) { if ((args[0].equalsIgnoreCase("putdown")) || (args[0].equalsIgnoreCase("kill"))) { @@ -108,9 +102,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandDogPutdown(sender, dogIdentifier); - - return true; + return commandDogPutdown(sender, dogIdentifier); } if ((args[0].equalsIgnoreCase("free")) || (args[0].equalsIgnoreCase("setfree")) || (args[0].equalsIgnoreCase("release"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.free"))) { @@ -125,9 +117,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandDogFree(sender, dogIdentifier); - - return true; + return commandDogFree(sender, dogIdentifier); } if ((args[0].equalsIgnoreCase("stats")) || (args[0].equalsIgnoreCase("info"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { @@ -141,9 +131,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandDogStats(sender, dogIdentifier); - - return true; + return commandDogStats(sender, dogIdentifier); } if ((args[0].equalsIgnoreCase("comehere"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { @@ -157,9 +145,47 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandDogComehere(sender, dogIdentifier); + return commandDogComehere(sender, dogIdentifier); + } + if ((args[0].equalsIgnoreCase("sit"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { + return false; + } - return true; + int dogIdentifier; + if (args[1].equalsIgnoreCase("all")) { + dogIdentifier = -1; + } + else { + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + } + + return commandDogSit(sender, dogIdentifier); + } + if ((args[0].equalsIgnoreCase("stand"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { + return false; + } + + int dogIdentifier; + if (args[1].equalsIgnoreCase("all")) { + dogIdentifier = -1; + } + else { + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + } + + return commandDogStand(sender, dogIdentifier); } if ((args[0].equalsIgnoreCase("revive"))) { if (!plugin.allowRevival || ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.revive")))) { @@ -177,9 +203,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandReviveDog(player, sender, dogIdentifier); - - return true; + return commandReviveDog(player, sender, dogIdentifier); } } else if ((args.length >= 3) && (player != null)) { if ((args[0].equalsIgnoreCase("editlevel"))) { @@ -198,18 +222,14 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - commandEditLevel(sender, dogIdentifier, dogLevel); - - return true; + return commandEditLevel(sender, dogIdentifier, dogLevel); } if ((args[0].equalsIgnoreCase("setid")) || (args[0].equalsIgnoreCase("changeid"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.setid"))) { return false; } - commandDogSetId(sender, args); - - return true; + return commandDogSetId(sender, args); } if ((args[0].equalsIgnoreCase("rename"))) { @@ -217,9 +237,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return false; } - commandDogRename(sender, args); - - return true; + return commandDogRename(sender, args); } sender.sendMessage(ChatColor.RED + "Too many arguments! Check /mydog help"); return true; @@ -233,7 +251,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String private boolean commandHelp(CommandSender sender) { sender.sendMessage(ChatColor.YELLOW + "---------------- " + plugin.getDescription().getFullName() + " ----------------"); - sender.sendMessage(ChatColor.AQUA + "By Fido2603 / HeroGamers"); + sender.sendMessage(ChatColor.AQUA + "By HeroGamers (Fido2603)"); sender.sendMessage(ChatColor.AQUA + ""); int dogsOwned = MyDog.getDogManager().dogsOwned((Player) sender); String dogs = " dogs!"; @@ -274,6 +292,10 @@ private boolean commandList(CommandSender sender) { if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { sender.sendMessage(ChatColor.AQUA + "/mydog comehere " + ChatColor.WHITE + " - Forces your Dog to teleport to your location"); } + if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { + sender.sendMessage(ChatColor.AQUA + "/mydog sit " + ChatColor.WHITE + " - Tells your dog(s) to sit and keep their position(s)"); + sender.sendMessage(ChatColor.AQUA + "/mydog stand " + ChatColor.WHITE + " - Tells your dog(s) to stand up and roam free"); + } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { sender.sendMessage(ChatColor.AQUA + "/mydog info " + ChatColor.WHITE + " - Gets stats and other info about a Dog you own"); } @@ -284,13 +306,13 @@ private boolean commandList(CommandSender sender) { sender.sendMessage(ChatColor.AQUA + "/mydog setid " + ChatColor.WHITE + " - Assigns a custom ID to a Dog you own"); } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.editlevel"))) { - sender.sendMessage(ChatColor.AQUA + "/mydog setlevel " + ChatColor.WHITE + " - Sets a dog's level"); + sender.sendMessage(ChatColor.AQUA + "/mydog setlevel " + ChatColor.WHITE + " - Sets a dog's level"); } if (plugin.allowRevival && ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { sender.sendMessage(ChatColor.AQUA + "/mydog dead" + ChatColor.WHITE + " - List of Dogs that have gone to another world"); } if (plugin.allowRevival && ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.revive")))) { - sender.sendMessage(ChatColor.AQUA + "/mydog revive " + ChatColor.WHITE + " - Resurrects a Dog for a fee"); + sender.sendMessage(ChatColor.AQUA + "/mydog revive " + ChatColor.WHITE + " - Resurrects a Dog for a fee"); } } @@ -455,6 +477,81 @@ private boolean commandDogFree(CommandSender sender, int dogIdentifier) { return true; } + private boolean commandDogStand(CommandSender sender, int dogIdentifier) { + if (dogIdentifier > 0) { + Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); + + if (dog == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); + return false; + } + + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, " + dog.getDogColor() + dog.getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + + if (wolf != null) { + wolf.setSitting(false); + } + } + else if (dogIdentifier == -1) { + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, my dogs!"); + + List dogs = MyDog.getDogManager().getDogs(((Player) sender).getUniqueId()); + + for (Dog dog : dogs) { + if (dog != null) { + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + + if (wolf != null) { + wolf.setSitting(false); + } + } + } + } + + return true; + } + + private boolean commandDogSit(CommandSender sender, int dogIdentifier) { + if (dogIdentifier > 0) { + Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); + + if (dog == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); + return false; + } + + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, " + dog.getDogColor() + dog.getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + + if (wolf != null) { + wolf.setSitting(true); + } + } + else if (dogIdentifier == -1) { + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, my dogs!"); + + List dogs = MyDog.getDogManager().getDogs(((Player) sender).getUniqueId()); + + for (Dog dog : dogs) { + if (dog != null) { + Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + + if (wolf != null) { + wolf.setSitting(true); + } + } + } + } + else { + return false; + } + + return true; + } + private boolean commandDogStats(CommandSender sender, int dogIdentifier) { Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); if (dog == null) { @@ -727,6 +824,10 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.setid"))) { arg1.add("setid"); } + if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { + arg1.add("sit"); + arg1.add("stand"); + } if (plugin.allowRevival && (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { arg1.add("dead"); } @@ -741,7 +842,7 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } else if (args.length == 2) { List arg2 = new ArrayList<>(); - if (player != null && (args[0].equalsIgnoreCase("setlevel"))) { + if (player != null && (args[0].equalsIgnoreCase("setlevel") || args[0].equalsIgnoreCase("release") || args[0].equalsIgnoreCase("free") || args[0].equalsIgnoreCase("setfree") || args[0].equalsIgnoreCase("setid"))) { List dogs = MyDog.getDogManager().getDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); @@ -755,15 +856,17 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("release") || args[0].equalsIgnoreCase("free") || args[0].equalsIgnoreCase("setfree") || args[0].equalsIgnoreCase("setid"))) { - List dogs = MyDog.getDogManager().getDogs(player.getUniqueId()); + if (player != null && ((plugin.allowRevival && args[0].equalsIgnoreCase("revive")))) { + List dogs = MyDog.getDogManager().getDeadDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); } } - if (player != null && ((plugin.allowRevival && args[0].equalsIgnoreCase("revive")))) { - List dogs = MyDog.getDogManager().getDeadDogs(player.getUniqueId()); + if (player != null && (args[0].equalsIgnoreCase("sit") || args[0].equalsIgnoreCase("stand"))) { + arg2.add("all"); + + List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); } From 083b26910b4228ae4af562111897d0f60f783e42 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 00:57:14 +0200 Subject: [PATCH 17/25] Add Sonar to GitHub Actions CI --- .github/workflows/maven-publish.yml | 4 +- .github/workflows/maven-test.yml | 69 ++++++++++++++++++++++++----- pom.xml | 7 +-- 3 files changed, 61 insertions(+), 19 deletions(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index eabd9e1..59a01d1 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -15,10 +15,10 @@ jobs: packages: write steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Set up JDK 8 - uses: actions/setup-java@v2 + uses: actions/setup-java@v3 with: java-version: '8' distribution: 'adopt' diff --git a/.github/workflows/maven-test.yml b/.github/workflows/maven-test.yml index df2ecf0..58110a2 100644 --- a/.github/workflows/maven-test.yml +++ b/.github/workflows/maven-test.yml @@ -3,10 +3,48 @@ name: Maven Test on: - push + push: + branches: + - master + - dev + pull_request: + types: [ opened, synchronize, reopened ] jobs: build: + name: Build and analyze + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: 17 + cache: 'maven' + server-id: github # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Cache SonarCloud packages + uses: actions/cache@v3 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + - name: Cache Maven packages + uses: actions/cache@v3 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + + - name: Build with Maven and analyze + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=HeroGamers_MyDog --file pom.xml + + compatability: runs-on: ubuntu-latest permissions: contents: read @@ -17,15 +55,22 @@ jobs: name: Java ${{ matrix.java }} build steps: - - uses: actions/checkout@v2 - - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v2 - with: - distribution: 'zulu' - java-version: ${{ matrix.java }} - cache: 'maven' - server-id: github # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file + - uses: actions/checkout@v3 + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: ${{ matrix.java }} + cache: 'maven' + server-id: github # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Cache Maven packages + uses: actions/cache@v3 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 - - name: Build with Maven - run: mvn -B test --file pom.xml + - name: Build with Maven + run: mvn -B verify --file pom.xml \ No newline at end of file diff --git a/pom.xml b/pom.xml index 572250b..40b0cf0 100644 --- a/pom.xml +++ b/pom.xml @@ -26,11 +26,8 @@ ${encoding} - http://localhost:9000/ - - ${dependency.check.report.dir}/dependency-check-report.xml - - ${dependency.check.report.dir}/dependency-check-report.html + herogamers + https://sonarcloud.io
From 2fbf4afe951f94980af6591a575eab4c7fa0e70c Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 01:11:01 +0200 Subject: [PATCH 18/25] Revive using levels, closes #79 --- src/main/java/dk/fido2603/mydog/MyDog.java | 3 +++ .../mydog/managers/CommandManager.java | 20 ++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/MyDog.java b/src/main/java/dk/fido2603/mydog/MyDog.java index 8fe31ec..baf30ea 100644 --- a/src/main/java/dk/fido2603/mydog/MyDog.java +++ b/src/main/java/dk/fido2603/mydog/MyDog.java @@ -56,6 +56,7 @@ public class MyDog extends JavaPlugin { public boolean allowNametagRename = true; public boolean allowRevival = true; public int revivalPrice = 200; + public boolean revivalUsingPlayerExp = true; public boolean allowArrowDamage = false; public String levelUpSound = "ENTITY_WOLF_HOWL"; @@ -288,6 +289,7 @@ public void loadSettings() { this.allowNametagRename = config.getBoolean("DogSettings.AllowNametagRename", true); this.allowRevival = config.getBoolean("DogSettings.AllowRevival", true); this.revivalPrice = config.getInt("DogSettings.RevivalPricePerLevel", 200); + this.revivalUsingPlayerExp = config.getBoolean("DogSettings.RevivalUsingPlayerExp", false); this.allowArrowDamage = config.getBoolean("DogSettings.AllowArrowDamage", false); if (config.contains("DogSettings.DogNames") && !config.getStringList("DogSettings.DogNames").isEmpty()) { this.dogNames = config.getStringList("DogSettings.DogNames"); @@ -354,6 +356,7 @@ public void saveSettings() { config.set("DogSettings.DogNames", this.dogNames); config.set("DogSettings.AllowRevival", this.allowRevival); config.set("DogSettings.RevivalPricePerLevel", this.revivalPrice); + config.set("DogSettings.RevivalUsingPlayerExp", this.revivalUsingPlayerExp); config.set("DogSettings.AllowArrowDamage", this.allowArrowDamage); // Levels diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 7b4a6ed..11a9a26 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -678,12 +678,22 @@ private boolean commandReviveDog(Player player, CommandSender sender, int dogIde return false; } - if (MyDog.getEconomy() != null) { - if (!MyDog.getEconomy().has(player, deadDog.getRevivalPrice())) { - sender.sendMessage(ChatColor.RED + "You don't have enough funds to resurrect the dog."); + int revivalPrice = deadDog.getRevivalPrice(); + if (!plugin.revivalUsingPlayerExp) { + if (MyDog.getEconomy() != null) { + if (!MyDog.getEconomy().has(player, revivalPrice)) { + sender.sendMessage(ChatColor.RED + "You don't have enough funds to resurrect the dog."); + return false; + } + MyDog.getEconomy().withdrawPlayer(player, revivalPrice); + } + } + else { + if (player.getLevel() < revivalPrice) { + sender.sendMessage(ChatColor.RED + "You don't have enough power to resurrect the dog. You need " + ChatColor.GOLD + (revivalPrice - player.getLevel()) + ChatColor.RED + " more levels!"); return false; } - MyDog.getEconomy().withdrawPlayer(player, deadDog.getRevivalPrice()); + player.setLevel(player.getLevel() - revivalPrice); } Wolf wolf = player.getWorld().spawn(player.getLocation(), Wolf.class); @@ -695,7 +705,7 @@ private boolean commandReviveDog(Player player, CommandSender sender, int dogIde deadDog.setDead(false); deadDog.updateWolf(); - sender.sendMessage(ChatColor.GREEN + "Your dog is resurrected."); + sender.sendMessage(ChatColor.GREEN + "Your dog has been resurrected."); return true; } From df58af85b2251675840729aaa2a6f6e6e7a22bec Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 19:07:33 +0200 Subject: [PATCH 19/25] Add lifesteal and fix setlevel command; closes #59 --- src/main/java/dk/fido2603/mydog/MyDog.java | 3 ++ .../mydog/listeners/DamageListener.java | 54 +++++++++++++++++++ .../mydog/managers/CommandManager.java | 2 +- 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/main/java/dk/fido2603/mydog/MyDog.java b/src/main/java/dk/fido2603/mydog/MyDog.java index baf30ea..52ba842 100644 --- a/src/main/java/dk/fido2603/mydog/MyDog.java +++ b/src/main/java/dk/fido2603/mydog/MyDog.java @@ -58,6 +58,7 @@ public class MyDog extends JavaPlugin { public int revivalPrice = 200; public boolean revivalUsingPlayerExp = true; public boolean allowArrowDamage = false; + public double lifesteal = 0.25D; public String levelUpSound = "ENTITY_WOLF_HOWL"; public String levelUpString = "&5&l[{chatPrefix}] &r&5Your dog, {dogNameColor}{dogName}&5, just leveled up to &dLevel {level}&5!"; @@ -291,6 +292,7 @@ public void loadSettings() { this.revivalPrice = config.getInt("DogSettings.RevivalPricePerLevel", 200); this.revivalUsingPlayerExp = config.getBoolean("DogSettings.RevivalUsingPlayerExp", false); this.allowArrowDamage = config.getBoolean("DogSettings.AllowArrowDamage", false); + this.lifesteal = config.getDouble("DogSettings.Lifesteal", 0.25D); if (config.contains("DogSettings.DogNames") && !config.getStringList("DogSettings.DogNames").isEmpty()) { this.dogNames = config.getStringList("DogSettings.DogNames"); } @@ -358,6 +360,7 @@ public void saveSettings() { config.set("DogSettings.RevivalPricePerLevel", this.revivalPrice); config.set("DogSettings.RevivalUsingPlayerExp", this.revivalUsingPlayerExp); config.set("DogSettings.AllowArrowDamage", this.allowArrowDamage); + config.set("DogSettings.Lifesteal", this.lifesteal); // Levels for (Integer level : this.dogLevels.keySet()) { diff --git a/src/main/java/dk/fido2603/mydog/listeners/DamageListener.java b/src/main/java/dk/fido2603/mydog/listeners/DamageListener.java index 7d54fe8..f55824e 100644 --- a/src/main/java/dk/fido2603/mydog/listeners/DamageListener.java +++ b/src/main/java/dk/fido2603/mydog/listeners/DamageListener.java @@ -3,10 +3,14 @@ import dk.fido2603.mydog.MyDog; import dk.fido2603.mydog.objects.Dog; +import dk.fido2603.mydog.objects.LevelFactory; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; @@ -37,6 +41,56 @@ public void onWolfEntityDamage(EntityDamageByEntityEvent e) { // TODO something with a Dog's equipped armor to lower damage caused } + @EventHandler(priority = EventPriority.LOWEST) + public void onWolfEntityDamage2(EntityDamageByEntityEvent e) { + if (e.getDamager().getType() != EntityType.WOLF || !(MyDog.getDogManager().isDog(e.getDamager().getUniqueId())) || plugin.lifesteal == 0.0D) { + return; + } + + if (e.getFinalDamage() > 0) { + double healthPoints = e.getFinalDamage() * plugin.lifesteal; + + if (healthPoints > 0) { + plugin.logDebug("Lifesteal event, dog stole " + healthPoints + " health!"); + + Wolf wolf = (Wolf) e.getDamager(); + Dog dog = MyDog.getDogManager().getDog(wolf.getUniqueId()); + + int dogsLevel = dog.getLevel(); + if (dogsLevel < 1) { + plugin.logDebug("Level was under 1, setting level to 1"); + dogsLevel = 1; + } + + LevelFactory.Level level = plugin.dogLevels.get(dogsLevel); + if (level == null) { + plugin.logDebug("Level object is null, returning!"); + return; + } + + double health = level.health; + if (health < 10.0) { + health = 10.0; + } + + AttributeInstance wolfMaxHealth = wolf.getAttribute(Attribute.GENERIC_MAX_HEALTH); + + if (wolfMaxHealth.getValue() != health) { + wolfMaxHealth.setBaseValue(health); + } + + if (wolf.getHealth() < health) { + if (wolf.getHealth() + healthPoints > health) { + wolf.setHealth(health); + } else { + wolf.setHealth(wolf.getHealth() + healthPoints); + } + plugin.logDebug("Gave the dog, " + dog.getDogName() + ", " + healthPoints + " in health."); + } + } + } + } + @EventHandler public void onEntityDeath(EntityDamageEvent event) { if (event instanceof EntityDamageByEntityEvent) { diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 11a9a26..122487e 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -206,7 +206,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return commandReviveDog(player, sender, dogIdentifier); } } else if ((args.length >= 3) && (player != null)) { - if ((args[0].equalsIgnoreCase("editlevel"))) { + if ((args[0].equalsIgnoreCase("editlevel") || args[0].equalsIgnoreCase("setlevel"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.editlevel"))) { return false; } From 94d235d28a11966f2a466e9be82189c73a495c0a Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sat, 27 May 2023 19:15:24 +0200 Subject: [PATCH 20/25] Expand comehere command to be able to affect all dogs; closes #51 --- .../mydog/managers/CommandManager.java | 167 +++++++++--------- 1 file changed, 82 insertions(+), 85 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 122487e..4a824da 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -137,12 +137,18 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { return false; } + int dogIdentifier; - try { - dogIdentifier = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { - sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); - return true; + if (args[1].equalsIgnoreCase("all")) { + dogIdentifier = -1; + } + else { + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } } return commandDogComehere(sender, dogIdentifier); @@ -478,9 +484,16 @@ private boolean commandDogFree(CommandSender sender, int dogIdentifier) { } private boolean commandDogStand(CommandSender sender, int dogIdentifier) { - if (dogIdentifier > 0) { - Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); + List dogs = new ArrayList<>(); + if (dogIdentifier == -1) { + dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); + } + else { + dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); + } + + for (Dog dog : dogs) { if (dog == null) { sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); return false; @@ -494,29 +507,21 @@ private boolean commandDogStand(CommandSender sender, int dogIdentifier) { wolf.setSitting(false); } } - else if (dogIdentifier == -1) { - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, my dogs!"); - - List dogs = MyDog.getDogManager().getDogs(((Player) sender).getUniqueId()); - - for (Dog dog : dogs) { - if (dog != null) { - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - - if (wolf != null) { - wolf.setSitting(false); - } - } - } - } return true; } private boolean commandDogSit(CommandSender sender, int dogIdentifier) { - if (dogIdentifier > 0) { - Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); + List dogs = new ArrayList<>(); + if (dogIdentifier == -1) { + dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); + } + else { + dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); + } + + for (Dog dog : dogs) { if (dog == null) { sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); return false; @@ -530,24 +535,6 @@ private boolean commandDogSit(CommandSender sender, int dogIdentifier) { wolf.setSitting(true); } } - else if (dogIdentifier == -1) { - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, my dogs!"); - - List dogs = MyDog.getDogManager().getDogs(((Player) sender).getUniqueId()); - - for (Dog dog : dogs) { - if (dog != null) { - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - - if (wolf != null) { - wolf.setSitting(true); - } - } - } - } - else { - return false; - } return true; } @@ -710,60 +697,70 @@ private boolean commandReviveDog(Player player, CommandSender sender, int dogIde } private boolean commandDogComehere(CommandSender sender, int dogIdentifier) { - Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); - if (dog == null) { - sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + - ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); - return false; - } + List dogs = new ArrayList<>(); - Wolf wolf = null; + if (dogIdentifier == -1) { + dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); + } + else { + dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); + } - Location dogLocation = dog.getDogLocation(); - Boolean useLocation = false; - if (dogLocation == null) { - wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - if (wolf == null) { - sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + - ChatColor.RED + "Aww bonkers! Seems like your Dog cannot be found... Sorry about that!"); + for (Dog dog : dogs) { + if (dog == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + + ChatColor.RESET + ChatColor.RED + "Could not find a Dog with that ID! Check /mydog dogs"); return false; } - } else { - if (dogLocation.getChunk().load(false)) { - plugin.logDebug("Loaded the chunk sucessfully, no generate!"); - } else if (dogLocation.getChunk().load(true)) { - plugin.logDebug("Loaded the chunk sucessfully, generated!"); + + Wolf wolf = null; + + Location dogLocation = dog.getDogLocation(); + Boolean useLocation = false; + if (dogLocation == null) { + wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + if (wolf == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + + ChatColor.RED + "Aww bonkers! Seems like your Dog cannot be found... Sorry about that!"); + return false; + } } else { - sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + - ChatColor.RED + "Aww bonkers! Seems like your Dog is at a location that cannot be loaded right now!"); - return false; + if (dogLocation.getChunk().load(false)) { + plugin.logDebug("Loaded the chunk sucessfully, no generate!"); + } else if (dogLocation.getChunk().load(true)) { + plugin.logDebug("Loaded the chunk sucessfully, generated!"); + } else { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + + ChatColor.RED + "Aww bonkers! Seems like your Dog is at a location that cannot be loaded right now!"); + return false; + } + useLocation = true; } - useLocation = true; - } - wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - if (wolf == null) { - sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + - ChatColor.RED + "Aww bonkers! Seems like your Dog cannot be found..."); - plugin.logDebug("Could not find Dog, even though chunks should be loaded..."); - return false; - } + if (wolf == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + + ChatColor.RED + "Aww bonkers! Seems like your Dog cannot be found..."); + plugin.logDebug("Could not find Dog, even though chunks should be loaded..."); + return false; + } - Location playerLoc = ((Player) sender).getLocation(); - wolf.teleport(playerLoc); - wolf.setSitting(false); + Location playerLoc = ((Player) sender).getLocation(); + wolf.teleport(playerLoc); + wolf.setSitting(false); - String comehereString = plugin.commandComehereString.replace("{chatPrefix}", plugin.getChatPrefix()).replace("{dogNameColor}", "&" + dog.getDogColor().getChar()).replace("{dogName}", dog.getDogName()); - sender.sendMessage(ChatColor.translateAlternateColorCodes('&', comehereString)); - /*sender.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + + String comehereString = plugin.commandComehereString.replace("{chatPrefix}", plugin.getChatPrefix()).replace("{dogNameColor}", "&" + dog.getDogColor().getChar()).replace("{dogName}", dog.getDogName()); + sender.sendMessage(ChatColor.translateAlternateColorCodes('&', comehereString)); + /*sender.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.GOLD + "Come here! Good doggo, " + dog.getDogName() + "!");*/ - dog.updateWolf(); + dog.updateWolf(); - if (useLocation) { - dogLocation.getChunk().unload(true); - plugin.logDebug("Unloaded the chunk sucessfully!"); + if (useLocation) { + dogLocation.getChunk().unload(true); + plugin.logDebug("Unloaded the chunk sucessfully!"); + } } return true; @@ -859,7 +856,7 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("comehere") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("stats"))) { + if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("stats"))) { List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); @@ -873,7 +870,7 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("sit") || args[0].equalsIgnoreCase("stand"))) { + if (player != null && (args[0].equalsIgnoreCase("sit") || args[0].equalsIgnoreCase("stand") || args[0].equalsIgnoreCase("comehere"))) { arg2.add("all"); List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); From a59d1f19c0b90d7e3c49d92d91e5741a8e8464b5 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sun, 28 May 2023 21:12:49 +0200 Subject: [PATCH 21/25] Add limits to dogs owned using permissions; closes #40 --- src/main/java/dk/fido2603/mydog/MyDog.java | 1 + .../mydog/listeners/WolfMainListener.java | 354 +++++++++++------- .../mydog/managers/CommandManager.java | 29 +- .../fido2603/mydog/managers/DogManager.java | 14 + .../java/dk/fido2603/mydog/objects/Dog.java | 11 + src/main/resources/plugin.yml | 19 + 6 files changed, 268 insertions(+), 160 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/MyDog.java b/src/main/java/dk/fido2603/mydog/MyDog.java index 52ba842..6460662 100644 --- a/src/main/java/dk/fido2603/mydog/MyDog.java +++ b/src/main/java/dk/fido2603/mydog/MyDog.java @@ -68,6 +68,7 @@ public class MyDog extends JavaPlugin { public String deadDogString = "&c&l[{chatPrefix}] &r&cYour dog, {dogNameColor}{dogName}&c, just passed away... {dogNameColor}{dogName}&c lived for {time}{deadDogLevelString}."; public String deadDogLevelString = ", and got to &4Level {level}&c"; public String commandComehereString = "&6&l[{chatPrefix}] &r&6Come here! Good doggo, {dogNameColor}{dogName}&6!"; + public String tameLimitString = "&c&l[{chatPrefix}] &r&cTaming failed! Looks like you have reached your limit of dogs! You can maybe set some dead dogs free, or revive some?"; private static MyDog plugin; private static FileConfiguration config = null; diff --git a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java index cbb1c70..32d1417 100644 --- a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java +++ b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java @@ -36,9 +36,16 @@ public void onEntityTameEvent(EntityTameEvent event) { return; } - Wolf wolf = (Wolf) event.getEntity(); Player owner = (Player) event.getOwner(); + if (!MyDog.getDogManager().canTameMoreDogs(owner)) { + owner.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.tameLimitString.replace("{chatPrefix}", plugin.getChatPrefix()))); + event.setCancelled(true); + return; + } + + Wolf wolf = (Wolf) event.getEntity(); + // Make the task for getting the doggo, we want it to load in first... BukkitRunnable newTamedDog = new BukkitRunnable() { @Override @@ -97,23 +104,6 @@ public void onEntityDeathEvent(EntityDeathEvent event) { MyDog.getDogManager().dogDied(event.getEntity().getUniqueId()); } - @EventHandler - public void onWolfSit(PlayerInteractEntityEvent event) { - Entity entity = event.getRightClicked(); - if (!(entity instanceof Sittable) || !(entity instanceof Wolf)) { - return; - } - - if (MyDog.getDogManager().isDog(entity.getUniqueId())) { - Dog dog = MyDog.getDogManager().getDog(entity.getUniqueId()); - - if (!((Sittable) entity).isSitting()) { - plugin.logDebug("Saved dog location!"); - dog.getDogLocation(); - } - } - } - @EventHandler public void onWolfPlayerInteract(PlayerInteractEntityEvent event) { Entity entity = event.getRightClicked(); @@ -121,44 +111,10 @@ public void onWolfPlayerInteract(PlayerInteractEntityEvent event) { return; } - if (!MyDog.getDogManager().isDog(entity.getUniqueId())) { - // Make the wolf into a dog, if it's tamed - Wolf wolf = (Wolf) entity; - if (wolf.isValid() && wolf.isTamed() && wolf.getOwner() != null && wolf.getOwner() instanceof Player) { - Player owner = (Player) wolf.getOwner(); - Dog dog = null; - - if ((wolf.getCustomName() == null || wolf.getCustomName().isEmpty()) && wolf.getCollarColor() == DyeColor.RED) { - dog = MyDog.getDogManager().newDog(wolf, owner); - } else if (wolf.getCustomName() == null || wolf.getCustomName().isEmpty()) { - dog = MyDog.getDogManager().newDog(wolf, owner, null, wolf.getCollarColor()); - } else if ((wolf.getCustomName() != null && !wolf.getCustomName().isEmpty()) && wolf.getCollarColor() == DyeColor.RED) { - dog = MyDog.getDogManager().newDog(wolf, owner, wolf.getCustomName(), null); - } else if (wolf.getCustomName() != null && !wolf.getCustomName().isEmpty()) { - dog = MyDog.getDogManager().newDog(wolf, owner, wolf.getCustomName(), wolf.getCollarColor()); - } else { - plugin.logDebug("New already-tamed dog creation failed!"); - return; - } - plugin.logDebug("New already-tamed dog! Name: " + dog.getDogName() + " - DogId: " + dog.getDogId() + " - Owner: " + plugin.getServer().getPlayer(dog.getOwnerId()).getName() + " - OwnerId: " + dog.getOwnerId()); - Location dogLocation = dog.getDogLocation(); - plugin.logDebug("Dog Location = X: " + dogLocation.getX() + " Y: " + dogLocation.getY() + " Z: " + dogLocation.getZ()); - - if (!dog.updateWolf()) { - event.setCancelled(true); - return; - } - - String newDogString = plugin.newDogString.replace("{chatPrefix}", plugin.getChatPrefix()).replace("{dogNameColor}", "&" + dog.getDogColor().getChar()).replace("{dogName}", dog.getDogName()); - owner.sendMessage(ChatColor.translateAlternateColorCodes('&', newDogString)); - } - } - Dog dog = MyDog.getDogManager().getDog(entity.getUniqueId()); if (dog == null) { - plugin.logDebug("Dog is null, returning!"); - return; + plugin.logDebug("Dog is null!"); } EquipmentSlot hand = event.getHand(); @@ -171,19 +127,176 @@ public void onWolfPlayerInteract(PlayerInteractEntityEvent event) { } else if (hand.equals(EquipmentSlot.OFF_HAND)) { item = player.getEquipment().getItemInOffHand(); } else { - plugin.logDebug("No item in hand, returning!"); + plugin.logDebug("No item in hand."); + } + + saveDogLocation(dog, wolf); + + // 0 = OK + // 1 = Failed + // 2 = Cancel event + if (onWolfPlayerInteractAlreadyTamed(dog, wolf, player) == 2) { + plugin.logDebug("AlreadyTamed event: Cancelled"); + event.setCancelled(true); return; } - if (item.getType() == Material.AIR) { - if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { - dog.toggleMode(); - event.setCancelled(true); - } - plugin.logDebug("Item is null, retuning!"); + if (onWolfPlayerInteractToggleMode(dog, item, player) == 2) { + plugin.logDebug("ToggleMode event: Cancelled"); + event.setCancelled(true); + return; + } + + if (onWolfPlayerInteractChangeColor(dog, wolf, item, player) == 2) { + plugin.logDebug("ChangeColor event: Cancelled"); + event.setCancelled(true); return; } + if (onWolfPlayerInteractFeed(dog, wolf, item, player) == 2) { + plugin.logDebug("Feed event: Cancelled"); + event.setCancelled(true); + return; + } + + if (onWolfPlayerInteractRename(dog, item, player) == 2) { + plugin.logDebug("Rename event: Cancelled"); + event.setCancelled(true); + } + } + + public void saveDogLocation(Dog dog, Wolf wolf) { + if (dog != null && wolf != null) { + plugin.logDebug("Saved dog location!"); + dog.getDogLocation(); + } + } + + public int onWolfPlayerInteractAlreadyTamed(Dog dog, Wolf wolf, Player player) { + if (dog != null || player == null) { + return 0; // OK + } + + // Make the wolf into a dog, if it's tamed + if (wolf.isValid() && wolf.isTamed() && wolf.getOwner() != null && wolf.getOwner() instanceof Player) { + Player owner = (Player) wolf.getOwner(); + + if (!owner.getUniqueId().equals(player.getUniqueId())) { + return 1; // Error + } + + if (!MyDog.getDogManager().canTameMoreDogs(owner)) { + owner.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.tameLimitString.replace("{chatPrefix}", plugin.getChatPrefix()))); + return 1; // Error + } + + if ((wolf.getCustomName() == null || wolf.getCustomName().isEmpty()) && wolf.getCollarColor() == DyeColor.RED) { + dog = MyDog.getDogManager().newDog(wolf, owner); + } else if (wolf.getCustomName() == null || wolf.getCustomName().isEmpty()) { + dog = MyDog.getDogManager().newDog(wolf, owner, null, wolf.getCollarColor()); + } else if ((wolf.getCustomName() != null && !wolf.getCustomName().isEmpty()) && wolf.getCollarColor() == DyeColor.RED) { + dog = MyDog.getDogManager().newDog(wolf, owner, wolf.getCustomName(), null); + } else if (wolf.getCustomName() != null && !wolf.getCustomName().isEmpty()) { + dog = MyDog.getDogManager().newDog(wolf, owner, wolf.getCustomName(), wolf.getCollarColor()); + } else { + plugin.logDebug("New already-tamed dog creation failed!"); + return 1; // Error + } + plugin.logDebug("New already-tamed dog! Name: " + dog.getDogName() + " - DogId: " + dog.getDogId() + " - Owner: " + plugin.getServer().getPlayer(dog.getOwnerId()).getName() + " - OwnerId: " + dog.getOwnerId()); + Location dogLocation = dog.getDogLocation(); + plugin.logDebug("Dog Location = X: " + dogLocation.getX() + " Y: " + dogLocation.getY() + " Z: " + dogLocation.getZ()); + + if (!dog.updateWolf()) { + return 1; // Error + } + + String newDogString = plugin.newDogString.replace("{chatPrefix}", plugin.getChatPrefix()).replace("{dogNameColor}", "&" + dog.getDogColor().getChar()).replace("{dogName}", dog.getDogName()); + owner.sendMessage(ChatColor.translateAlternateColorCodes('&', newDogString)); + } + return 0; // OK + } + + public int onWolfPlayerInteractFeed(Dog dog, Wolf wolf, ItemStack item, Player player) { + if (dog == null || item == null) { + return 0; // OK + } + + // Check for food + double healthPoints = 0.0; + switch (item.getType()) { + case CHICKEN: + case COOKED_CHICKEN: + healthPoints = 1.0; + break; + case PORKCHOP: + case COOKED_PORKCHOP: + case BEEF: + case COOKED_BEEF: + case MUTTON: + case COOKED_MUTTON: + case RABBIT: + case COOKED_RABBIT: + case ROTTEN_FLESH: + healthPoints = 2.0; + break; + default: + if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { + dog.toggleMode(); + return 2; // Cancel event + } + break; + } + + if (healthPoints != 0.0) { + plugin.logDebug("Item is food!"); + int dogsLevel = dog.getLevel(); + if (dogsLevel < 1) { + plugin.logDebug("Level was under 1, setting level to 1"); + dogsLevel = 1; + } + + Level level = plugin.dogLevels.get(dogsLevel); + if (level == null) { + plugin.logDebug("Level object is null, returning!"); + return 1; // Error + } + + double health = level.health; + if (health < 10.0) { + health = 10.0; + } + + AttributeInstance wolfMaxHealth = wolf.getAttribute(Attribute.GENERIC_MAX_HEALTH); + + if (wolfMaxHealth.getValue() != health) { + wolfMaxHealth.setBaseValue(health); + } + + if (wolf.getHealth() >= 20.0 && wolf.getHealth() < health) { + if (wolf.getHealth() + healthPoints > health) { + wolf.setHealth(health); + } else { + wolf.setHealth(wolf.getHealth() + healthPoints); + } + plugin.logDebug("Gave the dog, " + dog.getDogName() + ", " + healthPoints + " in health."); + if (player.getGameMode() != GameMode.CREATIVE) { + item.setAmount(item.getAmount() - 1); + } + return 2; // Cancel event + } + } + return 0; // OK + } + + public int onWolfPlayerInteractChangeColor(Dog dog, Wolf wolf, ItemStack item, Player player) { + if (dog == null || wolf == null || item == null || player == null) { + return 0; // OK + } + + if (!dog.getOwnerId().equals(player.getUniqueId())) { + return 1; // Error + } + DyeColor dc = null; switch (item.getType()) { case BLACK_DYE: @@ -238,102 +351,53 @@ public void onWolfPlayerInteract(PlayerInteractEntityEvent event) { break; } - if (dc == null) { - // Check if the player has a name_tag equipped - if (item.getType().equals(Material.NAME_TAG) && item.getItemMeta().hasDisplayName()) { - if (!plugin.allowNametagRename || !dog.getOwnerId().equals(player.getUniqueId())) { - plugin.logDebug("NametagRename is disabled or not owner trying to rename dog!"); - event.setCancelled(true); - return; - } + if (dc != null) { + // Set collar color - dog.setDogName(item.getItemMeta().getDisplayName()); - plugin.logDebug("Set the Dog's name to: " + item.getItemMeta().getDisplayName()); - if (player.getGameMode() != GameMode.CREATIVE) { - item.setAmount(item.getAmount() - 1); - } - event.setCancelled(true); - return; - } - plugin.logDebug("Item is not a name-tag!"); - - // Check for food - double healthPoints = 0.0; - switch (item.getType()) { - case CHICKEN: - case COOKED_CHICKEN: - healthPoints = 1.0; - break; - case PORKCHOP: - case COOKED_PORKCHOP: - case BEEF: - case COOKED_BEEF: - case MUTTON: - case COOKED_MUTTON: - case RABBIT: - case COOKED_RABBIT: - case ROTTEN_FLESH: - healthPoints = 2.0; - break; - default: - if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { - dog.toggleMode(); - event.setCancelled(true); - } - break; + if (wolf.getCollarColor().equals(dc)) { + plugin.logDebug("Collar color is the same as dye color, returning!"); + return 0; // OK } - if (healthPoints != 0.0) { - plugin.logDebug("Item is food!"); - int dogsLevel = dog.getLevel(); - if (dogsLevel < 1) { - plugin.logDebug("Level was under 1, setting level to 1"); - dogsLevel = 1; - } - - Level level = plugin.dogLevels.get(dogsLevel); - if (level == null) { - plugin.logDebug("Level object is null, returning!"); - return; - } + dog.setDogColor(dc); + } + return 0; // OK + } - double health = level.health; - if (health < 10.0) { - health = 10.0; - } + public int onWolfPlayerInteractToggleMode(Dog dog, ItemStack item, Player player) { + if (dog == null || item == null || player == null) { + return 0; // OK + } - AttributeInstance wolfMaxHealth = wolf.getAttribute(Attribute.GENERIC_MAX_HEALTH); + if (item.getType().equals(Material.AIR)) { + if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { + dog.toggleMode(); + return 2; // Cancel event + } + } + return 0; // OK + } - if (wolfMaxHealth.getValue() != health) { - wolfMaxHealth.setBaseValue(health); - } + public int onWolfPlayerInteractRename(Dog dog, ItemStack item, Player player) { + if (dog == null || item == null || player == null) { + return 0; // OK + } - if (wolf.getHealth() >= 20.0 && wolf.getHealth() < health) { - if (wolf.getHealth() + healthPoints > health) { - wolf.setHealth(health); - } else { - wolf.setHealth(wolf.getHealth() + healthPoints); - } - plugin.logDebug("Gave the dog, " + dog.getDogName() + ", " + healthPoints + " in health."); - if (player.getGameMode() != GameMode.CREATIVE) { - item.setAmount(item.getAmount() - 1); - } - event.setCancelled(true); - } - return; + // Check if the player has a name_tag equipped + if (item.getType().equals(Material.NAME_TAG) && item.getItemMeta().hasDisplayName()) { + if (!plugin.allowNametagRename || !dog.getOwnerId().equals(player.getUniqueId())) { + plugin.logDebug("NametagRename is disabled or not owner trying to rename dog!"); + return 2; // Cancel event } - plugin.logDebug("Item is not food!"); - return; - } else { - // Set collar color - if (wolf.getCollarColor().equals(dc)) { - plugin.logDebug("Collar color is the same as dye color, returning!"); - return; + dog.setDogName(item.getItemMeta().getDisplayName()); + plugin.logDebug("Set the Dog's name to: " + item.getItemMeta().getDisplayName()); + if (player.getGameMode() != GameMode.CREATIVE) { + item.setAmount(item.getAmount() - 1); } - - dog.setDogColor(dc); + return 2; // Cancel event } + return 0; // OK } @EventHandler(priority = EventPriority.LOWEST) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 4a824da..2da473a 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -25,13 +25,16 @@ public CommandManager(MyDog p) { } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { + if (!plugin.isEnabled()) { + return false; + } + Player player = null; if ((sender instanceof Player)) { player = (Player) sender; } - if ((cmd.getName().equalsIgnoreCase("mydog")) || (cmd.getName().equalsIgnoreCase("md")) || (cmd.getName().equalsIgnoreCase("dog")) || (cmd.getName().equalsIgnoreCase("dogs"))) { if ((args.length == 0) && (player != null)) { return commandHelp(sender); @@ -488,9 +491,13 @@ private boolean commandDogStand(CommandSender sender, int dogIdentifier) { if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, my dogs!"); } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); + if (dogs.get(0) != null) { + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + } } for (Dog dog : dogs) { @@ -499,13 +506,7 @@ private boolean commandDogStand(CommandSender sender, int dogIdentifier) { return false; } - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, " + dog.getDogColor() + dog.getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); - - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - - if (wolf != null) { - wolf.setSitting(false); - } + dog.sit(false); } return true; @@ -516,9 +517,13 @@ private boolean commandDogSit(CommandSender sender, int dogIdentifier) { if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, my dogs!"); } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); + if (dogs.get(0) != null) { + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + } } for (Dog dog : dogs) { @@ -527,13 +532,7 @@ private boolean commandDogSit(CommandSender sender, int dogIdentifier) { return false; } - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, " + dog.getDogColor() + dog.getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); - - Wolf wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); - - if (wolf != null) { - wolf.setSitting(true); - } + dog.sit(true); } return true; diff --git a/src/main/java/dk/fido2603/mydog/managers/DogManager.java b/src/main/java/dk/fido2603/mydog/managers/DogManager.java index 06c7e10..2ce72af 100644 --- a/src/main/java/dk/fido2603/mydog/managers/DogManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/DogManager.java @@ -112,6 +112,20 @@ public void changeDogUUID(UUID oldDogID, UUID newDogID) { } } + public boolean canTameMoreDogs(Player player) { + if (player.isOp()) { + return true; + } + + int currentlyOwned = getDogs(player.getUniqueId()).size(); + for (int i = 0; i <= currentlyOwned; i++) { + if (MyDog.getPermissionsManager().hasPermission(player, "mydog.limit." + i)) { + return false; + } + } + return true; + } + public Dog newDog(Wolf dog, Player dogOwner) { int dogID = generateNewId(dogOwner.getUniqueId()); return new Dog(dog, dogOwner, dogID, 1); diff --git a/src/main/java/dk/fido2603/mydog/objects/Dog.java b/src/main/java/dk/fido2603/mydog/objects/Dog.java index bbe5be5..f251e75 100644 --- a/src/main/java/dk/fido2603/mydog/objects/Dog.java +++ b/src/main/java/dk/fido2603/mydog/objects/Dog.java @@ -233,12 +233,23 @@ public void toggleMode() { if (dog == null) { return; } + MyDog.instance().logDebug("Toggling dog mode."); this.setIsAngry(!isAngry()); dog.setCustomName(nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); dog.setCustomNameVisible(!MyDog.instance().onlyShowNametagOnHover); MyDog.getDogManager().saveTimed(); } + public void sit(boolean sit) { + Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); + if (dog == null || !dog.isValid()) { + return; + } + + dog.setSitting(sit); + getDogLocation(); + } + public boolean isDead() { if (isDead != null) { return isDead; diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index e793f98..08ec28d 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -34,6 +34,13 @@ permissions: mydog.rename: true mydog.free: true mydog.setid: true + mydog.editlevel: true + mydog.dead: true + mydog.revive: true + mydog.sit: true + mydog.limit.*: + description: Give limits to the amount of dogs a player can tame. + default: false mydog.teleport: description: Player's tamed wolves will teleport to the player default: true @@ -55,9 +62,21 @@ permissions: mydog.rename: description: Player can rename their Dogs default: true + mydog.sit: + description: Player can have dogs sit and stand up + default: true mydog.setid: description: Player can set a custom ID to their Dogs default: true + mydog.editlevel: + description: Player can set the level of their dogs + default: false + mydog.dead: + description: Player can see the list of dead dogs + default: true + mydog.revive: + description: Player can revive dead dogs + default: true mydog.free: description: Player can set their Dogs free default: true From 77c3a0b5a68f403acedfb74549cc86703b4d77fa Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sun, 28 May 2023 22:24:37 +0200 Subject: [PATCH 22/25] Add petting dogs; closes #32 --- src/main/java/dk/fido2603/mydog/MyDog.java | 2 + .../mydog/listeners/WolfMainListener.java | 14 +-- .../mydog/managers/CommandManager.java | 80 +++++++++++-- .../java/dk/fido2603/mydog/objects/Dog.java | 111 +++++++++--------- .../fido2603/mydog/utils/ParticleUtils.java | 26 ++++ src/main/resources/plugin.yml | 12 ++ 6 files changed, 173 insertions(+), 72 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/MyDog.java b/src/main/java/dk/fido2603/mydog/MyDog.java index 6460662..5cc40bc 100644 --- a/src/main/java/dk/fido2603/mydog/MyDog.java +++ b/src/main/java/dk/fido2603/mydog/MyDog.java @@ -69,6 +69,8 @@ public class MyDog extends JavaPlugin { public String deadDogLevelString = ", and got to &4Level {level}&c"; public String commandComehereString = "&6&l[{chatPrefix}] &r&6Come here! Good doggo, {dogNameColor}{dogName}&6!"; public String tameLimitString = "&c&l[{chatPrefix}] &r&cTaming failed! Looks like you have reached your limit of dogs! You can maybe set some dead dogs free, or revive some?"; + public String pettingString = "&6Who's a good doggo?! {dogNameColor}{dogName}&6 is!"; + public String pettingSplashString = "{dogNameColor}{dogName}&6 splashes water all over you!"; private static MyDog plugin; private static FileConfiguration config = null; diff --git a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java index 32d1417..724d040 100644 --- a/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java +++ b/src/main/java/dk/fido2603/mydog/listeners/WolfMainListener.java @@ -141,8 +141,8 @@ public void onWolfPlayerInteract(PlayerInteractEntityEvent event) { return; } - if (onWolfPlayerInteractToggleMode(dog, item, player) == 2) { - plugin.logDebug("ToggleMode event: Cancelled"); + if (onWolfPlayerInteractPet(dog, item, player) == 2) { + plugin.logDebug("Petting event: Cancelled"); event.setCancelled(true); return; } @@ -240,8 +240,8 @@ public int onWolfPlayerInteractFeed(Dog dog, Wolf wolf, ItemStack item, Player p healthPoints = 2.0; break; default: - if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { - dog.toggleMode(); + if (player.isSneaking()) { + dog.pet(player); return 2; // Cancel event } break; @@ -364,14 +364,14 @@ public int onWolfPlayerInteractChangeColor(Dog dog, Wolf wolf, ItemStack item, P return 0; // OK } - public int onWolfPlayerInteractToggleMode(Dog dog, ItemStack item, Player player) { + public int onWolfPlayerInteractPet(Dog dog, ItemStack item, Player player) { if (dog == null || item == null || player == null) { return 0; // OK } if (item.getType().equals(Material.AIR)) { - if (player.isSneaking() && dog.getOwnerId().equals(player.getUniqueId())) { - dog.toggleMode(); + if (player.isSneaking()) { + dog.pet(player); return 2; // Cancel event } } diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 2da473a..796be74 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -174,7 +174,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogSit(sender, dogIdentifier); + return commandDogStandSit(sender, dogIdentifier, true); } if ((args[0].equalsIgnoreCase("stand"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { @@ -194,7 +194,47 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogStand(sender, dogIdentifier); + return commandDogStandSit(sender, dogIdentifier, false); + } + if ((args[0].equalsIgnoreCase("attack"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { + return false; + } + + int dogIdentifier; + if (args[1].equalsIgnoreCase("all")) { + dogIdentifier = -1; + } + else { + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + } + + return commandDogDefendAttack(sender, dogIdentifier, true); + } + if ((args[0].equalsIgnoreCase("defend"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { + return false; + } + + int dogIdentifier; + if (args[1].equalsIgnoreCase("all")) { + dogIdentifier = -1; + } + else { + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + } + + return commandDogDefendAttack(sender, dogIdentifier, false); } if ((args[0].equalsIgnoreCase("revive"))) { if (!plugin.allowRevival || ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.revive")))) { @@ -305,6 +345,10 @@ private boolean commandList(CommandSender sender) { sender.sendMessage(ChatColor.AQUA + "/mydog sit " + ChatColor.WHITE + " - Tells your dog(s) to sit and keep their position(s)"); sender.sendMessage(ChatColor.AQUA + "/mydog stand " + ChatColor.WHITE + " - Tells your dog(s) to stand up and roam free"); } + if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { + sender.sendMessage(ChatColor.AQUA + "/mydog attack " + ChatColor.WHITE + " - Tells your dog(s) to attack any mobs nearby"); + sender.sendMessage(ChatColor.AQUA + "/mydog defend " + ChatColor.WHITE + " - Tells your dog(s) to defend you"); + } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { sender.sendMessage(ChatColor.AQUA + "/mydog info " + ChatColor.WHITE + " - Gets stats and other info about a Dog you own"); } @@ -486,17 +530,22 @@ private boolean commandDogFree(CommandSender sender, int dogIdentifier) { return true; } - private boolean commandDogStand(CommandSender sender, int dogIdentifier) { + private boolean commandDogDefendAttack(CommandSender sender, int dogIdentifier, boolean toAttack) { List dogs = new ArrayList<>(); + String mode = "Defend me"; + if (toAttack) { + mode = "Attack"; + } + if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, my dogs!"); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", my dogs!"); } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); if (dogs.get(0) != null) { - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Stand, " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); } } @@ -506,23 +555,28 @@ private boolean commandDogStand(CommandSender sender, int dogIdentifier) { return false; } - dog.sit(false); + dog.setAngryMode(toAttack); } return true; } - private boolean commandDogSit(CommandSender sender, int dogIdentifier) { + private boolean commandDogStandSit(CommandSender sender, int dogIdentifier, boolean toSit) { List dogs = new ArrayList<>(); + String mode = "Stand"; + if (toSit) { + mode = "Sit"; + } + if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, my dogs!"); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", my dogs!"); } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); if (dogs.get(0) != null) { - sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + "Sit, " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); + sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); } } @@ -532,7 +586,7 @@ private boolean commandDogSit(CommandSender sender, int dogIdentifier) { return false; } - dog.sit(true); + dog.sit(toSit); } return true; @@ -834,6 +888,10 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia arg1.add("sit"); arg1.add("stand"); } + if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { + arg1.add("attack"); + arg1.add("defend"); + } if (plugin.allowRevival && (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { arg1.add("dead"); } @@ -869,7 +927,7 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("sit") || args[0].equalsIgnoreCase("stand") || args[0].equalsIgnoreCase("comehere"))) { + if (player != null && (args[0].equalsIgnoreCase("sit") || args[0].equalsIgnoreCase("stand") || args[0].equalsIgnoreCase("comehere") || args[0].equalsIgnoreCase("attack") || args[0].equalsIgnoreCase("defend"))) { arg2.add("all"); List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); diff --git a/src/main/java/dk/fido2603/mydog/objects/Dog.java b/src/main/java/dk/fido2603/mydog/objects/Dog.java index f251e75..9f9e79e 100644 --- a/src/main/java/dk/fido2603/mydog/objects/Dog.java +++ b/src/main/java/dk/fido2603/mydog/objects/Dog.java @@ -2,9 +2,7 @@ import dk.fido2603.mydog.MyDog; import dk.fido2603.mydog.utils.ColorUtils; -import org.bukkit.ChatColor; -import org.bukkit.DyeColor; -import org.bukkit.Location; +import org.bukkit.*; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; @@ -13,13 +11,12 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.UUID; +import java.util.*; public class Dog { private static final String ANGRY_MODE = ChatColor.GRAY + "[" + ChatColor.RED + "⚔" + ChatColor.GRAY + "]"; private static final String DEFENCE_MODE = ChatColor.GRAY + "[" + ChatColor.GREEN + "⛨" + ChatColor.GRAY + "]"; + private static final List PETTING_SOUNDS = Arrays.asList(Sound.ENTITY_WOLF_PANT, Sound.ENTITY_WOLF_AMBIENT); private UUID dogId; private UUID dogOwnerId; @@ -208,35 +205,54 @@ public boolean setDogColor(DyeColor color) { this.dogName = getDogName(); } - - if (MyDog.instance().useLevels && MyDog.instance().showLevelsInNametag) { - String dogNamePlate = nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE); - MyDog.instance().logDebug("Setting customName to: " + dogNamePlate); - dog.setCustomName(dogNamePlate); - } else { - MyDog.instance().logDebug("Setting customName to: " + nameColor + dogName); - dog.setCustomName(nameColor + dogName); - } - - if (MyDog.instance().onlyShowNametagOnHover) { - dog.setCustomNameVisible(false); - } else { - dog.setCustomNameVisible(true); - } + setDogCustomName(); } MyDog.getDogManager().saveTimed(); return true; } + public void pet(Player player) { + if (player == null || (!player.isOp() && !MyDog.getPermissionsManager().hasPermission(player, "mydog.pet"))) { + return; + } + + if (!player.getUniqueId().equals(dogOwnerId) && !MyDog.getPermissionsManager().hasPermission(player, "mydog.pet.others")) { + return; + } + + Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); + if (dog == null) { + return; + } + + MyDog.instance().logDebug("Petting dog."); + + Random rand = new Random(); + String pettingString = MyDog.instance().pettingString.replace("{dogNameColor}", "&" + getDogColor().getChar()).replace("{dogName}", getDogName()); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', pettingString)); + + if (rand.nextInt(10) == 1) { + dog.playEffect(EntityEffect.WOLF_SHAKE); + pettingString = MyDog.instance().pettingSplashString.replace("{dogNameColor}", "&" + getDogColor().getChar()).replace("{dogName}", getDogName()); + player.sendMessage(ChatColor.translateAlternateColorCodes('&', pettingString)); + } + MyDog.getParticleUtils().newPettingParticle(dog); + Sound sound = PETTING_SOUNDS.get(rand.nextInt(PETTING_SOUNDS.size())); + player.playSound(player.getLocation(), sound, 3.0F, 1.0F); + } + public void toggleMode() { + setAngryMode(!isAngry()); + } + + public void setAngryMode(boolean angry) { Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); if (dog == null) { return; } MyDog.instance().logDebug("Toggling dog mode."); - this.setIsAngry(!isAngry()); - dog.setCustomName(nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); - dog.setCustomNameVisible(!MyDog.instance().onlyShowNametagOnHover); + this.setIsAngry(angry); + setDogCustomName(); MyDog.getDogManager().saveTimed(); } @@ -280,29 +296,7 @@ public boolean setDogName(String name) { this.dogName = name; MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".Name", dogName); - Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); - - if (dog == null) { - MyDog.instance().logDebug("Dog is null"); - return false; - } - - if (dogName.isEmpty()) { - this.dogName = getDogName(); - } - - if (MyDog.instance().useLevels && MyDog.instance().showLevelsInNametag) { - MyDog.instance().logDebug("Setting customName to: " + nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); - dog.setCustomName(nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); - } else { - MyDog.instance().logDebug("Setting customName to: " + nameColor + dogName); - dog.setCustomName(nameColor + dogName); - } - if (MyDog.instance().onlyShowNametagOnHover) { - dog.setCustomNameVisible(false); - } else { - dog.setCustomNameVisible(true); - } + setDogCustomName(); } MyDog.getDogManager().saveTimed(); return true; @@ -416,6 +410,18 @@ public void setExperience(int exp) { MyDog.getDogManager().saveTimed(); } + public String getDogCustomName() { + if (MyDog.getDogManager().getDogsConfig().contains(dogId.toString())) { + if (MyDog.instance().useLevels && MyDog.instance().showLevelsInNametag) { + return (nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); + } + else { + return nameColor + dogName; + } + } + return null; + } + public boolean setDogCustomName() { MyDog.instance().logDebug("Setting custom name... dogId: " + dogId); if (MyDog.instance().getServer().getEntity(dogId) == null || !MyDog.instance().getServer().getEntity(dogId).isValid() || !(MyDog.instance().getServer().getEntity(dogId) instanceof Wolf)) { @@ -426,13 +432,10 @@ public boolean setDogCustomName() { Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); if (MyDog.getDogManager().getDogsConfig().contains(dogId.toString())) { - if (MyDog.instance().useLevels && MyDog.instance().showLevelsInNametag) { - MyDog.instance().logDebug("Setting customName to: " + nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); - dog.setCustomName(nameColor + dogName + ChatColor.GRAY + " [" + ChatColor.GOLD + "" + this.level + ChatColor.GRAY + "]" + (isAngry() ? ANGRY_MODE : DEFENCE_MODE)); - } else { - MyDog.instance().logDebug("Setting customName to: " + nameColor + dogName); - dog.setCustomName(nameColor + dogName); - } + String customName = getDogCustomName(); + MyDog.instance().logDebug("Setting customName to: " + customName); + dog.setCustomName(customName); + if (MyDog.instance().onlyShowNametagOnHover) { dog.setCustomNameVisible(false); } else { diff --git a/src/main/java/dk/fido2603/mydog/utils/ParticleUtils.java b/src/main/java/dk/fido2603/mydog/utils/ParticleUtils.java index 9ee15b4..90e956f 100644 --- a/src/main/java/dk/fido2603/mydog/utils/ParticleUtils.java +++ b/src/main/java/dk/fido2603/mydog/utils/ParticleUtils.java @@ -89,6 +89,32 @@ public void run() { }.runTaskTimer(plugin, 0, 1); } + public void newPettingParticle(Entity entity) { + double r = 0.8; + + new BukkitRunnable() { + double t = 0; + + public void run() { + Location loc = entity.getLocation(); + loc.setY(loc.getY() + 0.5); + t = t + Math.PI / 4; + double x = r * Math.cos(t); + //double y = 0.05*t; + double y = Math.random() * r; + double z = r * Math.sin(t); + + loc.add(x, y, z); + loc.getWorld().spawnParticle(Particle.HEART, loc, 1); + loc.subtract(x, y, z); + + if (t > Math.PI * 4) { + this.cancel(); + } + } + }.runTaskTimer(plugin, 0, 1); + } + /*public void newLevelUpParticle2(Location loc) { new BukkitRunnable() diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 08ec28d..fde99c0 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -38,6 +38,9 @@ permissions: mydog.dead: true mydog.revive: true mydog.sit: true + mydog.togglemode: true + mydog.pet: true + mydog.pet.others: true mydog.limit.*: description: Give limits to the amount of dogs a player can tame. default: false @@ -68,6 +71,15 @@ permissions: mydog.setid: description: Player can set a custom ID to their Dogs default: true + mydog.togglemode: + description: Player can toggle dogs between attack and defend mode + default: true + mydog.pet: + description: Player can pet their dogs + default: true + mydog.pet.others: + description: Player can pet others dogs + default: true mydog.editlevel: description: Player can set the level of their dogs default: false From aae2f68dbe52a45012b124c54c24b48ed944c127 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Sun, 28 May 2023 22:34:32 +0200 Subject: [PATCH 23/25] Health format in list --- src/main/java/dk/fido2603/mydog/managers/CommandManager.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 796be74..7c45ac5 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -378,6 +378,7 @@ private boolean commandDogList(CommandSender sender) { for (Dog dog : MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId())) { dogsSorted.put(dog.getIdentifier(), dog); } + DecimalFormat df = new DecimalFormat("#.#"); sender.sendMessage(ChatColor.YELLOW + "---------------- " + this.plugin.getDescription().getFullName() + " ----------------"); for (Map.Entry entry : dogsSorted.entrySet()) { @@ -386,7 +387,7 @@ private boolean commandDogList(CommandSender sender) { if (wolf != null) { double maxHealth = wolf.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); double health = wolf.getHealth(); - healthString = " " + ChatColor.BLUE + "(HP: " + health + "/" + maxHealth + ")"; + healthString = " " + ChatColor.BLUE + "(HP: " + df.format(health) + "/" + df.format(maxHealth) + ")"; } sender.sendMessage(ChatColor.AQUA + "#" + ((Dog) entry.getValue()).getIdentifier() + ChatColor.WHITE + " - " + ChatColor.AQUA + ((Dog) entry.getValue()).getDogName() + healthString); From 131291bf24a237aeee11a2eebeb9af1084dcfc72 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Mon, 29 May 2023 02:14:48 +0200 Subject: [PATCH 24/25] Implement trading of dogs between players; closes #28 --- .../mydog/managers/CommandManager.java | 344 +++++++++++++++--- .../fido2603/mydog/managers/DogManager.java | 110 +++++- .../java/dk/fido2603/mydog/objects/Dog.java | 28 ++ src/main/resources/plugin.yml | 4 + 4 files changed, 439 insertions(+), 47 deletions(-) diff --git a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java index 7c45ac5..be8d540 100644 --- a/src/main/java/dk/fido2603/mydog/managers/CommandManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/CommandManager.java @@ -37,7 +37,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String if ((cmd.getName().equalsIgnoreCase("mydog")) || (cmd.getName().equalsIgnoreCase("md")) || (cmd.getName().equalsIgnoreCase("dog")) || (cmd.getName().equalsIgnoreCase("dogs"))) { if ((args.length == 0) && (player != null)) { - return commandHelp(sender); + commandHelp(sender); + return true; } else if (args.length == 1) { if (args[0].equalsIgnoreCase("reload")) { if (player == null) { @@ -76,22 +77,42 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return false; } - return commandList(sender); + commandList(sender); + return true; } if (((args[0].equalsIgnoreCase("dogs")) || (args[0].equalsIgnoreCase("list"))) && (player != null)) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.dogs"))) { return false; } - return commandDogList(sender); + commandDogList(sender); + return true; } if (args[0].equalsIgnoreCase("dead") && (player != null)) { if (!plugin.allowRevival || ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { return false; } - return commandDogDead(sender); + commandDogDead(sender); + return true; } + if (args[0].equalsIgnoreCase("tradeaccept") && (player != null)) { + if (((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.trade")))) { + return false; + } + + commandTradeAccept(sender); + return true; + } + if ((args[0].equalsIgnoreCase("tradedeny") || args[0].equalsIgnoreCase("tradedecline")) && (player != null)) { + if (((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.trade")))) { + return false; + } + + commandTradeDeny(sender); + return true; + } + sender.sendMessage(ChatColor.RED + "Not a MyDog Command! Check /mydog help"); } else if ((args.length == 2) && (player != null)) { if ((args[0].equalsIgnoreCase("putdown")) || (args[0].equalsIgnoreCase("kill"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.putdown"))) { @@ -105,7 +126,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - return commandDogPutdown(sender, dogIdentifier); + commandDogPutdown(sender, dogIdentifier); + return true; } if ((args[0].equalsIgnoreCase("free")) || (args[0].equalsIgnoreCase("setfree")) || (args[0].equalsIgnoreCase("release"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.free"))) { @@ -120,7 +142,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - return commandDogFree(sender, dogIdentifier); + commandDogFree(sender, dogIdentifier); + return true; } if ((args[0].equalsIgnoreCase("stats")) || (args[0].equalsIgnoreCase("info"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { @@ -134,7 +157,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - return commandDogStats(sender, dogIdentifier); + commandDogStats(sender, dogIdentifier); + return true; } if ((args[0].equalsIgnoreCase("comehere"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.comehere"))) { @@ -144,8 +168,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String int dogIdentifier; if (args[1].equalsIgnoreCase("all")) { dogIdentifier = -1; - } - else { + } else { try { dogIdentifier = Integer.parseInt(args[1]); } catch (NumberFormatException e) { @@ -154,7 +177,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogComehere(sender, dogIdentifier); + commandDogComehere(sender, dogIdentifier); + return true; } if ((args[0].equalsIgnoreCase("sit"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { @@ -164,8 +188,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String int dogIdentifier; if (args[1].equalsIgnoreCase("all")) { dogIdentifier = -1; - } - else { + } else { try { dogIdentifier = Integer.parseInt(args[1]); } catch (NumberFormatException e) { @@ -174,7 +197,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogStandSit(sender, dogIdentifier, true); + commandDogStandSit(sender, dogIdentifier, true); + return true; } if ((args[0].equalsIgnoreCase("stand"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.sit"))) { @@ -184,8 +208,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String int dogIdentifier; if (args[1].equalsIgnoreCase("all")) { dogIdentifier = -1; - } - else { + } else { try { dogIdentifier = Integer.parseInt(args[1]); } catch (NumberFormatException e) { @@ -194,7 +217,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogStandSit(sender, dogIdentifier, false); + commandDogStandSit(sender, dogIdentifier, false); + return true; } if ((args[0].equalsIgnoreCase("attack"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { @@ -204,8 +228,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String int dogIdentifier; if (args[1].equalsIgnoreCase("all")) { dogIdentifier = -1; - } - else { + } else { try { dogIdentifier = Integer.parseInt(args[1]); } catch (NumberFormatException e) { @@ -214,7 +237,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogDefendAttack(sender, dogIdentifier, true); + commandDogDefendAttack(sender, dogIdentifier, true); + return true; } if ((args[0].equalsIgnoreCase("defend"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.togglemode"))) { @@ -224,8 +248,7 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String int dogIdentifier; if (args[1].equalsIgnoreCase("all")) { dogIdentifier = -1; - } - else { + } else { try { dogIdentifier = Integer.parseInt(args[1]); } catch (NumberFormatException e) { @@ -234,7 +257,8 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } } - return commandDogDefendAttack(sender, dogIdentifier, false); + commandDogDefendAttack(sender, dogIdentifier, false); + return true; } if ((args[0].equalsIgnoreCase("revive"))) { if (!plugin.allowRevival || ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.revive")))) { @@ -242,8 +266,6 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String } //check is args1 is a number - - int dogIdentifier; try { dogIdentifier = Integer.parseInt(args[1]); @@ -252,9 +274,11 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - return commandReviveDog(player, sender, dogIdentifier); + commandReviveDog(player, sender, dogIdentifier); + return true; } - } else if ((args.length >= 3) && (player != null)) { + sender.sendMessage(ChatColor.RED + "Not a MyDog Command! Check /mydog help"); + } else if ((args.length == 3) && (player != null)) { if ((args[0].equalsIgnoreCase("editlevel") || args[0].equalsIgnoreCase("setlevel"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.editlevel"))) { return false; @@ -271,14 +295,16 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return true; } - return commandEditLevel(sender, dogIdentifier, dogLevel); + commandEditLevel(sender, dogIdentifier, dogLevel); + return true; } if ((args[0].equalsIgnoreCase("setid")) || (args[0].equalsIgnoreCase("changeid"))) { if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.setid"))) { return false; } - return commandDogSetId(sender, args); + commandDogSetId(sender, args); + return true; } if ((args[0].equalsIgnoreCase("rename"))) { @@ -286,13 +312,83 @@ public boolean onCommand(CommandSender sender, Command cmd, String label, String return false; } - return commandDogRename(sender, args); + commandDogRename(sender, args); + return true; + } + + if ((args[0].equalsIgnoreCase("trade"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.trade"))) { + return false; + } + + //check is args1 is a number + int dogIdentifier; + String recipientName = args[2]; + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + + Player recipient = plugin.getServer().getPlayer(recipientName); + if (recipient == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a player with that name!"); + return true; + } + if (recipient.getUniqueId().equals(((Player) sender).getUniqueId())) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "You cannot send a trade request to yourself!"); + return true; + } + + commandTrade(sender, dogIdentifier, recipient, 0.0D); + return true; } - sender.sendMessage(ChatColor.RED + "Too many arguments! Check /mydog help"); - return true; - } else { sender.sendMessage(ChatColor.RED + "Not a MyDog Command! Check /mydog help"); - return true; + } else if ((args.length == 4) && (player != null)) { + if ((args[0].equalsIgnoreCase("trade"))) { + if ((!player.isOp()) && (!MyDog.getPermissionsManager().hasPermission(player, "mydog.trade"))) { + return false; + } + + //check is args1 is a number + int dogIdentifier; + String recipientName = args[2]; + double price; + try { + dogIdentifier = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid ID! Check /mydog dogs"); + return true; + } + try { + price = Double.parseDouble(args[3]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid price!"); + return true; + } + + if (price < 0.0D) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Please enter a valid price!"); + return true; + } + + Player recipient = plugin.getServer().getPlayer(recipientName); + if (recipient == null) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "Could not find a player with that name!"); + return true; + } + if (recipient.getUniqueId().equals(((Player) sender).getUniqueId())) { + sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.RED + "You cannot send a trade request to yourself!"); + return true; + } + + commandTrade(sender, dogIdentifier, recipient, price); + return true; + } + sender.sendMessage(ChatColor.RED + "Not a MyDog Command! Check /mydog help"); + } else { + sender.sendMessage(ChatColor.RED + "Too many arguments! Check /mydog help"); } } return true; @@ -349,6 +445,11 @@ private boolean commandList(CommandSender sender) { sender.sendMessage(ChatColor.AQUA + "/mydog attack " + ChatColor.WHITE + " - Tells your dog(s) to attack any mobs nearby"); sender.sendMessage(ChatColor.AQUA + "/mydog defend " + ChatColor.WHITE + " - Tells your dog(s) to defend you"); } + if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.trade"))) { + sender.sendMessage(ChatColor.AQUA + "/mydog trade [price]" + ChatColor.WHITE + " - Send a trade request to another player"); + sender.sendMessage(ChatColor.AQUA + "/mydog tradeaccept" + ChatColor.WHITE + " - Accept a trade"); + sender.sendMessage(ChatColor.AQUA + "/mydog tradedecline" + ChatColor.WHITE + " - Decline a trade"); + } if ((sender.isOp()) || (MyDog.getPermissionsManager().hasPermission(player, "mydog.stats"))) { sender.sendMessage(ChatColor.AQUA + "/mydog info " + ChatColor.WHITE + " - Gets stats and other info about a Dog you own"); } @@ -542,8 +643,7 @@ private boolean commandDogDefendAttack(CommandSender sender, int dogIdentifier, if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", my dogs!"); - } - else { + } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); if (dogs.get(0) != null) { sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); @@ -573,8 +673,7 @@ private boolean commandDogStandSit(CommandSender sender, int dogIdentifier, bool if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", my dogs!"); - } - else { + } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); if (dogs.get(0) != null) { sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "[" + plugin.getChatPrefix() + "] " + ChatColor.RESET + ChatColor.AQUA + mode + ", " + dogs.get(0).getDogColor() + dogs.get(0).getDogName() + ChatColor.RESET + ChatColor.AQUA + "!"); @@ -728,8 +827,7 @@ private boolean commandReviveDog(Player player, CommandSender sender, int dogIde } MyDog.getEconomy().withdrawPlayer(player, revivalPrice); } - } - else { + } else { if (player.getLevel() < revivalPrice) { sender.sendMessage(ChatColor.RED + "You don't have enough power to resurrect the dog. You need " + ChatColor.GOLD + (revivalPrice - player.getLevel()) + ChatColor.RED + " more levels!"); return false; @@ -755,8 +853,7 @@ private boolean commandDogComehere(CommandSender sender, int dogIdentifier) { if (dogIdentifier == -1) { dogs = MyDog.getDogManager().getAliveDogs(((Player) sender).getUniqueId()); - } - else { + } else { dogs.add(MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId())); } @@ -820,14 +917,146 @@ private boolean commandDogComehere(CommandSender sender, int dogIdentifier) { return true; } + private boolean commandTradeAccept(CommandSender sender) { + if (!(sender instanceof Player)) { + return false; + } + Player player = ((Player) sender); + + DogManager dogManager = MyDog.getDogManager(); + if (!dogManager.hasTrade(player.getUniqueId())) { + sender.sendMessage(ChatColor.GOLD + "You don't have any pending trades!"); + return false; + } + + double tradePrice = dogManager.getTradePrice(player.getUniqueId()); + if (tradePrice > 0.0D) { + if (MyDog.getEconomy() == null) { + sender.sendMessage(ChatColor.GOLD + "No economy provider found, you cannot trade dogs for cash!"); + return false; + } + + if (!MyDog.getEconomy().has(player, tradePrice)) { + sender.sendMessage(ChatColor.GOLD + "You don't have enough money to trade for that dog!"); + return false; + } + } + + if (!dogManager.canTameMoreDogs(player)) { + sender.sendMessage(ChatColor.GOLD + "You cannot own any more dogs!"); + return false; + } + + Dog dog = dogManager.getTradeDog(player.getUniqueId()); + Wolf wolf = null; + + if (dog != null) { + wolf = (Wolf) plugin.getServer().getEntity(dog.getDogId()); + } + + if (wolf == null || !wolf.isValid() || wolf.isDead()) { + sender.sendMessage(ChatColor.GOLD + "The dog you are trying to accept cannot be found! Is it dead?"); + return false; + } + + dogManager.acceptTrade(player); + sender.sendMessage(ChatColor.GOLD + "You successfully accepted the trade request!"); + Player tradeSender = plugin.getServer().getPlayer(dog.getOwnerId()); + if (tradeSender != null) { + tradeSender.sendMessage(ChatColor.GOLD + "Dog trade request got accepted by recipient!"); + } + return true; + } + + private boolean commandTradeDeny(CommandSender sender) { + if (!(sender instanceof Player)) { + return false; + } + Player player = ((Player) sender); + + DogManager dogManager = MyDog.getDogManager(); + if (!dogManager.hasTrade(player.getUniqueId())) { + sender.sendMessage(ChatColor.GOLD + "You don't have any pending trades!"); + return false; + } + + Dog dog = dogManager.getTradeDog(player.getUniqueId()); + + dogManager.denyTrade(player); + sender.sendMessage(ChatColor.GOLD + "You successfully denied the trade request!"); + if (dog != null) { + Player tradeSender = plugin.getServer().getPlayer(dog.getOwnerId()); + if (tradeSender != null) { + tradeSender.sendMessage(ChatColor.GOLD + "Dog trade request got denied by recipient!"); + } + } + return true; + } + + private boolean commandTrade(CommandSender sender, int dogIdentifier, Player receiver, double price) { + DogManager dogManager = MyDog.getDogManager(); + + Dog dog = dogManager.getDog(dogIdentifier, ((Player) sender).getUniqueId()); + if (dog == null) { + sender.sendMessage(ChatColor.GOLD + "Could not find a dog with this ID!"); + return false; + } + if (dog.isDead()) { + sender.sendMessage(ChatColor.GOLD + "You cannot trade dead dogs!"); + return false; + } + + if (price > 0.0D) { + if (MyDog.getEconomy() == null) { + sender.sendMessage(ChatColor.GOLD + "No economy provider found, you cannot trade dogs for cash!"); + return false; + } + + if (!MyDog.getEconomy().has(receiver, price)) { + sender.sendMessage(ChatColor.GOLD + "It doesn't look like the receiver will be able to.. afford that.."); + return false; + } + } + + if (dogManager.hasTrade(receiver.getUniqueId())) { + sender.sendMessage(ChatColor.GOLD + "The receiver already has a trade pending!"); + return false; + } + + if (!receiver.isOp() && !MyDog.getPermissionsManager().hasPermission(receiver, "mydog.trade")) { + sender.sendMessage(ChatColor.GOLD + "The receiver doesn't have permissions to trade!"); + return false; + } + + if (!dogManager.canTameMoreDogs(receiver)) { + sender.sendMessage(ChatColor.GOLD + "The receiver has reached their dog limit!"); + return false; + } + + if (dogManager.handleNewTrade(dog, receiver, price)) { + DecimalFormat df = new DecimalFormat("#.#"); + receiver.sendMessage(ChatColor.GOLD + "You have received a dog trade request from " + ChatColor.AQUA + + ((Player) sender).getDisplayName() + ChatColor.GOLD + "!\n" + ChatColor.AQUA + + ((Player) sender).getDisplayName() + ChatColor.GOLD + " is offering " + dog.getDogColor() + + dog.getDogName() + ChatColor.GOLD + (plugin.useLevels ? (" (" + ChatColor.AQUA + "Level " + + dog.getLevel() + ChatColor.GOLD + ")") : "") + " for " + ChatColor.AQUA + + ((price > 0.0D ? (df.format(price) + "$") : "free")) + ChatColor.GOLD + "!\n\n" + + ChatColor.GOLD + "Accept the trade request with " + ChatColor.AQUA + "/md tradeaccept\n" + + ChatColor.GOLD + "Decline the trade request with " + ChatColor.AQUA + "/md tradedecline\n" + + ChatColor.GOLD + "Request expires in 30 seconds!"); + sender.sendMessage(ChatColor.GOLD + "Trade request successfully sent!"); + } + return true; + } + private boolean commandEditLevel(CommandSender sender, int dogIdentifier, int dogLevel) { Dog dog = MyDog.getDogManager().getDog(dogIdentifier, ((Player) sender).getUniqueId()); if (dog == null) { - sender.sendMessage("Could not find a dog with this ID!"); + sender.sendMessage(ChatColor.GOLD + "Could not find a dog with this ID!"); return false; } if (dogLevel < 1 || dogLevel > 100) { - sender.sendMessage("Level must be between 0 and 100!"); + sender.sendMessage(ChatColor.GOLD + "Level must be between 0 and 100!"); } dog.setLevel(dogLevel); dog.updateWolf(); @@ -893,6 +1122,12 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia arg1.add("attack"); arg1.add("defend"); } + if (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.trade"))) { + arg1.add("trade"); + arg1.add("tradeaccept"); + arg1.add("tradedecline"); + arg1.add("tradedeny"); + } if (plugin.allowRevival && (player == null || (player.isOp() || MyDog.getPermissionsManager().hasPermission(player, "mydog.dead")))) { arg1.add("dead"); } @@ -914,7 +1149,7 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia } } - if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("stats"))) { + if (player != null && (args[0].equalsIgnoreCase("putdown") || args[0].equalsIgnoreCase("rename") || args[0].equalsIgnoreCase("info") || args[0].equalsIgnoreCase("kill") || args[0].equalsIgnoreCase("stats") || args[0].equalsIgnoreCase("trade"))) { List dogs = MyDog.getDogManager().getAliveDogs(player.getUniqueId()); for (Dog dog : dogs) { arg2.add(Integer.toString(dog.getIdentifier())); @@ -948,10 +1183,27 @@ public List onTabComplete(CommandSender sender, Command cmd, String alia arg3.add(""); } else if (args[0].equalsIgnoreCase("setlevel")) { arg3.add(""); + } else if (args[0].equalsIgnoreCase("trade")) { + // idk how, uhm, good this might be + Collection players = plugin.getServer().getOnlinePlayers(); + for (Player playerObj : players) { + if (playerObj != null) { + arg3.add(playerObj.getName()); + } + } + } + + Iterable THIRD_ARGUMENTS = arg3; + StringUtil.copyPartialMatches(args[2], THIRD_ARGUMENTS, result); + } else if (args.length == 4) { + List arg4 = new ArrayList(); + + if (args[0].equalsIgnoreCase("trade")) { + arg4.add("[price]"); } - Iterable SECOND_ARGUMENTS = arg3; - StringUtil.copyPartialMatches(args[2], SECOND_ARGUMENTS, result); + Iterable FOURTH_ARGUMENTS = arg4; + StringUtil.copyPartialMatches(args[3], FOURTH_ARGUMENTS, result); } Collections.sort(result); diff --git a/src/main/java/dk/fido2603/mydog/managers/DogManager.java b/src/main/java/dk/fido2603/mydog/managers/DogManager.java index 2ce72af..93a49f4 100644 --- a/src/main/java/dk/fido2603/mydog/managers/DogManager.java +++ b/src/main/java/dk/fido2603/mydog/managers/DogManager.java @@ -13,6 +13,7 @@ import org.bukkit.entity.Wolf; import dk.fido2603.mydog.objects.Dog; +import org.bukkit.scheduler.BukkitRunnable; public class DogManager { private MyDog plugin = null; @@ -21,6 +22,8 @@ public class DogManager { private Random random = new Random(); private long lastSaveTime = 0L; + private HashMap> dogTrades = new HashMap<>(); + public DogManager(MyDog plugin) { this.plugin = plugin; } @@ -198,6 +201,111 @@ public List getDeadDogs(UUID ownerId) { return dogs; } + public boolean handleNewTrade(Dog dog, Player receiver, double price) { + if (dogTrades.containsKey(receiver.getUniqueId())) { + return false; + } + + if (!canTameMoreDogs(receiver)) { + return false; + } + + HashMap dogTrade = new HashMap<>(); + dogTrade.put("time", System.currentTimeMillis()); + dogTrade.put("dog", dog.getDogId()); + dogTrade.put("price", price); + + dogTrades.put(receiver.getUniqueId(), dogTrade); + + // Delete the trade after 30 seconds if it still exists + new BukkitRunnable() { + @Override + public void run() { + if (hasTrade(receiver.getUniqueId())) { + dogTrades.remove(receiver.getUniqueId()); + receiver.sendMessage(ChatColor.GOLD + "Dog trade expired!"); + + Player sender = plugin.getServer().getPlayer(dog.getOwnerId()); + if (sender != null) { + sender.sendMessage(ChatColor.GOLD + "Recipient didn't answer to dog trade!"); + } + } + } + }.runTaskLaterAsynchronously(plugin, 20L * 30L); + + return true; + } + + public boolean hasTrade(UUID recipient) { + return dogTrades.containsKey(recipient); + } + + public HashMap getTrade(UUID recipient) { + if (!hasTrade(recipient)) { + return null; + } + + return dogTrades.get(recipient); + } + + public Dog getTradeDog(UUID recipient) { + HashMap trade = getTrade(recipient); + if (trade == null) { + return null; + } + + return getDog((UUID) trade.get("dog")); + } + + public Double getTradePrice(UUID recipient) { + if (!hasTrade(recipient)) { + return null; + } + + return (double) dogTrades.get(recipient).get("price"); + } + + public boolean acceptTrade(Player accepter) { + HashMap dogTrade = getTrade(accepter.getUniqueId()); + + if (dogTrade == null) { + return false; + } + + Dog dog = getDog((UUID) dogTrade.get("dog")); + + if (dog == null) { + return false; + } + + double price = (double) dogTrade.get("price"); + if (price > 0.0D) { + if (MyDog.getEconomy() == null) { + plugin.log("No economy provider, failed to trade dogs!"); + return false; + } + + if (!MyDog.getEconomy().has(accepter, price)) { + return false; + } + MyDog.getEconomy().withdrawPlayer(accepter, price); + } + + dog.setOwner(accepter); + + dogTrades.remove(accepter.getUniqueId()); + return true; + } + + public boolean denyTrade(Player denier) { + if (!hasTrade(denier.getUniqueId())) { + return false; + } + + dogTrades.remove(denier.getUniqueId()); + return true; + } + public String newDogName() { int dogNameNumber = random.nextInt(plugin.dogNames.size()); return plugin.dogNames.get(dogNameNumber); @@ -218,7 +326,7 @@ public boolean setNewId(Dog dog, int id) { return false; } - private int generateNewId(UUID dogOwnerId) { + public int generateNewId(UUID dogOwnerId) { int id = 1; List dogs = MyDog.getDogManager().getDogs(dogOwnerId); diff --git a/src/main/java/dk/fido2603/mydog/objects/Dog.java b/src/main/java/dk/fido2603/mydog/objects/Dog.java index 9f9e79e..f4c5cf5 100644 --- a/src/main/java/dk/fido2603/mydog/objects/Dog.java +++ b/src/main/java/dk/fido2603/mydog/objects/Dog.java @@ -347,6 +347,34 @@ public UUID getOwnerId() { return dogOwnerId; } + public boolean setOwner(Player player) { + if (player == null) { + return false; + } + + Wolf dog = (Wolf) MyDog.instance().getServer().getEntity(dogId); + + if (dog == null || !dog.isValid()) { + return false; + } + + if (dogOwnerId.equals(player.getUniqueId())) { + // Same owner + return false; + } + + if (MyDog.getDogManager().getDogsConfig().contains(dogId.toString())) { + this.dogOwnerId = player.getUniqueId(); + this.dogIdentifier = MyDog.getDogManager().generateNewId(player.getUniqueId()); + MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".Owner", dogOwnerId); + MyDog.getDogManager().getDogsConfig().set(dogId.toString() + ".ID", dogIdentifier); + dog.setOwner(player); + } + + MyDog.getDogManager().saveTimed(); + return true; + } + public int getRevivalPrice() { return (int) (level * MyDog.instance().revivalPrice); } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index fde99c0..3d7ea4f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -41,6 +41,7 @@ permissions: mydog.togglemode: true mydog.pet: true mydog.pet.others: true + mydog.trade: true mydog.limit.*: description: Give limits to the amount of dogs a player can tame. default: false @@ -92,6 +93,9 @@ permissions: mydog.free: description: Player can set their Dogs free default: true + mydog.trade: + description: Players can trade their dogs + default: true mydog.reload: description: Player can reload the configuration(s) default: false From 41900510da4dd020103f037c7c76ae5c9fe264c5 Mon Sep 17 00:00:00 2001 From: HeroGamers Date: Mon, 29 May 2023 02:18:34 +0200 Subject: [PATCH 25/25] Change release to 0.2.0-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 40b0cf0..dc63da7 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 dk.fido2603 mydog - 0.1.5-SNAPSHOT + 0.2.0-SNAPSHOT MyDog Tamed wolves but at least 10x better! https://github.com/${github.repo}