From f4954efb39612b2903a57a0cbeaa088e67644976 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 3 May 2022 13:07:40 -0400 Subject: [PATCH 01/68] start of 1.4.3 --- pom.xml | 2 +- .../java/net/tylermurphy/hideAndSeek/command/About.java | 2 +- .../tylermurphy/hideAndSeek/configuration/Localization.java | 2 +- src/main/java/net/tylermurphy/hideAndSeek/game/Board.java | 2 +- src/main/java/net/tylermurphy/hideAndSeek/game/Game.java | 4 ++-- src/main/resources/lang/localization_de-DE.yml | 6 ++++-- src/main/resources/lang/localization_en-US.yml | 2 ++ src/main/resources/plugin.yml | 2 +- 8 files changed, 13 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index e6bab08..4f73ae1 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 net.tylermurphy HideAndSeek - 1.4.2 + 1.4.3 Hide and Seek Plugin UTF-8 diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java index 756a8e1..046c2d8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java @@ -26,7 +26,7 @@ public class About implements ICommand { public void execute(CommandSender sender, String[] args) { sender.sendMessage( - String.format("%s%sHide and Seek %s(%s1.4.2%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) + + String.format("%s%sHide and Seek %s(%s1.4.3%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) + String.format("%sAuthor: %s[KenshinEto]\n", ChatColor.GRAY, ChatColor.WHITE) + String.format("%sHelp Command: %s/hs %shelp", ChatColor.GRAY, ChatColor.AQUA, ChatColor.WHITE) ); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java index b93329f..fc2983a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java @@ -31,7 +31,7 @@ public class Localization { private static final Map CHANGES = new HashMap() {{ put("en-US", new String[][]{{"WORLDBORDER_DECREASING"},{"START","TAUNTED"}}); - put("de-DE", new String[][]{{}}); + put("de-DE", new String[][]{{},{"TAUNTED"}}); }}; public static void loadLocalization() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 5608e88..d569a7f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -141,7 +141,7 @@ public class Board { private static void createLobbyBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); if(recreate) { - board = new CustomBoard(player, "&l&eHIDE AND SEEK"); + board = new CustomBoard(player, LOBBY_TITLE); board.updateTeams(); } int i=0; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 6a6ccaa..eb467c4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -119,11 +119,11 @@ public class Game { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS,1000000,127,false,false)); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW,1000000,127,false,false)); player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,1000000,128,false,false)); - Titles.sendTitle(player, 10, 70, 20, ChatColor.RED + "" + ChatColor.BOLD + "SEEKER", ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString()); + Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("SEEKER_TEAM_NAME"), ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString()); } for(Player player : Board.getHiders()) { player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false)); - Titles.sendTitle(player, 10, 70, 20, ChatColor.GOLD + "" + ChatColor.BOLD + "HIDER", ChatColor.WHITE + message("HIDERS_SUBTITLE").toString()); + Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString()); } if(tauntEnabled) taunt = new Taunt(); diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index 67c14fd..26841d5 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -37,7 +37,7 @@ Localization: WORLDBORDER_ENABLE: "Setze World Border zentriert von dieser Position aus. Größe: {AMOUNT}. Verzögerung: {AMOUNT}." WORLDBORDER_DECREASING: "World Norder schrumpoft 100 Blöcke über die nächsten 30 Sekunden!" WORLDBORDER_WARN: "Die Weltgrenze wird in den nächsten 30er Jahren schrumpfen!" - TAUNTED: "$c$oOh nein! Du wurdest geärgert!" + TAUNTED: "&c&oOh nein! Du wurdest geärgert!" TAUNT: "Ein zufälliger Hider wird in den nächsten 30 Sekunden geärgert." TAUNT_ACTIVATE: "Ärgern wurde aktiviert" ERROR_GAME_SPAWN: "Bitte erst die Spawn-Position für das Spiel festlegen." @@ -56,6 +56,8 @@ Localization: START_COUNTDOWN: "Die Hider haben {AMOUNT} Sekunden Zeit sich zu verstecken!" START: "Los, Seeker! Es ist Zeit, die Hider zu finden." STOP: "Das Spiel wurde gestoppt." + HIDER_TEAM_NAME: "&6&lHIDER" + SEEKER_TEAM_NAME: "&c&lSEEKER" HIDERS_SUBTITLE: "Verstecke dich gut vor den Seekern!" SEEKERS_SUBTITLE: "Finde alle Hider!" SPECTATOR_SUBTITLE: "Du bist mitten im spiel beigetreten." @@ -67,5 +69,5 @@ Localization: BLOCKED_COMMAND: "Command blocked by Kenshin's Hide And Seek" # DO NOT EDIT IT OR IT MAY BREAK OR RESET FILE -version: 2 +version: 3 type: "de-DE" diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index 33ae4ef..72719f2 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -57,6 +57,8 @@ Localization: START_COUNTDOWN: "Hiders have {AMOUNT} seconds to hide!" START: "Attention SEEKERS, its time to find the hiders!" STOP: "Game has been force stopped." + HIDER_TEAM_NAME: "&6&lHIDER" + SEEKER_TEAM_NAME: "&c&lSEEKER" HIDERS_SUBTITLE: "Hide away from the seekers" SEEKERS_SUBTITLE: "Eliminate all hiders" SPECTATOR_SUBTITLE: "You joined mid-game." diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 7e1bca8..afe2ed2 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ name: HideAndSeek main: net.tylermurphy.hideAndSeek.Main -version: 1.4.2 +version: 1.4.3 author: KenshinEto load: STARTUP api-version: 1.13 From 664c0d9ad5eaaefd9bc7e56ca732c58cb6030b72 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 09:28:38 -0400 Subject: [PATCH 02/68] 1.4.3 beta 2 (bug fix issue requests) --- .../net/tylermurphy/hideAndSeek/command/Stop.java | 3 +-- .../hideAndSeek/configuration/ConfigManager.java | 15 ++++++++------- .../net/tylermurphy/hideAndSeek/game/Game.java | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index b41277b..0b53ed6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -37,8 +37,7 @@ public class Stop implements ICommand { return; } if(Game.status == Status.STARTING || Game.status == Status.PLAYING) { - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("STOP")); - else Game.broadcastMessage(abortPrefix + message("STOP")); + Game.broadcastMessage(abortPrefix + message("STOP")); Game.stop(WinType.NONE); } else { sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS")); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 1684896..71c9e02 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -176,11 +176,10 @@ public class ConfigManager { } public boolean getBoolean(String path){ - boolean value = config.getBoolean(path); - if(!value){ + if(!config.contains(path)){ return defaultConfig.getBoolean(path); } else { - return true; + return config.getBoolean(path); } } @@ -209,7 +208,7 @@ public class ConfigManager { while((c = reader.read()) != -1){ textBuilder.append((char) c); } - String yamlString = textBuilder.toString(); + String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8); Map temp = config.getValues(true); for(Map.Entry entry: temp.entrySet()){ if(entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List){ @@ -239,18 +238,20 @@ public class ConfigManager { } replace = replace.substring(0, replace.length()-2); replace = replace + "]"; + replace = new String(replace.getBytes(), StandardCharsets.UTF_8); } else { - replace = entry.getValue().toString(); + replace = new String(entry.getValue().toString().getBytes(), StandardCharsets.UTF_8); } if(entry.getValue() instanceof String){ replace = "\"" + replace + "\""; } StringBuilder builder = new StringBuilder(yamlString); builder.replace(start+1, end, replace); - yamlString = builder.toString(); + yamlString = new String(builder.toString().getBytes(), StandardCharsets.UTF_8); } } - PrintWriter out = new PrintWriter(file); + OutputStream os = new FileOutputStream(file); + PrintWriter out = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true); out.print(yamlString); out.close(); } catch (IOException e){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index eb467c4..72a530f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -171,6 +171,7 @@ public class Game { } worldBorder.resetWorldborder("hideandseek_"+spawnWorld); for(Player player : Board.getPlayers()) { + player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); Board.createLobbyBoard(player); player.setGameMode(GameMode.ADVENTURE); Board.addHider(player); @@ -179,7 +180,6 @@ public class Game { player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); if(lobbyLeaveItem != null) player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); - player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); for(PotionEffect effect : player.getActivePotionEffects()){ player.removePotionEffect(effect.getType()); } @@ -259,6 +259,7 @@ public class Game { public static void join(Player player){ if(Game.status == Status.STANDBY) { + player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); player.getInventory().clear(); if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); @@ -267,7 +268,6 @@ public class Game { Board.addHider(player); if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); - player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); player.setGameMode(GameMode.ADVENTURE); Board.createLobbyBoard(player); Board.reloadLobbyBoards(); From 90b43758533b07b87bed187c1038b189e5c7cd61 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 10:48:46 -0400 Subject: [PATCH 03/68] 1.4.3 beta 3 --- .../hideAndSeek/configuration/ConfigManager.java | 7 +++---- .../net/tylermurphy/hideAndSeek/game/EventListener.java | 4 ++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 71c9e02..4b24cb9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -208,7 +208,7 @@ public class ConfigManager { while((c = reader.read()) != -1){ textBuilder.append((char) c); } - String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8); + String yamlString = textBuilder.toString(); Map temp = config.getValues(true); for(Map.Entry entry: temp.entrySet()){ if(entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List){ @@ -238,16 +238,15 @@ public class ConfigManager { } replace = replace.substring(0, replace.length()-2); replace = replace + "]"; - replace = new String(replace.getBytes(), StandardCharsets.UTF_8); } else { - replace = new String(entry.getValue().toString().getBytes(), StandardCharsets.UTF_8); + replace = entry.getValue().toString(); } if(entry.getValue() instanceof String){ replace = "\"" + replace + "\""; } StringBuilder builder = new StringBuilder(yamlString); builder.replace(start+1, end, replace); - yamlString = new String(builder.toString().getBytes(), StandardCharsets.UTF_8); + yamlString = builder.toString(); } } OutputStream os = new FileOutputStream(file); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 668a446..0c750fa 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -189,6 +189,10 @@ public class EventListener implements Listener { } if(event.isCancelled()) return; if (player.getHealth() - event.getFinalDamage() < 0.5 || !pvpEnabled) { + if(!pvpEnabled && !Board.isSeeker(player)){ + event.setCancelled(true); + return; + } if (spawnPosition == null) return; event.setCancelled(true); if(Version.atLeast("1.9")) { From 0416f4bfd2f3202d43387909e7d965da64edc14a Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 11:00:06 -0400 Subject: [PATCH 04/68] no pvp damage event fix --- .../net/tylermurphy/hideAndSeek/game/Board.java | 7 ++++--- .../hideAndSeek/game/EventListener.java | 15 ++++++++++++--- src/main/resources/lang/localization_de-DE.yml | 1 + src/main/resources/lang/localization_en-US.yml | 1 + 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index d569a7f..c08b779 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -20,6 +20,7 @@ package net.tylermurphy.hideAndSeek.game; import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; import java.util.*; import java.util.stream.Collectors; @@ -271,9 +272,9 @@ public class Board { } private static String getTeam(Player player) { - if(isHider(player)) return ChatColor.GOLD + "HIDER"; - else if(isSeeker(player)) return ChatColor.RED + "SEEKER"; - else if(isSpectator(player)) return ChatColor.GRAY + "SPECTATOR"; + if(isHider(player)) return message("HIDER_TEAM_NAME").toString(); + else if(isSeeker(player)) return message("SEEKER_TEAM_NAME").toString(); + else if(isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString(); else return ChatColor.WHITE + "UNKNOWN"; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 0c750fa..db97967 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -189,9 +189,18 @@ public class EventListener implements Listener { } if(event.isCancelled()) return; if (player.getHealth() - event.getFinalDamage() < 0.5 || !pvpEnabled) { - if(!pvpEnabled && !Board.isSeeker(player)){ - event.setCancelled(true); - return; + if (event instanceof EntityDamageByEntityEvent && !pvpEnabled) { + Entity damager = ((EntityDamageByEntityEvent) event).getDamager(); + if (damager instanceof Player) { + Player atacker = (Player) damager; + if(!Board.isSeeker(atacker)){ + event.setCancelled(true); + return; + } + } else { + event.setCancelled(true); + return; + } } if (spawnPosition == null) return; event.setCancelled(true); diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index 26841d5..d560d24 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -58,6 +58,7 @@ Localization: STOP: "Das Spiel wurde gestoppt." HIDER_TEAM_NAME: "&6&lHIDER" SEEKER_TEAM_NAME: "&c&lSEEKER" + SPECTATOR_TEAM_NAME: "&8&lSPECTATOR" HIDERS_SUBTITLE: "Verstecke dich gut vor den Seekern!" SEEKERS_SUBTITLE: "Finde alle Hider!" SPECTATOR_SUBTITLE: "Du bist mitten im spiel beigetreten." diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index 72719f2..1757877 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -59,6 +59,7 @@ Localization: STOP: "Game has been force stopped." HIDER_TEAM_NAME: "&6&lHIDER" SEEKER_TEAM_NAME: "&c&lSEEKER" + SPECTATOR_TEAM_NAME: "&8&lSPECTATOR" HIDERS_SUBTITLE: "Hide away from the seekers" SEEKERS_SUBTITLE: "Eliminate all hiders" SPECTATOR_SUBTITLE: "You joined mid-game." From c93937df0383ae059d9be356e4c94091b04b5ce4 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 11:01:48 -0400 Subject: [PATCH 05/68] add not EntityDamageByEntityEvent for no pvp mode --- .../java/net/tylermurphy/hideAndSeek/game/EventListener.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index db97967..5995dbc 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -201,6 +201,9 @@ public class EventListener implements Listener { event.setCancelled(true); return; } + } else if(!pvpEnabled) { + event.setCancelled(true); + return; } if (spawnPosition == null) return; event.setCancelled(true); From 061611ef306d6f413559725183f79adbc7e43615 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 12:01:10 -0400 Subject: [PATCH 06/68] custom model data --- .../tylermurphy/hideAndSeek/configuration/Config.java | 10 ++++++++++ .../hideAndSeek/configuration/ConfigManager.java | 4 ++++ .../tylermurphy/hideAndSeek/configuration/Items.java | 5 +++++ 3 files changed, 19 insertions(+) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index c021fce..9397cc8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -256,6 +256,11 @@ public class Config { ConfigurationSection item = new YamlConfiguration().createSection("temp"); item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.leave.name"))); item.set("material", config.getString("lobbyItems.leave.material")); + if(Version.atLeast("1.14")){ + if(config.contains("lobbyItems.leave.model-data")){ + config.set("model-data", config.getInt("lobbyItems.leave.model-data")); + } + } List lore = config.getStringList("lobbyItems.leave.lore"); if (lore != null && !lore.isEmpty()) item.set("lore", lore); ItemStack temp = null; @@ -274,6 +279,11 @@ public class Config { lobbyStartItem = temp; lobbyItemStartAdmin = config.getBoolean("lobbyItems.start.adminOnly"); lobbyItemStartPosition = config.getInt("lobbyItems.start.position"); + if(Version.atLeast("1.14")){ + if(config.contains("lobbyItems.start.model-data")){ + config.set("model-data", config.getInt("lobbyItems.start.model-data")); + } + } } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 4b24cb9..53a30c2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -104,6 +104,10 @@ public class ConfigManager { } } + public boolean contains(String path){ + return config.contains(path); + } + public double getDouble(String path){ double value = config.getDouble(path); if(value == 0.0D){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index 1c77ec2..e42001f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -102,6 +102,11 @@ public class Items { config.set("material", material); config.set("enchants", item.getConfigurationSection("enchantments")); config.set("unbreakable", item.getBoolean("unbreakable")); + if(Version.atLeast("1.14")){ + if(item.contains("model-data")){ + config.set("model-data", item.getInt("model-data")); + } + } if(item.isSet("lore")) config.set("lore", item.getStringList("lore")); if (material.equalsIgnoreCase("POTION") || material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")) From 590ab6c0e8755f5e5fe9293bd5c7ac93bdd02b30 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 12:22:23 -0400 Subject: [PATCH 07/68] leaveOnEnd added to config file --- .../hideAndSeek/configuration/Config.java | 4 +- .../tylermurphy/hideAndSeek/game/Game.java | 64 ++++++++++++++----- .../tylermurphy/hideAndSeek/util/Status.java | 3 +- src/main/resources/config.yml | 7 ++ 4 files changed, 60 insertions(+), 18 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 9397cc8..589d3a2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -74,7 +74,8 @@ public class Config { lobbyCountdownEnabled, seekerPing, bungeeLeave, - lobbyItemStartAdmin; + lobbyItemStartAdmin, + leaveOnEnd; public static int minPlayers, @@ -219,6 +220,7 @@ public class Config { teleportToExit = config.getBoolean("teleportToExit"); locale = config.getString("locale", "local"); blockedCommands = config.getStringList("blockedCommands"); + leaveOnEnd = config.getBoolean("leaveOnEnd"); blockedInteracts = new ArrayList<>(); List tempInteracts = config.getStringList("blockedInteracts"); for(String id : tempInteracts){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 72a530f..c01682b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -153,6 +153,24 @@ public class Game { }, 20 * 30); } + public static void end(WinType type){ + if(status == Status.STANDBY || status == Status.ENDING) return; + status = Status.ENDING; + for(Player player : Board.getPlayers()) { + player.getInventory().clear(); + player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } + if(Version.atLeast("1.9")){ + for(Player temp : Board.getPlayers()) { + Packet.setGlow(player, temp, false); + } + } + } + Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, () -> stop(type), 5*20); + } + public static void stop(WinType type){ if(status == Status.STANDBY) return; tick = 0; @@ -171,24 +189,38 @@ public class Game { } worldBorder.resetWorldborder("hideandseek_"+spawnWorld); for(Player player : Board.getPlayers()) { - player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); - Board.createLobbyBoard(player); - player.setGameMode(GameMode.ADVENTURE); - Board.addHider(player); - player.getInventory().clear(); - if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp())) - player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); - if(lobbyLeaveItem != null) - player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); - for(PotionEffect effect : player.getActivePotionEffects()){ - player.removePotionEffect(effect.getType()); - } - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); if(Version.atLeast("1.9")){ for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); } } + if(leaveOnEnd){ + Board.removeBoard(player); + Board.remove(player); + player.getInventory().clear(); + if(bungeeLeave) { + ByteArrayDataOutput out = ByteStreams.newDataOutput(); + out.writeUTF("Connect"); + out.writeUTF(leaveServer); + player.sendPluginMessage(Main.plugin, "BungeeCord", out.toByteArray()); + } else { + player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + } + } else { + player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); + Board.createLobbyBoard(player); + player.setGameMode(GameMode.ADVENTURE); + Board.addHider(player); + player.getInventory().clear(); + if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp())) + player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); + if(lobbyLeaveItem != null) + player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } + player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); + } } EventListener.temp_loc.clear(); worldLoader.unloadMap(); @@ -390,15 +422,15 @@ public class Game { if(Board.sizeHider() < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); - stop(WinType.SEEKER_WIN); + end(WinType.SEEKER_WIN); } else if(Board.sizeSeeker() < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); - stop(WinType.NONE); + end(WinType.NONE); } else if(timeLeft < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); - stop(WinType.HIDER_WIN); + end(WinType.HIDER_WIN); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java b/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java index 44a3e42..e1ffa22 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java @@ -22,5 +22,6 @@ package net.tylermurphy.hideAndSeek.util; public enum Status { STANDBY, STARTING, - PLAYING + PLAYING, + ENDING } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index c163c2d..9a82052 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -44,6 +44,13 @@ autoJoin: false # default: false teleportToExit: false +# Normally when the game ends, players are set back to the lobby to play another game. +# You can disable this, and empty the lobby after the game finishes. This is like everyone +# running /hs leave at the end of the game. Players will leave either to the exit position +# or another server depending what you have `leaveType` set too. +# default: false +leaveOnEnd: false + # What do you want to happen when a player leaves the lobby. If you are running a single server, maybe you want to send # them to the world hub. But if you are running a bungee-cord or velocity server, maybe you want to send them to the servers # hub. From 1005d4a8d8eef7aae6598bd4a96eea49f902ea80 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 16:30:55 -0400 Subject: [PATCH 08/68] custom model data, custom glow item, custom seeker ping --- .../hideAndSeek/configuration/Config.java | 34 +++++++++++-- .../configuration/ConfigManager.java | 9 ++++ .../hideAndSeek/game/EventListener.java | 49 ++++++++----------- .../tylermurphy/hideAndSeek/game/Game.java | 25 +++------- src/main/resources/config.yml | 18 +++++-- 5 files changed, 83 insertions(+), 52 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 589d3a2..39bc55f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -21,6 +21,7 @@ package net.tylermurphy.hideAndSeek.configuration; import com.cryptomorin.xseries.XItemStack; import com.cryptomorin.xseries.XMaterial; +import com.cryptomorin.xseries.XSound; import net.tylermurphy.hideAndSeek.util.Version; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -100,6 +101,11 @@ public class Config { lobbyItemLeavePosition, lobbyItemStartPosition; + public static float + seekerPingLeadingVolume, + seekerPingVolume, + seekerPingPitch; + public static List blockedCommands, blockedInteracts; @@ -124,7 +130,12 @@ public class Config { public static ItemStack lobbyLeaveItem, - lobbyStartItem; + lobbyStartItem, + glowPowerupItem; + + public static XSound + ringingSound, + heartbeatSound; public static void loadConfig() { @@ -196,6 +207,16 @@ public class Config { glowLength = Math.max(1, config.getInt("glow.time")); glowStackable = config.getBoolean("glow.stackable"); glowEnabled = config.getBoolean("glow.enabled") && Version.atLeast("1.9"); + if(glowEnabled) { + ConfigurationSection item = new YamlConfiguration().createSection("temp"); + item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("glow.name"))); + item.set("material", config.getString("glow.material")); + List lore = config.getStringList("glow.lore"); + if (lore != null && !lore.isEmpty()) item.set("lore", lore); + ItemStack temp = null; + try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){} + glowPowerupItem = temp; + } //Lobby minPlayers = Math.max(2, config.getInt("minPlayers")); @@ -210,6 +231,13 @@ public class Config { seekerPingLevel1 = config.getInt("seekerPing.distances.level1"); seekerPingLevel2 = config.getInt("seekerPing.distances.level2"); seekerPingLevel3 = config.getInt("seekerPing.distances.level3"); + seekerPingLeadingVolume = config.getFloat("seekerPing.sounds.leadingVolume"); + seekerPingVolume = config.getFloat("seekerPing.sounds.volume"); + seekerPingPitch = config.getFloat("seekerPing.sounds.pitch"); + Optional heartbeatOptional = XSound.matchXSound(config.getString("seekerPing.sounds.heartbeatNoise")); + heartbeatSound = heartbeatOptional.orElse(XSound.BLOCK_NOTE_BLOCK_BASEDRUM); + Optional ringingOptional = XSound.matchXSound(config.getString("seekerPing.sounds.ringingNoise")); + ringingSound = heartbeatOptional.orElse(XSound.BLOCK_NOTE_BLOCK_PLING); //Other nametagsVisible = config.getBoolean("nametagsVisible"); @@ -259,7 +287,7 @@ public class Config { item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.leave.name"))); item.set("material", config.getString("lobbyItems.leave.material")); if(Version.atLeast("1.14")){ - if(config.contains("lobbyItems.leave.model-data")){ + if(config.contains("lobbyItems.leave.model-data") && config.getInt("lobbyItems.leave.model-data") != 0){ config.set("model-data", config.getInt("lobbyItems.leave.model-data")); } } @@ -282,7 +310,7 @@ public class Config { lobbyItemStartAdmin = config.getBoolean("lobbyItems.start.adminOnly"); lobbyItemStartPosition = config.getInt("lobbyItems.start.position"); if(Version.atLeast("1.14")){ - if(config.contains("lobbyItems.start.model-data")){ + if(config.contains("lobbyItems.start.model-data") && config.getInt("lobbyItems.start.model-data") != 0){ config.set("model-data", config.getInt("lobbyItems.start.model-data")); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 53a30c2..3546fa8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -130,6 +130,15 @@ public class ConfigManager { return defaultConfig.getInt(path); } + public float getFloat(String path){ + float value = (float) config.getDouble(path); + if(value == 0){ + return (float) defaultConfig.getDouble(path); + } else { + return value; + } + } + public String getString(String path){ String value = config.getString(path); if(value == null){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 5995dbc..e464fba 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -32,7 +32,6 @@ import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import org.bukkit.entity.Snowball; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -42,7 +41,6 @@ import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.*; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.projectiles.ProjectileSource; @@ -239,24 +237,6 @@ public class EventListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onProjectile(ProjectileLaunchEvent event) { - if(Game.status != Status.PLAYING) return; - if(event.getEntity() instanceof Snowball) { - if(!glowEnabled) return; - Snowball snowball = (Snowball) event.getEntity(); - if(snowball.getShooter() instanceof Player) { - Player player = (Player) snowball.getShooter(); - if(Board.isHider(player)) { - Game.glow.onProjectile(); - snowball.remove(); - assert XMaterial.SNOWBALL.parseMaterial() != null; - player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); - } - } - } - } - @EventHandler(priority = EventPriority.HIGHEST) public void onFoodLevelChange(FoodLevelChangeEvent event) { if(event.getEntity() instanceof Player) { @@ -297,18 +277,19 @@ public class EventListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { if(!Board.isPlayer(event.getPlayer())) return; - if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())){ event.setCancelled(true); return; } - - if(Game.status != Status.STANDBY) return; - - ItemStack temp = event.getItem(); if(temp == null) return; + if(Game.status == Status.STANDBY) + onPlayerInteractLobby(temp, event); + if(Game.status == Status.PLAYING) + onPlayerInteractGame(temp, event); + } + private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event){ if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { event.setCancelled(true); Game.leave(event.getPlayer()); @@ -330,7 +311,20 @@ public class EventListener implements Listener { } Game.start(); } + } + private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event){ + if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { + if(!glowEnabled) return; + Player player = event.getPlayer(); + if(Board.isHider(player)) { + Game.glow.onProjectile(); + player.getInventory().remove(glowPowerupItem); + assert XMaterial.SNOWBALL.parseMaterial() != null; + player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); + event.setCancelled(true); + } + } } @EventHandler(priority = EventPriority.HIGHEST) @@ -344,9 +338,8 @@ public class EventListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST) - public void onItemDrop(PlayerDropItemEvent event) - { - if(Board.isPlayer(event.getPlayer()) && Game.status == Status.STANDBY){ + public void onItemDrop(PlayerDropItemEvent event) { + if(Board.isPlayer(event.getPlayer())){ event.setCancelled(true); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index c01682b..7488163 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -273,18 +273,7 @@ public class Game { for(PotionEffect effect : Items.HIDER_EFFECTS) player.addPotionEffect(effect); if(glowEnabled) { - assert XMaterial.SNOWBALL.parseMaterial() != null; - ItemStack snowball = new ItemStack(XMaterial.SNOWBALL.parseMaterial(), 1); - ItemMeta snowballMeta = snowball.getItemMeta(); - assert snowballMeta != null; - snowballMeta.setDisplayName("Glow Powerup"); - List snowballLore = new ArrayList<>(); - snowballLore.add("Throw to make all seekers glow"); - snowballLore.add("Last 30s, all hiders can see it"); - snowballLore.add("Time stacks on multi use"); - snowballMeta.setLore(snowballLore); - snowball.setItemMeta(snowballMeta); - player.getInventory().addItem(snowball); + player.getInventory().addItem(glowPowerupItem); } } } @@ -391,18 +380,18 @@ public class Game { } if(seekerPing) switch(tick%10) { case 0: - if(distance < seekerPingLevel1) XSound.BLOCK_NOTE_BLOCK_BASEDRUM.play(hider, .5f, 1f); - if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f); + if(distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch); + if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 3: - if(distance < seekerPingLevel1) XSound.BLOCK_NOTE_BLOCK_BASEDRUM.play(hider, .3f, 1f); - if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f); + if(distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingVolume, seekerPingPitch); + if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 6: - if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f); + if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 9: - if(distance < seekerPingLevel2) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f); + if(distance < seekerPingLevel2) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; } } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 9a82052..8e52343 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -99,6 +99,9 @@ glow: time: 30 stackable: true enabled: true + name: "Glow Powerup" + lore: [ "Throw to make all seekers glow", "Last 30s, all hiders can see it", "Time stacks on multi use" ] + material: SNOWBALL # The message prefixes displayed before messages. The message contents themselves # can be changed in localization.yml. @@ -124,21 +127,24 @@ lobby: # Below are the two items given to you when you join a lobby. A item to click to leave the lobby, and another # to start the game. Each of these items can be toggled separately, but only these items are currently supported. -# You can customize the material, name, lore, and position of the item. And finally, the start item is marked as -# adminOnly be default since the /hs start command is also admin by default. If you set adminOnly to false, only -# the item will become non admin only, not the command. +# You can customize the material, name, lore, and position of the item. You can also change the model data if your +# server is running 1.14 or above. Any earlier version, the model-data tag will be ignored; Model-data 0 is also ignored. +# Finally, the start item is marked as adminOnly be default since the /hs start command is also admin by default. +# If you set adminOnly to false, only the item will become non admin only, not the command. lobbyItems: leave: material: BED name: "&cLeave Lobby" lore: ["Go back to server hub"] position: 8 + model-data: 0 enabled: true start: material: CLOCK name: "&bStart Game" lore: [] position: 0 + model-data: 0 enabled: true adminOnly: true @@ -150,6 +156,12 @@ seekerPing: level1: 30 level2: 20 level3: 10 + sounds: + leadingVolume: 0.5 + volume: 0.3 + pitch: 1 + heartbeatNoise: BLOCK_NOTE_BLOCK_BASEDRUM + ringingNoise: BLOCK_NOTE_BLOCK_PLING enabled: true # Changes the default plugin language. Currently, Supported localizations are: From b870eac53b50605ad99482ab7208a9d2ebec84bc Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 16:35:15 -0400 Subject: [PATCH 09/68] Expand SQL Error messages --- .../java/net/tylermurphy/hideAndSeek/database/Database.java | 1 + .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index 8001368..25a4171 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -50,6 +50,7 @@ public class Database { conn = DriverManager.getConnection(url, config.toProperties()); } catch (SQLException e) { Main.plugin.getLogger().severe(e.getMessage()); + e.printStackTrace(); } return conn; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 7b9b476..5fa196c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -47,6 +47,7 @@ public class PlayerInfoTable { statement.executeUpdate(sql); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); } } @@ -74,6 +75,7 @@ public class PlayerInfoTable { rs.close(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); } catch (IOException e) { Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); e.printStackTrace(); @@ -102,6 +104,7 @@ public class PlayerInfoTable { return infoList; } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); } return null; } From 73f609bb87fddc497e7e661ec2880bac9801a11d Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 16:40:42 -0400 Subject: [PATCH 10/68] fix misplaced rs.close(); statement --- .../tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 5fa196c..e6f29b0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -62,15 +62,16 @@ public class PlayerInfoTable { statement.setBytes(1, bytes); ResultSet rs = statement.executeQuery(); if(rs.next()){ - rs.close(); connection.close(); - return new PlayerInfo( + PlayerInfo info = new PlayerInfo( uuid, rs.getInt("wins"), rs.getInt("seeker_wins"), rs.getInt("hider_wins"), rs.getInt("games_played") ); + rs.close(); + return info; } rs.close(); } catch (SQLException e){ From c2d298dbff76e81726e8149ef2c0f8c624c546ba Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 16:50:29 -0400 Subject: [PATCH 11/68] set model-data to correct configuration --- .../net/tylermurphy/hideAndSeek/configuration/Config.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 39bc55f..79571fc 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -288,7 +288,7 @@ public class Config { item.set("material", config.getString("lobbyItems.leave.material")); if(Version.atLeast("1.14")){ if(config.contains("lobbyItems.leave.model-data") && config.getInt("lobbyItems.leave.model-data") != 0){ - config.set("model-data", config.getInt("lobbyItems.leave.model-data")); + item.set("model-data", config.getInt("lobbyItems.leave.model-data")); } } List lore = config.getStringList("lobbyItems.leave.lore"); @@ -311,7 +311,7 @@ public class Config { lobbyItemStartPosition = config.getInt("lobbyItems.start.position"); if(Version.atLeast("1.14")){ if(config.contains("lobbyItems.start.model-data") && config.getInt("lobbyItems.start.model-data") != 0){ - config.set("model-data", config.getInt("lobbyItems.start.model-data")); + item.set("model-data", config.getInt("lobbyItems.start.model-data")); } } } From 97199843fa084bbd8bbea29f89cdeb6ff83df6a4 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 4 May 2022 16:56:33 -0400 Subject: [PATCH 12/68] dont close sql querty before geting result set --- .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index e6f29b0..142c263 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -62,7 +62,6 @@ public class PlayerInfoTable { statement.setBytes(1, bytes); ResultSet rs = statement.executeQuery(); if(rs.next()){ - connection.close(); PlayerInfo info = new PlayerInfo( uuid, rs.getInt("wins"), @@ -71,6 +70,7 @@ public class PlayerInfoTable { rs.getInt("games_played") ); rs.close(); + connection.close(); return info; } rs.close(); From dbc6291397c33b21b1c0124bfb15e6f2e3568d46 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 5 May 2022 09:06:22 -0400 Subject: [PATCH 13/68] actionbar messages --- .../tylermurphy/hideAndSeek/game/Game.java | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 7488163..992570d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -21,8 +21,7 @@ package net.tylermurphy.hideAndSeek.game; import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import com.cryptomorin.xseries.XMaterial; -import com.cryptomorin.xseries.XSound; +import com.cryptomorin.xseries.messages.ActionBar; import com.cryptomorin.xseries.messages.Titles; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; @@ -45,10 +44,10 @@ import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.util.Packet; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import javax.swing.*; import java.io.File; import java.util.*; import java.util.stream.Collectors; @@ -139,12 +138,12 @@ public class Game { status = Status.STARTING; int temp = gameId; broadcastMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30)); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); - sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); + sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> { if(temp != gameId) return; broadcastMessage(messagePrefix + message("START")); @@ -423,10 +422,14 @@ public class Game { } } - private static void sendDelayedMessage(String message, int gameId, int delay) { + private static void sendDelayedActionbar(String message, int gameId, int delay) { Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> { - if(gameId == Game.gameId) - broadcastMessage(message); + if(gameId == Game.gameId){ + for(Player player : Board.getPlayers()){ + ActionBar.clearActionBar(player); + ActionBar.sendActionBar(player,message); + } + } }, delay); } From 36027e007e512d54e7e3cd8fb66774cc9c5e43f2 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 5 May 2022 12:22:04 -0400 Subject: [PATCH 14/68] countdown titles, and possible config save for utf8 --- .../hideAndSeek/configuration/Config.java | 11 ++++++ .../configuration/ConfigManager.java | 29 ++++++++------- .../tylermurphy/hideAndSeek/game/Game.java | 37 +++++++++++-------- .../hideAndSeek/util/CountdownDisplay.java | 26 +++++++++++++ src/main/resources/config.yml | 13 +++++++ 5 files changed, 87 insertions(+), 29 deletions(-) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 79571fc..ee2f8b6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -22,6 +22,8 @@ package net.tylermurphy.hideAndSeek.configuration; import com.cryptomorin.xseries.XItemStack; import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.util.CountdownDisplay; import net.tylermurphy.hideAndSeek.util.Version; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -136,6 +138,9 @@ public class Config { public static XSound ringingSound, heartbeatSound; + + public static CountdownDisplay + countdownDisplay; public static void loadConfig() { @@ -249,6 +254,12 @@ public class Config { locale = config.getString("locale", "local"); blockedCommands = config.getStringList("blockedCommands"); leaveOnEnd = config.getBoolean("leaveOnEnd"); + try { + countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay")); + } catch (IllegalArgumentException e){ + countdownDisplay = CountdownDisplay.CHAT; + Main.plugin.getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!"); + } blockedInteracts = new ArrayList<>(); List tempInteracts = config.getStringList("blockedInteracts"); for(String id : tempInteracts){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 3546fa8..0168dc5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -52,16 +52,20 @@ public class ConfigManager { this.config = YamlConfiguration.loadConfiguration(file); - InputStream input = Main.plugin.getResource(file.getName()); - if(input == null){ + FileInputStream input = null; + try{ + input = new FileInputStream(file); + } catch (Exception e){ throw new RuntimeException("Could not create input stream for "+file.getPath()); } - InputStreamReader reader = new InputStreamReader(input); + + InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8); this.defaultConfig = YamlConfiguration.loadConfiguration(reader); try{ input.close(); reader.close(); - } catch (IOException ignored){} + } catch (IOException ignored){ + } } public ConfigManager(String filename, String defaultFilename){ @@ -221,7 +225,7 @@ public class ConfigManager { while((c = reader.read()) != -1){ textBuilder.append((char) c); } - String yamlString = textBuilder.toString(); + String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8); Map temp = config.getValues(true); for(Map.Entry entry: temp.entrySet()){ if(entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List){ @@ -246,26 +250,25 @@ public class ConfigManager { if(entry.getValue() instanceof List){ if(((List) entry.getValue()).isEmpty()) continue; replace = "["; - for(Object o : (List)entry.getValue()){ - replace = replace + o.toString() + ", "; + for(Object o : (List)entry.getValue()){ + replace = replace + new String(o.toString().getBytes(), StandardCharsets.UTF_8) + ", "; } replace = replace.substring(0, replace.length()-2); replace = replace + "]"; } else { - replace = entry.getValue().toString(); + replace = new String(entry.getValue().toString().getBytes(), StandardCharsets.UTF_8); } if(entry.getValue() instanceof String){ replace = "\"" + replace + "\""; } StringBuilder builder = new StringBuilder(yamlString); builder.replace(start+1, end, replace); - yamlString = builder.toString(); + yamlString = new String(builder.toString().getBytes(), StandardCharsets.UTF_8); } } - OutputStream os = new FileOutputStream(file); - PrintWriter out = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true); - out.print(yamlString); - out.close(); + Writer fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); + fileWriter.write(yamlString); + fileWriter.close(); } catch (IOException e){ e.printStackTrace(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 992570d..a886247 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -28,9 +28,7 @@ import com.google.common.io.ByteStreams; import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.database.Database; -import net.tylermurphy.hideAndSeek.util.Status; -import net.tylermurphy.hideAndSeek.util.Version; -import net.tylermurphy.hideAndSeek.util.WinType; +import net.tylermurphy.hideAndSeek.util.*; import net.tylermurphy.hideAndSeek.world.WorldLoader; import org.bukkit.*; import org.bukkit.attribute.Attribute; @@ -41,13 +39,11 @@ import org.bukkit.entity.Firework; import org.bukkit.entity.Player; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.util.Packet; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import javax.swing.*; import java.io.File; import java.util.*; import java.util.stream.Collectors; @@ -137,16 +133,18 @@ public class Game { Board.reloadGameBoards(); status = Status.STARTING; int temp = gameId; - broadcastMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30)); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); - sendDelayedActionbar(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); + if(countdownDisplay != CountdownDisplay.TITLE) { + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30), gameId, 0); + } + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20); + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25); + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27); + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); + sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> { if(temp != gameId) return; - broadcastMessage(messagePrefix + message("START")); + sendHideCountdownMessage(messagePrefix + message("START"), gameId, 0); for(Player player : Board.getPlayers()) resetPlayer(player); status = Status.PLAYING; }, 20 * 30); @@ -422,12 +420,19 @@ public class Game { } } - private static void sendDelayedActionbar(String message, int gameId, int delay) { + private static void sendHideCountdownMessage(String message, int gameId, int delay) { Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> { if(gameId == Game.gameId){ for(Player player : Board.getPlayers()){ - ActionBar.clearActionBar(player); - ActionBar.sendActionBar(player,message); + if(countdownDisplay == CountdownDisplay.CHAT){ + player.sendMessage(message); + } else if(countdownDisplay == CountdownDisplay.ACTIONBAR){ + ActionBar.clearActionBar(player); + ActionBar.sendActionBar(player,message); + } else if(countdownDisplay == CountdownDisplay.TITLE){ + Titles.clearTitle(player); + Titles.sendTitle(player, 10, 71, 10, null, message); + } } } }, delay); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java b/src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java new file mode 100644 index 0000000..477f7ca --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java @@ -0,0 +1,26 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.util; + +public enum CountdownDisplay { + CHAT, + ACTIONBAR, + TITLE +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 8e52343..cdf88ac 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -14,6 +14,19 @@ gameLength: 1200 # default: true announceMessagesToNonPlayers: true +# When the game is starting, the plugin will state there is x seconds left to hide. +# You change where countdown messages to be displayed: in the chat, action bar, or a title. +# Below you can set CHAT, ACTIONBAR, or TITLE. Any invalid option will revert to CHAT. +# +# CHAT - Messages will be displayed in the chat +# +# ACTIONBAR - Messages will be displayed in the action bar (area above the hotbar) +# +# TITLE - Messages will be displayed as a title +# +# default: CHAT +hideCountdownDisplay: CHAT + # Allow Hiders to see their own teams nametags as well as seekers. Seekers can never see nametags regardless. # default: false nametagsVisible: false From acb7da8337cd559a39c2177a006f30d7849ccae7 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 5 May 2022 12:58:57 -0400 Subject: [PATCH 15/68] custom load config --- .../hideAndSeek/configuration/Config.java | 4 +- .../configuration/ConfigManager.java | 93 +++++++++---------- .../hideAndSeek/configuration/Items.java | 2 +- .../configuration/Localization.java | 2 +- 4 files changed, 49 insertions(+), 52 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index ee2f8b6..835b03d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -144,9 +144,9 @@ public class Config { public static void loadConfig() { - config = new ConfigManager("config.yml"); + config = ConfigManager.create("config.yml"); config.saveConfig(); - leaderboard = new ConfigManager("leaderboard.yml"); + leaderboard = ConfigManager.create("leaderboard.yml"); //Spawn spawnPosition = new Vector( diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 0168dc5..4010ab4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -21,6 +21,7 @@ package net.tylermurphy.hideAndSeek.configuration; import net.tylermurphy.hideAndSeek.Main; import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import java.io.*; @@ -35,9 +36,18 @@ public class ConfigManager { private YamlConfiguration config,defaultConfig; private String defaultFilename; - public ConfigManager(String filename){ + public static ConfigManager create(String filename){ + return new ConfigManager(filename, filename); + } + + public static ConfigManager create(String filename, String defaultFilename){ + return new ConfigManager(filename, defaultFilename); + } + + private ConfigManager(String filename, String defaultFilename){ + + this.defaultFilename = defaultFilename; this.file = new File(Main.data, filename); - this.defaultFilename = file.getName(); File folder = Main.data; if(!folder.exists()){ @@ -47,64 +57,51 @@ public class ConfigManager { } if(!file.exists()){ - saveDefaultConfiguration(); + try{ + InputStream input = Main.plugin.getResource(defaultFilename); + if(input == null){ + throw new RuntimeException("Could not create input stream for "+defaultFilename); + } + java.nio.file.Files.copy(input, file.toPath()); + input.close(); + } catch(IOException e){ + e.printStackTrace(); + } } - this.config = YamlConfiguration.loadConfiguration(file); - - FileInputStream input = null; - try{ - input = new FileInputStream(file); - } catch (Exception e){ + FileInputStream fileInputStream; + try { + fileInputStream = new FileInputStream(file); + } catch (FileNotFoundException e){ throw new RuntimeException("Could not create input stream for "+file.getPath()); } - - InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8); - this.defaultConfig = YamlConfiguration.loadConfiguration(reader); - try{ - input.close(); - reader.close(); - } catch (IOException ignored){ - } - } - - public ConfigManager(String filename, String defaultFilename){ - - this.defaultFilename = defaultFilename; - this.file = new File(Main.data, filename); - - if(!file.exists()){ - saveDefaultConfiguration(); + InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8); + this.config = new YamlConfiguration(); + try { + this.config.load(reader); + } catch(InvalidConfigurationException | IOException e){ + throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); } - this.config = YamlConfiguration.loadConfiguration(file); - - InputStream input = Main.plugin.getResource(defaultFilename); + InputStream input = this.getClass().getClassLoader().getResourceAsStream(defaultFilename); if(input == null){ throw new RuntimeException("Could not create input stream for "+defaultFilename); } - InputStreamReader reader = new InputStreamReader(input); - this.defaultConfig = YamlConfiguration.loadConfiguration(reader); - try{ - input.close(); - reader.close(); - } catch (IOException e){ - Main.plugin.getLogger().severe("Couldn't find "+defaultFilename+" internally. Did you set an incorrect local?"); - Main.plugin.getServer().getPluginManager().disablePlugin(Main.plugin); - throw new RuntimeException(); + InputStreamReader default_reader = new InputStreamReader(input, StandardCharsets.UTF_8); + this.defaultConfig = new YamlConfiguration(); + try { + this.defaultConfig.load(reader); + } catch(InvalidConfigurationException | IOException e){ + throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); } - } - private void saveDefaultConfiguration(){ try{ - InputStream input = Main.plugin.getResource(defaultFilename); - if(input == null){ - throw new RuntimeException("Could not create input stream for "+defaultFilename); - } - java.nio.file.Files.copy(input, file.toPath()); input.close(); - } catch(IOException e){ - e.printStackTrace(); + fileInputStream.close(); + reader.close(); + default_reader.close(); + } catch (IOException e){ + throw new RuntimeException("Unable to finalize loading of config files."); } } @@ -136,7 +133,7 @@ public class ConfigManager { public float getFloat(String path){ float value = (float) config.getDouble(path); - if(value == 0){ + if(value == 0.0F){ return (float) defaultConfig.getDouble(path); } else { return value; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index e42001f..22ec84b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -38,7 +38,7 @@ public class Items { public static void loadItems() { - ConfigManager manager = new ConfigManager("items.yml"); + ConfigManager manager = ConfigManager.create("items.yml"); SEEKER_ITEMS = new ArrayList<>(); ConfigurationSection SeekerItems = manager.getConfigurationSection("items.seeker"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java index fc2983a..d477117 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java @@ -36,7 +36,7 @@ public class Localization { public static void loadLocalization() { - ConfigManager manager = new ConfigManager("localization.yml", "lang/localization_"+Config.locale +".yml"); + ConfigManager manager = ConfigManager.create("localization.yml", "lang/localization_"+Config.locale +".yml"); int PLUGIN_VERSION = manager.getDefaultInt("version"); int VERSION = manager.getInt("version"); From 50f3fc4b7cfd8711aac216ba43bec3fa0ec3767f Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 5 May 2022 17:05:09 -0400 Subject: [PATCH 16/68] utf8 finally working --- .../configuration/ConfigManager.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 4010ab4..78d5c6e 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -90,15 +90,13 @@ public class ConfigManager { InputStreamReader default_reader = new InputStreamReader(input, StandardCharsets.UTF_8); this.defaultConfig = new YamlConfiguration(); try { - this.defaultConfig.load(reader); + this.defaultConfig.load(default_reader); } catch(InvalidConfigurationException | IOException e){ throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); } try{ - input.close(); fileInputStream.close(); - reader.close(); default_reader.close(); } catch (IOException e){ throw new RuntimeException("Unable to finalize loading of config files."); @@ -216,7 +214,7 @@ public class ConfigManager { if(is == null){ throw new RuntimeException("Could not create input stream for "+defaultFilename); } - StringBuilder textBuilder = new StringBuilder(); + StringBuilder textBuilder = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8)); Reader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name()))); int c; while((c = reader.read()) != -1){ @@ -243,24 +241,27 @@ public class ConfigManager { int start = yamlString.indexOf(' ', index); int end = yamlString.indexOf('\n', index); if(end == -1) end = yamlString.length(); - String replace; + StringBuilder replace = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8)); if(entry.getValue() instanceof List){ if(((List) entry.getValue()).isEmpty()) continue; - replace = "["; + replace.append("["); for(Object o : (List)entry.getValue()){ - replace = replace + new String(o.toString().getBytes(), StandardCharsets.UTF_8) + ", "; + replace.append(new String(o.toString().getBytes(), StandardCharsets.UTF_8)).append(", "); } - replace = replace.substring(0, replace.length()-2); - replace = replace + "]"; + replace = new StringBuilder(replace.substring(0, replace.length() - 2)); + replace.append("]"); } else { - replace = new String(entry.getValue().toString().getBytes(), StandardCharsets.UTF_8); + replace.append(entry.getValue()); } if(entry.getValue() instanceof String){ - replace = "\"" + replace + "\""; + replace.append("\""); + replace.reverse(); + replace.append("\""); + replace.reverse(); } StringBuilder builder = new StringBuilder(yamlString); - builder.replace(start+1, end, replace); - yamlString = new String(builder.toString().getBytes(), StandardCharsets.UTF_8); + builder.replace(start+1, end, replace.toString()); + yamlString = builder.toString(); } } Writer fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); From 651d0c5a544bf599176b0842411fbc3534ac78c4 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 6 May 2022 07:33:48 -0400 Subject: [PATCH 17/68] split catch block in config manager --- .../hideAndSeek/configuration/ConfigManager.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 78d5c6e..c844924 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -79,8 +79,10 @@ public class ConfigManager { this.config = new YamlConfiguration(); try { this.config.load(reader); - } catch(InvalidConfigurationException | IOException e){ + } catch(InvalidConfigurationException e){ throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); + } catch(IOException e){ + throw new RuntimeException("Could not access file: "+file.getPath()); } InputStream input = this.getClass().getClassLoader().getResourceAsStream(defaultFilename); @@ -91,8 +93,10 @@ public class ConfigManager { this.defaultConfig = new YamlConfiguration(); try { this.defaultConfig.load(default_reader); - } catch(InvalidConfigurationException | IOException e){ + } catch(InvalidConfigurationException e){ throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); + } catch(IOException e){ + throw new RuntimeException("Could not access file: "+file.getPath()); } try{ From 1b0985710c66a56c07d38e3c2fe75e5dbaaf102b Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 6 May 2022 09:00:46 -0400 Subject: [PATCH 18/68] special characters in lists fix, empty list fix --- .../hideAndSeek/configuration/ConfigManager.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index c844924..4bb1a83 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -247,13 +247,16 @@ public class ConfigManager { if(end == -1) end = yamlString.length(); StringBuilder replace = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8)); if(entry.getValue() instanceof List){ - if(((List) entry.getValue()).isEmpty()) continue; - replace.append("["); - for(Object o : (List)entry.getValue()){ - replace.append(new String(o.toString().getBytes(), StandardCharsets.UTF_8)).append(", "); + if(((List) entry.getValue()).isEmpty()){ + replace.append("[]"); + } else { + replace.append("["); + for (Object o : (List) entry.getValue()) { + replace.append(o.toString()).append(", "); + } + replace = new StringBuilder(replace.substring(0, replace.length() - 2)); + replace.append("]"); } - replace = new StringBuilder(replace.substring(0, replace.length() - 2)); - replace.append("]"); } else { replace.append(entry.getValue()); } From bd37044e10f06d269f8915bcc06237a6edbe65dc Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 6 May 2022 10:26:27 -0400 Subject: [PATCH 19/68] add empty space to titles --- src/main/java/net/tylermurphy/hideAndSeek/game/Game.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index a886247..d61d11f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -431,7 +431,7 @@ public class Game { ActionBar.sendActionBar(player,message); } else if(countdownDisplay == CountdownDisplay.TITLE){ Titles.clearTitle(player); - Titles.sendTitle(player, 10, 71, 10, null, message); + Titles.sendTitle(player, 10, 40, 10, " ", message); } } } From 134444243a491a5b22c2cc4219e8fdd361ce2693 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 6 May 2022 12:22:04 -0400 Subject: [PATCH 20/68] option to disable mapsave --- .../hideAndSeek/command/SaveMap.java | 4 +++ .../hideAndSeek/command/SetSpawnLocation.java | 2 +- .../hideAndSeek/command/Setup.java | 11 +++++--- .../hideAndSeek/configuration/Config.java | 4 ++- .../hideAndSeek/game/EventListener.java | 10 ++++---- .../tylermurphy/hideAndSeek/game/Game.java | 25 ++++++++++++------- src/main/resources/config.yml | 12 +++++++-- .../resources/lang/localization_de-DE.yml | 1 + .../resources/lang/localization_en-US.yml | 1 + 9 files changed, 48 insertions(+), 22 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java index c48e1c6..f5e63a5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java @@ -36,6 +36,10 @@ public class SaveMap implements ICommand { public static boolean runningBackup = false; public void execute(CommandSender sender, String[] args) { + if(!mapSaveEnabled){ + sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED")); + return; + } if(Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java index 7afe861..d5e1cba 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java @@ -56,7 +56,7 @@ public class SetSpawnLocation implements ICommand { if(world == null){ throw new RuntimeException("Unable to get world: " + spawnWorld); } - if(!world.getName().equals(spawnWorld)){ + if(mapSaveEnabled && !world.getName().equals(spawnWorld)){ Game.worldLoader.unloadMap(); Game.worldLoader = new WorldLoader(world.getName()); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java index 74c29bf..14a5d6f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java @@ -19,6 +19,7 @@ package net.tylermurphy.hideAndSeek.command; +import net.tylermurphy.hideAndSeek.game.Game; import org.bukkit.command.CommandSender; import net.tylermurphy.hideAndSeek.Main; @@ -51,10 +52,12 @@ public class Setup implements ICommand { msg = msg + "\n" + message("SETUP_BOUNDS"); count++; } - File destenation = new File(Main.root+File.separator+"hideandseek_"+spawnWorld); - if(!destenation.exists()) { - msg = msg + "\n" + message("SETUP_SAVEMAP"); - count++; + if(mapSaveEnabled) { + File destenation = new File(Main.root + File.separator + Game.getGameWorld()); + if (!destenation.exists()) { + msg = msg + "\n" + message("SETUP_SAVEMAP"); + count++; + } } if(count < 1) { sender.sendMessage(messagePrefix + message("SETUP_COMPLETE")); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 835b03d..ec4e84e 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -78,7 +78,8 @@ public class Config { seekerPing, bungeeLeave, lobbyItemStartAdmin, - leaveOnEnd; + leaveOnEnd, + mapSaveEnabled; public static int minPlayers, @@ -201,6 +202,7 @@ public class Config { saveMinZ = config.getInt("bounds.min.z"); saveMaxX = config.getInt("bounds.max.x"); saveMaxZ = config.getInt("bounds.max.z"); + mapSaveEnabled = config.getBoolean("mapSaveEnabled"); //Taunt tauntEnabled = config.getBoolean("taunt.enabled"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index e464fba..35089e4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -61,12 +61,12 @@ public class EventListener implements Listener { if(autoJoin){ Game.join(event.getPlayer()); } else if(teleportToExit) { - if (event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { + if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().setGameMode(GameMode.ADVENTURE); } } else { - if (event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld)) { + if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { if(Game.status != Status.STANDBY){ Game.join(event.getPlayer()); } else { @@ -115,10 +115,10 @@ public class EventListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onMove(PlayerMoveEvent event){ - if(!event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld)) return; + if(!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; if(event.getPlayer().hasPermission("hideandseek.leavebounds")) return; if(event.getTo() == null || event.getTo().getWorld() == null) return; - if(!event.getTo().getWorld().getName().equals("hideandseek_" + spawnWorld)) return; + if(!event.getTo().getWorld().getName().equals(Game.getGameWorld())) return; if(event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ){ event.setCancelled(true); } @@ -211,7 +211,7 @@ public class EventListener implements Listener { } else { player.setHealth(player.getMaxHealth()); } - player.teleport(new Location(Bukkit.getWorld("hideandseek_" + spawnWorld), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); if(Version.atLeast("1.9")){ XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index d61d11f..16caee4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -89,7 +89,7 @@ public class Game { public static void start(Player seeker){ if(status == Status.STARTING || status == Status.PLAYING) return; - if(worldLoader.getWorld() != null) { + if(mapSaveEnabled && worldLoader.getWorld() != null) { worldLoader.rollback(); } else { worldLoader.loadMap(); @@ -105,7 +105,7 @@ public class Game { for(Player player : Board.getPlayers()) { player.getInventory().clear(); player.setGameMode(GameMode.ADVENTURE); - player.teleport(new Location(Bukkit.getWorld("hideandseek_"+spawnWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); for(PotionEffect effect : player.getActivePotionEffects()){ player.removePotionEffect(effect.getType()); } @@ -125,7 +125,7 @@ public class Game { if (glowEnabled) glow = new Glow(); worldBorder = new Border(); - worldBorder.resetWorldborder("hideandseek_"+spawnWorld); + worldBorder.resetWorldborder(getGameWorld()); if(gameLength > 0) timeLeft = gameLength; for(Player player : Board.getPlayers()) @@ -184,7 +184,7 @@ public class Game { winners.add(Board.getFirstSeeker().getUniqueId()); Database.playerInfo.addWins(players, winners, type); } - worldBorder.resetWorldborder("hideandseek_"+spawnWorld); + worldBorder.resetWorldborder(getGameWorld()); for(Player player : Board.getPlayers()) { if(Version.atLeast("1.9")){ for(Player temp : Board.getPlayers()) { @@ -220,7 +220,7 @@ public class Game { } } EventListener.temp_loc.clear(); - worldLoader.unloadMap(); + if(mapSaveEnabled) worldLoader.unloadMap(); Board.reloadLobbyBoards(); } @@ -228,11 +228,18 @@ public class Game { if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; - File destenation = new File(Main.root+File.separator+"hideandseek_"+spawnWorld); - if(!destenation.exists()) return true; + if(mapSaveEnabled) { + File destenation = new File(Main.root + File.separator + getGameWorld()); + if (!destenation.exists()) return true; + } return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; } + public static String getGameWorld(){ + if(mapSaveEnabled) return "hideandseek_"+spawnWorld; + else return spawnWorld; + } + public static void onTick() { if(isNotSetup()) return; if(status == Status.STANDBY) whileWaiting(); @@ -294,7 +301,7 @@ public class Game { player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); player.setGameMode(GameMode.SPECTATOR); Board.createGameBoard(player); - player.teleport(new Location(Bukkit.getWorld("hideandseek_"+spawnWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); } @@ -601,7 +608,7 @@ class Border { running = true; broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change)); currentWorldborderSize -= worldborderChange; - World world = Bukkit.getWorld("hideandseek_"+spawnWorld); + World world = Bukkit.getWorld(Game.getGameWorld()); assert world != null; org.bukkit.WorldBorder border = world.getWorldBorder(); border.setSize(border.getSize()-change,30); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index cdf88ac..88eab62 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -60,12 +60,12 @@ teleportToExit: false # Normally when the game ends, players are set back to the lobby to play another game. # You can disable this, and empty the lobby after the game finishes. This is like everyone # running /hs leave at the end of the game. Players will leave either to the exit position -# or another server depending what you have `leaveType` set too. +# or another server depending on what you have `leaveType` set too. # default: false leaveOnEnd: false # What do you want to happen when a player leaves the lobby. If you are running a single server, maybe you want to send -# them to the world hub. But if you are running a bungee-cord or velocity server, maybe you want to send them to the servers +# them to the world hub. But if you are running a bungee-cord or velocity server, maybe you want to send them to the servers' # hub. # # EXIT - Sends the player to the specified exit position set by /hs setexit @@ -79,6 +79,14 @@ leaveType: EXIT # players too. leaveServer: hub +# By default, the plugin forces you to use a map save to protect from changes to a map thought a game play though. It copies your +# hide-and-seek world to a separate world, and loads the game there to contain the game in an isolated and backed up map This allows you to +# not worry about your hide-and-seek map from changing, as all changes are made are in a separate world file that doesn't get saved. Once the game +# ends, it unloads the map and doesn't save. Then reloads the duplicate to the original state, rolling back the map for the next game. +# It is highly recommended that you keep this set to true unless you have other means of protecting your hide-and-seek map. +# default: true +mapSaveEnabled: true + # The worldborder closes every interval, which is evey [delay] in minutes. # Thw worldborder starts at [size], and decreases 100 blocks every interval. # x & z are the center location. [enabled] is whenever the border is enabled. diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index d560d24..5fd80d6 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -30,6 +30,7 @@ Localization: MAPSAVE_WARNING: "All commands will be disabled whenthe save is in progress. Do not turn off the server." MAPSAVE_END: "Speichervorgang abgeschlossen." MAPSAVE_ERROR: "Aktuelle Weltkarte konnte nicht gefunden werden." + MAPSAVE_DISABLED: "Mapsave ist in config.yml deaktiviert." WORLDBORDER_DISABLE: "World Border ausgeschaltet." WORLDBORDER_INVALID_INPUT: "Ungültiger Wert: {AMOUNT}" WORLDBORDER_MIN_SIZE: "World Border darf nicht geringer als 100 Blöcke sein." diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index 1757877..b047bdb 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -30,6 +30,7 @@ Localization: MAPSAVE_WARNING: "All commands will be disabled when the save is in progress. Do not turn off the server." MAPSAVE_END: "Map save complete." MAPSAVE_ERROR: "Couldn't find current map." + MAPSAVE_DISABLED: "Mapsave is disabled in config.yml." WORLDBORDER_DISABLE: "Disabled world border." WORLDBORDER_INVALID_INPUT: "Invalid integer {AMOUNT}." WORLDBORDER_MIN_SIZE: "World border cannot be smaller than 100 blocks." From e89e5f932c77034038c1fe166d1dfe2151a258f2 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 7 May 2022 23:54:48 -0400 Subject: [PATCH 21/68] rewrite database and damage event, add placeholders --- pom.xml | 10 ++ .../net/tylermurphy/hideAndSeek/Main.java | 5 + .../tylermurphy/hideAndSeek/command/Wins.java | 4 +- .../hideAndSeek/configuration/Config.java | 4 +- .../hideAndSeek/database/Database.java | 8 - .../hideAndSeek/database/PlayerInfo.java | 13 +- .../hideAndSeek/database/PlayerInfoTable.java | 126 ++++++++++----- .../tylermurphy/hideAndSeek/game/Board.java | 36 +++++ .../hideAndSeek/game/EventListener.java | 153 ++++++++---------- .../tylermurphy/hideAndSeek/game/Game.java | 4 +- .../hideAndSeek/util/PAPIExpansion.java | 128 +++++++++++++++ src/main/resources/config.yml | 7 + 12 files changed, 353 insertions(+), 145 deletions(-) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java diff --git a/pom.xml b/pom.xml index 4f73ae1..8073d7a 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,10 @@ dmulloy2-repo https://repo.dmulloy2.net/repository/public/ + + placeholderapi + https://repo.extendedclip.com/content/repositories/placeholderapi/ + @@ -103,5 +107,11 @@ XSeries 8.7.1 + + me.clip + placeholderapi + 2.11.1 + provided + \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index ac6c2d5..cf73757 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -23,6 +23,7 @@ import java.io.File; import java.util.List; import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.util.PAPIExpansion; import net.tylermurphy.hideAndSeek.util.UUIDFetcher; import org.bukkit.Bukkit; @@ -74,6 +75,10 @@ public class Main extends JavaPlugin implements Listener { },0,1).getTaskId(); Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); + + if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + new PAPIExpansion().register(); + } } public void onDisable() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index dfa5338..9140f49 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -66,8 +66,8 @@ public class Wins implements ICommand { message = message + message("INFORMATION_FOR").addPlayer(name) + "\n"; message = message + "==============================\n"; message = message + String.format("%sTOTAL WINS: %s%s\n%sHIDER WINS: %s%s\n%sSEEKER WINS: %s%s\n%sGAMES PLAYED: %s", - ChatColor.YELLOW, ChatColor.WHITE, info.wins, ChatColor.GOLD, ChatColor.WHITE, info.hider_wins, - ChatColor.RED, ChatColor.WHITE, info.seeker_wins, ChatColor.WHITE, info.games_played); + ChatColor.YELLOW, ChatColor.WHITE, info.seeker_wins+info.hider_wins, ChatColor.GOLD, ChatColor.WHITE, info.hider_wins, + ChatColor.RED, ChatColor.WHITE, info.seeker_wins, ChatColor.WHITE, info.seeker_games+info.hider_games); message = message + ChatColor.WHITE + "" + ChatColor.BOLD + "\n=============================="; sender.sendMessage(message); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index ec4e84e..f94ba0b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -79,7 +79,8 @@ public class Config { bungeeLeave, lobbyItemStartAdmin, leaveOnEnd, - mapSaveEnabled; + mapSaveEnabled, + allowNaturalCauses; public static int minPlayers, @@ -251,6 +252,7 @@ public class Config { permissionsRequired = config.getBoolean("permissionsRequired"); gameLength = config.getInt("gameLength"); pvpEnabled = config.getBoolean("pvp"); + allowNaturalCauses = config.getBoolean("allowNaturalCauses"); autoJoin = config.getBoolean("autoJoin"); teleportToExit = config.getBoolean("teleportToExit"); locale = config.getString("locale", "local"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index 25a4171..fe5ac5b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -55,14 +55,6 @@ public class Database { return conn; } - protected static InputStream convertUniqueId(UUID uuid) { - byte[] bytes = new byte[16]; - ByteBuffer.wrap(bytes) - .putLong(uuid.getMostSignificantBits()) - .putLong(uuid.getLeastSignificantBits()); - return new ByteArrayInputStream(bytes); - } - protected static UUID convertBinaryStream(InputStream stream) { ByteBuffer buffer = ByteBuffer.allocate(16); try { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java index 8464b54..5fbb96b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java @@ -24,14 +24,17 @@ import java.util.UUID; public class PlayerInfo { public UUID uuid; - public int wins, hider_wins, seeker_wins, games_played; + public int hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths; - public PlayerInfo(UUID uuid, int wins, int hider_wins, int seeker_wins, int games_played){ + public PlayerInfo(UUID uuid, int hider_wins, int seeker_wins, int hider_games, int seeker_games, int hider_kills, int seeker_kills, int hider_deaths, int seeker_deaths) { this.uuid = uuid; - this.wins = wins; this.hider_wins = hider_wins; this.seeker_wins = seeker_wins; - this.games_played = games_played; + this.hider_games = hider_games; + this.seeker_games = seeker_games; + this.hider_kills = hider_kills; + this.seeker_kills = seeker_kills; + this.hider_deaths = hider_deaths; + this.seeker_deaths = seeker_deaths; } - } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 142c263..06c036d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -19,28 +19,37 @@ package net.tylermurphy.hideAndSeek.database; +import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.configuration.Config; +import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.util.WinType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.ByteBuffer; import java.sql.*; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; +import java.util.*; public class PlayerInfoTable { + private static final Map CACHE = new HashMap<>(); + protected PlayerInfoTable(){ - String sql = "CREATE TABLE IF NOT EXISTS player_info (\n" + String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n" + " uuid BINARY(16) PRIMARY KEY,\n" - + " wins int NOT NULL,\n" - + " seeker_wins int NOT NULL,\n" + " hider_wins int NOT NULL,\n" - + " games_played int NOT NULL\n" + + " seeker_wins int NOT NULL,\n" + + " hider_games int NOT NULL\n" + + " seeker_games int NOT NULL\n" + + " hider_kills int NOT NULL\n" + + " seeker_kills int NOT NULL\n" + + " hider_deaths int NOT NULL\n" + + " seeker_deaths int NOT NULL\n" + ");"; try(Connection connection = Database.connect(); Statement statement = connection.createStatement()){ @@ -51,52 +60,87 @@ public class PlayerInfoTable { } } - public PlayerInfo getInfo(UUID uuid){ - String sql = "SELECT * FROM player_info WHERE uuid = ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ - InputStream is = Database.convertUniqueId(uuid); - byte[] bytes = new byte[is.available()]; - if(is.read(bytes) == -1){ - throw new IOException("Failed to read bytes from input stream"); + private byte[] encodeUUID(UUID uuid){ + try { + byte[] bytes = new byte[16]; + ByteBuffer.wrap(bytes) + .putLong(uuid.getMostSignificantBits()) + .putLong(uuid.getLeastSignificantBits()); + InputStream is = new ByteArrayInputStream(bytes); + byte[] result = new byte[is.available()]; + if (is.read(result) == -1) { + Main.plugin.getLogger().severe("IO Error: Failed to read bytes from input stream"); + return new byte[0]; } - statement.setBytes(1, bytes); + return result; + } catch (IOException e){ + Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); + return new byte[0]; + } + } + + private UUID decodeUUID(byte[] bytes){ + InputStream is = new ByteArrayInputStream(bytes); + ByteBuffer buffer = ByteBuffer.allocate(16); + try { + buffer.put(ByteStreams.toByteArray(is)); + buffer.flip(); + return new UUID(buffer.getLong(), buffer.getLong()); + } catch (IOException e) { + Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); + } + return null; + } + + @NotNull + public PlayerInfo getInfo(UUID uuid){ + String sql = "SELECT * FROM hs_data WHERE uuid = ?;"; + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); if(rs.next()){ PlayerInfo info = new PlayerInfo( uuid, - rs.getInt("wins"), - rs.getInt("seeker_wins"), rs.getInt("hider_wins"), - rs.getInt("games_played") + rs.getInt("seeker_wins"), + rs.getInt("hider_games"), + rs.getInt("seeker_games"), + rs.getInt("hider_kills"), + rs.getInt("seeker_kills"), + rs.getInt("hider_deaths"), + rs.getInt("seeker_deaths") ); rs.close(); connection.close(); + CACHE.put(uuid, info); return info; } rs.close(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); - } catch (IOException e) { - Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); - e.printStackTrace(); } - return new PlayerInfo(uuid, 0, 0, 0, 0); + return new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); } + @Nullable public List getInfoPage(int page){ - String sql = "SELECT * FROM player_info ORDER BY wins DESC LIMIT 10 OFFSET ?;"; + String sql = "SELECT * FROM hs_data ORDER BY (hider_wins + seeker_wins) DESC LIMIT 10 OFFSET ?;"; try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ statement.setInt(1, (page-1)*10); ResultSet rs = statement.executeQuery(); List infoList = new ArrayList<>(); while(rs.next()){ PlayerInfo info = new PlayerInfo( - Database.convertBinaryStream(new ByteArrayInputStream(rs.getBytes("uuid"))), - rs.getInt("wins"), - rs.getInt("seeker_wins"), + decodeUUID(rs.getBytes("uuid")), rs.getInt("hider_wins"), - rs.getInt("games_played") + rs.getInt("seeker_wins"), + rs.getInt("hider_games"), + rs.getInt("seeker_games"), + rs.getInt("hider_kills"), + rs.getInt("seeker_kills"), + rs.getInt("hider_deaths"), + rs.getInt("seeker_deaths") ); infoList.add(info); } @@ -110,31 +154,31 @@ public class PlayerInfoTable { return null; } - public void addWins(List uuids, List winners, WinType type){ + public void addWins(List uuids, List winners, Map kills, Map deaths, WinType type){ for(UUID uuid : uuids){ - String sql = "INSERT OR REPLACE INTO player_info (uuid, wins, seeker_wins, hider_wins, games_played) VALUES (?,?,?,?,?)"; + String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; PlayerInfo info = getInfo(uuid); try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ - InputStream is = Database.convertUniqueId(uuid); - byte[] bytes = new byte[is.available()]; - if(is.read(bytes) == -1){ - throw new IOException("Failed to read bytes from input stream"); - } - statement.setBytes(1, bytes); - statement.setInt(2, info.wins + (winners.contains(uuid) ? 1 : 0)); + statement.setBytes(1, encodeUUID(uuid)); + statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); - statement.setInt(4, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); - statement.setInt(5, info.games_played + 1); + statement.setInt(4, info.hider_games + (Board.isHider(uuid) ? 1 : 0)); + statement.setInt(5, info.seeker_games + (Board.isSeeker(uuid) ? 1 : 0)); + statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? kills.get(uuid.toString()) : 0)); + statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? kills.get(uuid.toString()) : 0)); + statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? deaths.get(uuid.toString()) : 0)); + statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? deaths.get(uuid.toString()) : 0)); statement.execute(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); return; - } catch (IOException e) { - Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); - e.printStackTrace(); + } finally { + CACHE.remove(uuid); } } } + + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index c08b779..86711ab 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -38,6 +38,8 @@ public class Board { private static final List Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); private static final Map playerList = new HashMap<>(); private static final Map customBoards = new HashMap<>(); + private static final Map kills = new HashMap<>(); + private static final Map deaths = new HashMap<>(); public static boolean isPlayer(Player player) { return playerList.containsKey(player.getUniqueId().toString()); @@ -51,10 +53,18 @@ public class Board { return Hider.contains(player.getUniqueId().toString()); } + public static boolean isHider(UUID uuid){ + return Hider.contains(uuid.toString()); + } + public static boolean isSeeker(Player player) { return Seeker.contains(player.getUniqueId().toString()); } + public static boolean isSeeker(UUID uuid){ + return Seeker.contains(uuid.toString()); + } + public static boolean isSpectator(Player player) { return Spectator.contains(player.getUniqueId().toString()); } @@ -133,6 +143,32 @@ public class Board { Hider.clear(); Seeker.clear(); Spectator.clear(); + kills.clear(); + deaths.clear(); + } + + public static void addKill(UUID uuid){ + if(kills.containsKey(uuid.toString())){ + kills.put(uuid.toString(), kills.get(uuid.toString())+1); + } else { + kills.put(uuid.toString(), 1); + } + } + + public static void addDeath(UUID uuid){ + if(deaths.containsKey(uuid.toString())){ + deaths.put(uuid.toString(), deaths.get(uuid.toString())+1); + } else { + deaths.put(uuid.toString(), 1); + } + } + + public static Map getKills(){ + return new HashMap<>(kills); + } + + public static Map getDeaths(){ + return new HashMap<>(deaths); } public static void createLobbyBoard(Player player) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 35089e4..7d83217 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -32,6 +32,7 @@ import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -148,93 +149,73 @@ public class EventListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { - try { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (!Board.isPlayer(player)) { - if (event instanceof EntityDamageByEntityEvent) { - Entity damager = ((EntityDamageByEntityEvent) event).getDamager(); - if (damager instanceof Player) { - if(Board.isPlayer(damager)){ - event.setCancelled(true); - return; - } - } - } - return; - } - if (Game.status != Status.PLAYING) { - event.setCancelled(true); - return; - } - Player attacker = null; - if (event instanceof EntityDamageByEntityEvent) { - Entity damager = ((EntityDamageByEntityEvent) event).getDamager(); - if (damager instanceof Player) { - attacker = (Player) damager; - if (!Board.isPlayer(attacker)) event.setCancelled(true); - if (Board.onSameTeam(player, attacker)) event.setCancelled(true); - if (Board.isSpectator(player)) event.setCancelled(true); - } else if(damager instanceof Arrow){ - ProjectileSource source = ((Arrow) damager).getShooter(); - if(source instanceof Player){ - attacker = (Player) source; - if (!Board.isPlayer(attacker)) event.setCancelled(true); - if (Board.onSameTeam(player, attacker)) event.setCancelled(true); - if (Board.isSpectator(player)) event.setCancelled(true); - } - } - } - if(event.isCancelled()) return; - if (player.getHealth() - event.getFinalDamage() < 0.5 || !pvpEnabled) { - if (event instanceof EntityDamageByEntityEvent && !pvpEnabled) { - Entity damager = ((EntityDamageByEntityEvent) event).getDamager(); - if (damager instanceof Player) { - Player atacker = (Player) damager; - if(!Board.isSeeker(atacker)){ - event.setCancelled(true); - return; - } - } else { - event.setCancelled(true); - return; - } - } else if(!pvpEnabled) { - event.setCancelled(true); - return; - } - if (spawnPosition == null) return; - event.setCancelled(true); - if(Version.atLeast("1.9")) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute != null) player.setHealth(attribute.getValue()); - } else { - player.setHealth(player.getMaxHealth()); - } - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - if(Version.atLeast("1.9")){ - XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); - } else { - XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); - } - if (Board.isSeeker(player)) { - Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); - } - if (Board.isHider(player)) { - if (attacker == null) { - Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); - } else { - Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); - } - Board.addSeeker(player); - } - Game.resetPlayer(player); - Board.reloadBoardTeams(); - } - } - } catch (Exception e){ - Main.plugin.getLogger().severe("Entity Damage Event Error: " + e.getMessage()); + // If you are not a player, get out of here + if(!(event.getEntity() instanceof Player)) return; + // Define variables + Player player = (Player) event.getEntity(); + Player attacker = null; + // If player pvp is enabled, and player doesn't die, we do not care + if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5){ return; } + // If no spawn position, we won't be able to manage their death :o + if(spawnPosition == null){ return; } + // If there is an attacker, find them + if (event instanceof EntityDamageByEntityEvent) { + if(((EntityDamageByEntityEvent) event).getDamager() instanceof Player) + attacker = (Player) ((EntityDamageByEntityEvent) event).getDamager(); + else if(((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile) + if(((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player) + attacker = (Player) ((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter(); } + // Makes sure that if there was an attacking player, that the event is allowed for the game + if(attacker != null){ + // Cancel if one player is in the game but other isn't + if((Board.isPlayer(player) && !Board.isPlayer(attacker)) || (!Board.isPlayer(player) && Board.isPlayer(attacker))){ + event.setCancelled(true); + return; + // Ignore event if neither player are in the game + } else if(!Board.isPlayer(player) && !Board.isPlayer(attacker)){ + return; + // Ignore event if players are on the same team, or one of them is a spectator + } else if(Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)){ + event.setCancelled(true); + return; + // Ignore the event if pvp is disabled, and a hider is trying to attack a seeker + } else if(!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)){ + event.setCancelled(true); + return; + } + // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. + } else if(!pvpEnabled && !allowNaturalCauses){ + event.setCancelled(true); + return; + } + // Handle death event + event.setCancelled(true); + // Reset health and play death effect + if(Version.atLeast("1.9")) { + AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + if (attribute != null) player.setHealth(attribute.getValue()); + XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); + } else { + player.setHealth(player.getMaxHealth()); + XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); + } + // Teleport player to seeker spawn + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + // Broadcast player death message + if (Board.isSeeker(player)) { + Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); + } else if (Board.isHider(player)) { + if (attacker == null) { + Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); + } else { + Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); + } + Board.addSeeker(player); + } + // Add leaderboard stats + Board.addDeath(player.getUniqueId()); + if(attacker != null){ Board.addKill(attacker.getUniqueId()); } } @EventHandler(priority = EventPriority.HIGHEST) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 16caee4..fb91a2f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -178,11 +178,11 @@ public class Game { List players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); if(type == WinType.HIDER_WIN){ List winners = Board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); - Database.playerInfo.addWins(players, winners, type); + Database.playerInfo.addWins(players, winners, Board.getKills(), Board.getDeaths(), type); } else if(type == WinType.SEEKER_WIN){ List winners = new ArrayList<>(); winners.add(Board.getFirstSeeker().getUniqueId()); - Database.playerInfo.addWins(players, winners, type); + Database.playerInfo.addWins(players, winners, Board.getKills(), Board.getDeaths(), type); } worldBorder.resetWorldborder(getGameWorld()); for(Player player : Board.getPlayers()) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java new file mode 100644 index 0000000..c5d70bc --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -0,0 +1,128 @@ +package net.tylermurphy.hideAndSeek.util; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.database.PlayerInfo; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.UUID; + +public class PAPIExpansion extends PlaceholderExpansion { + + @Override + public @NotNull String getIdentifier() { + return "kenshinshideandseek"; + } + + @Override + public @NotNull String getAuthor() { + return "KenshinEto"; + } + + @Override + public @NotNull String getVersion() { + return "1.4.3"; + } + + @Override + public boolean persist() { + return true; + } + + @Override + public String onRequest(OfflinePlayer player, @NotNull String params) { + switch (params.toLowerCase(Locale.ROOT)) { + case "hs_stats_total-wins": + return hs_stats_total_wins(player.getUniqueId()); + case "hs_stats_hider-wins": + return hs_stats_hider_wins(player.getUniqueId()); + case "hs_stats_seeker-wins": + return hs_stats_seeker_wins(player.getUniqueId()); + case "hs_stats_total-games": + return hs_stats_total_games(player.getUniqueId()); + case "hs_stats_hider-games": + return hs_stats_hider_games(player.getUniqueId()); + case "hs_stats_seeker-games": + return hs_stats_seeker_games(player.getUniqueId()); + case "hs_stats_total-kills": + return hs_stats_total_kills(player.getUniqueId()); + case "hs_stats_hider-kills": + return hs_stats_hider_kills(player.getUniqueId()); + case "hs_stats_seeker-kills": + return hs_stats_seeker_kills(player.getUniqueId()); + case "hs_stats_total-deaths": + return hs_stats_total_deaths(player.getUniqueId()); + case "hs_stats_hider-deaths": + return hs_stats_hider_deaths(player.getUniqueId()); + case "hs_stats_seeker-deaths": + return hs_stats_seeker_deaths(player.getUniqueId()); + default: + return null; + } + } + + private String hs_stats_total_wins(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_wins + info.seeker_wins); + } + + private String hs_stats_hider_wins(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_wins); + } + + private String hs_stats_seeker_wins(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.seeker_wins); + } + + private String hs_stats_total_games(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_games + info.seeker_games); + } + + private String hs_stats_hider_games(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_games); + } + + private String hs_stats_seeker_games(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.seeker_games); + } + + private String hs_stats_total_kills(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_kills + info.seeker_kills); + } + + private String hs_stats_hider_kills(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_kills); + } + + private String hs_stats_seeker_kills(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.seeker_kills); + } + + private String hs_stats_total_deaths(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_deaths + info.seeker_deaths); + } + + private String hs_stats_hider_deaths(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.hider_deaths); + } + + private String hs_stats_seeker_deaths(UUID uuid){ + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return String.valueOf(info.seeker_deaths); + } + +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 88eab62..45261a3 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -46,6 +46,13 @@ minPlayers: 2 # default: true pvp: true +# !! Only effects the game at all if pvp is set to false !! +# By default, If you disable pvp, Hiders and Seekers can no longer take damage from natural causes such as +# falling or projectiles. If you want, you can keep pvp disabled so that Seekers only have to tag Hiders, but +# all players can still take fall damage or any other damage that's not from another player. +# deafult: false +allowNaturalCauses: false + # Players that join the server will automatically be placed into the lobby. # default: false autoJoin: false From 61a0080b5ebbbcefd8fa65abd5f472f891dced80 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 7 May 2022 23:56:04 -0400 Subject: [PATCH 22/68] add softdepend to plugin.yml --- src/main/resources/plugin.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index afe2ed2..93fec0d 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -5,6 +5,7 @@ author: KenshinEto load: STARTUP api-version: 1.13 depend: [ProtocolLib] +softdepend: [PlaceholderAPI] commands: hideandseek: description: Hide and Seek command From 5da8c8ea0aecb72bc88e9e05700f20f7d5837a1b Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 7 May 2022 23:59:08 -0400 Subject: [PATCH 23/68] fix Top.java --- src/main/java/net/tylermurphy/hideAndSeek/command/Top.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 760bb2c..51e3574 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -50,6 +50,10 @@ public class Top implements ICommand { ChatColor.WHITE, ChatColor.BOLD, ChatColor.GRAY, page, ChatColor.WHITE)); List infos = Database.playerInfo.getInfoPage(page); int i = 1 + (page-1)*10; + if(infos == null){ + sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); + return; + } for(PlayerInfo info : infos){ String name = Main.plugin.getServer().getOfflinePlayer(info.uuid).getName(); ChatColor color; @@ -60,7 +64,7 @@ public class Top implements ICommand { default: color = ChatColor.WHITE; break; } message.append(String.format("%s%s. %s%s %s%s\n", - color, i, ChatColor.RED, info.wins, ChatColor.WHITE, name)); + color, i, ChatColor.RED, info.seeker_wins+info.hider_wins, ChatColor.WHITE, name)); i++; } sender.sendMessage(message.toString()); From 5086fb4a007925e4edc236d80211f4a0288dfa82 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Mon, 9 May 2022 16:19:24 -0400 Subject: [PATCH 24/68] refactor placeholders --- .../hideAndSeek/configuration/Config.java | 6 +- .../hideAndSeek/database/PlayerInfoTable.java | 42 ++++- .../hideAndSeek/util/PAPIExpansion.java | 174 +++++++++--------- .../hideAndSeek/util/UUIDFetcher.java | 16 +- src/main/resources/config.yml | 6 + 5 files changed, 150 insertions(+), 94 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index f94ba0b..4a2ae3a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -53,7 +53,9 @@ public class Config { exitWorld, lobbyWorld, locale, - leaveServer; + leaveServer, + placeholderError, + placeholderNoData; public static Vector spawnPosition, @@ -258,6 +260,8 @@ public class Config { locale = config.getString("locale", "local"); blockedCommands = config.getStringList("blockedCommands"); leaveOnEnd = config.getBoolean("leaveOnEnd"); + placeholderError = config.getString("placeholder.incorrect"); + placeholderNoData = config.getString("placeholder.noData"); try { countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay")); } catch (IllegalArgumentException e){ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 06c036d..6948134 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -44,11 +44,11 @@ public class PlayerInfoTable { + " uuid BINARY(16) PRIMARY KEY,\n" + " hider_wins int NOT NULL,\n" + " seeker_wins int NOT NULL,\n" - + " hider_games int NOT NULL\n" - + " seeker_games int NOT NULL\n" - + " hider_kills int NOT NULL\n" - + " seeker_kills int NOT NULL\n" - + " hider_deaths int NOT NULL\n" + + " hider_games int NOT NULL,\n" + + " seeker_games int NOT NULL,\n" + + " hider_kills int NOT NULL,\n" + + " seeker_kills int NOT NULL,\n" + + " hider_deaths int NOT NULL,\n" + " seeker_deaths int NOT NULL\n" + ");"; @@ -123,6 +123,38 @@ public class PlayerInfoTable { return new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); } + @Nullable + public PlayerInfo getInfoRanking(String order, int place){ + String sql = "SELECT * FROM hs_data ORDER BY "+order+" DESC LIMIT 1 OFFSET ?;"; + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + statement.setInt(1, place-1); + ResultSet rs = statement.executeQuery(); + if(rs.next()){ + UUID uuid = decodeUUID(rs.getBytes("uuid")); + PlayerInfo info = new PlayerInfo( + uuid, + rs.getInt("hider_wins"), + rs.getInt("seeker_wins"), + rs.getInt("hider_games"), + rs.getInt("seeker_games"), + rs.getInt("hider_kills"), + rs.getInt("seeker_kills"), + rs.getInt("hider_deaths"), + rs.getInt("seeker_deaths") + ); + rs.close(); + connection.close(); + CACHE.put(uuid, info); + return info; + } + rs.close(); + } catch (SQLException e){ + Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + } + return null; + } + @Nullable public List getInfoPage(int page){ String sql = "SELECT * FROM hs_data ORDER BY (hider_wins + seeker_wins) DESC LIMIT 10 OFFSET ?;"; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index c5d70bc..90f6432 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -1,21 +1,20 @@ package net.tylermurphy.hideAndSeek.util; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.PlayerInfo; import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.lang.reflect.Method; -import java.util.Locale; import java.util.UUID; public class PAPIExpansion extends PlaceholderExpansion { @Override public @NotNull String getIdentifier() { - return "kenshinshideandseek"; + return "hs"; } @Override @@ -35,94 +34,95 @@ public class PAPIExpansion extends PlaceholderExpansion { @Override public String onRequest(OfflinePlayer player, @NotNull String params) { - switch (params.toLowerCase(Locale.ROOT)) { - case "hs_stats_total-wins": - return hs_stats_total_wins(player.getUniqueId()); - case "hs_stats_hider-wins": - return hs_stats_hider_wins(player.getUniqueId()); - case "hs_stats_seeker-wins": - return hs_stats_seeker_wins(player.getUniqueId()); - case "hs_stats_total-games": - return hs_stats_total_games(player.getUniqueId()); - case "hs_stats_hider-games": - return hs_stats_hider_games(player.getUniqueId()); - case "hs_stats_seeker-games": - return hs_stats_seeker_games(player.getUniqueId()); - case "hs_stats_total-kills": - return hs_stats_total_kills(player.getUniqueId()); - case "hs_stats_hider-kills": - return hs_stats_hider_kills(player.getUniqueId()); - case "hs_stats_seeker-kills": - return hs_stats_seeker_kills(player.getUniqueId()); - case "hs_stats_total-deaths": - return hs_stats_total_deaths(player.getUniqueId()); - case "hs_stats_hider-deaths": - return hs_stats_hider_deaths(player.getUniqueId()); - case "hs_stats_seeker-deaths": - return hs_stats_seeker_deaths(player.getUniqueId()); + String[] args = params.split("_"); + System.out.println(); + if(args.length < 1) return null; + if(args[0].equals("stats") && args.length == 2){ + PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + return getValue(info, args[1]); + } else if(args[0].equals("stats") && args.length == 3){ + UUID uuid; + try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } + PlayerInfo info = Database.playerInfo.getInfo(uuid); + return getValue(info, args[1]); + } else if(args[0].equals("rank") && args.length == 3){ + int place; + try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } + if(place < 1) { return placeholderError; } + if(getRanking(args[1]) == null) { return placeholderError; } + PlayerInfo info = Database.playerInfo.getInfoRanking(getRanking(args[1]), place); + if(info == null) return placeholderNoData; + if(args[0].equals("rankStat")){ + return getValue(info, args[1]); + } else { + return UUIDFetcher.getPlayer(info.uuid).getName(); + } + } + return null; + } + + private String getValue(PlayerInfo info, String query){ + if(query == null) return null; + switch (query) { + case "total-wins": + return String.valueOf(info.hider_wins + info.seeker_wins); + case "hider-wins": + return String.valueOf(info.hider_wins); + case "seeker-wins": + return String.valueOf(info.seeker_wins); + case "total-games": + return String.valueOf(info.hider_games + info.seeker_games); + case "hider-games": + return String.valueOf(info.hider_games); + case "seeker-games": + return String.valueOf(info.seeker_games); + case "total-kills": + return String.valueOf(info.hider_kills + info.seeker_kills); + case "hider-kills": + return String.valueOf(info.hider_kills); + case "seeker-kills": + return String.valueOf(info.seeker_kills); + case "total-deaths": + return String.valueOf(info.hider_deaths + info.seeker_deaths); + case "hider-deaths": + return String.valueOf(info.hider_deaths); + case "seeker-deaths": + return String.valueOf(info.seeker_deaths); default: return null; } } - private String hs_stats_total_wins(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_wins + info.seeker_wins); - } - - private String hs_stats_hider_wins(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_wins); - } - - private String hs_stats_seeker_wins(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.seeker_wins); - } - - private String hs_stats_total_games(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_games + info.seeker_games); - } - - private String hs_stats_hider_games(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_games); - } - - private String hs_stats_seeker_games(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.seeker_games); - } - - private String hs_stats_total_kills(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_kills + info.seeker_kills); - } - - private String hs_stats_hider_kills(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_kills); - } - - private String hs_stats_seeker_kills(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.seeker_kills); - } - - private String hs_stats_total_deaths(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_deaths + info.seeker_deaths); - } - - private String hs_stats_hider_deaths(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.hider_deaths); - } - - private String hs_stats_seeker_deaths(UUID uuid){ - PlayerInfo info = Database.playerInfo.getInfo(uuid); - return String.valueOf(info.seeker_deaths); + private String getRanking(String query){ + if(query == null) return null; + switch (query) { + case "total-wins": + return "(hider_wins + seeker_wins)"; + case "hider-wins": + return "hider_wins"; + case "seeker-wins": + return "seeker_wins"; + case "total-games": + return "(hider_games + seeker_games)"; + case "hider-games": + return "hider_games"; + case "seeker-games": + return "seeker_games"; + case "total-kills": + return "(hider_kills + seeker_kills)"; + case "hider-kills": + return "hider_kills"; + case "seeker-kills": + return "seeker_kills"; + case "total-deaths": + return "(hider_deaths + seeker_deaths)"; + case "hider-deaths": + return "hider_deaths"; + case "seeker-deaths": + return "seeker_deaths"; + default: + return null; + } } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java index ef65af3..4ab883d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java @@ -20,6 +20,9 @@ package net.tylermurphy.hideAndSeek.util; import net.tylermurphy.hideAndSeek.Main; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -33,12 +36,16 @@ import java.util.UUID; public final class UUIDFetcher { private static final Map CACHE = new HashMap<>(); + private static final Map PLAYER_CACHE = new HashMap<>(); private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static int cacheTask; public static void init(){ - cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, CACHE::clear,600*20, 600*20); + cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, () -> { + CACHE.clear(); + PLAYER_CACHE.clear(); + }, 600 * 20, 600 * 20); } public static void cleanup(){ @@ -66,6 +73,13 @@ public final class UUIDFetcher { return UUID.fromString(uuid.toString()); } + public static OfflinePlayer getPlayer(UUID uuid){ + if(PLAYER_CACHE.containsKey(uuid)) return PLAYER_CACHE.get(uuid); + OfflinePlayer temp = Bukkit.getOfflinePlayer(uuid); + PLAYER_CACHE.put(uuid, temp); + return temp; + } + private static void readData(String toRead, StringBuilder result) { for (int i = toRead.length() - 3; i >= 0; i--) { if (toRead.charAt(i) != '"') { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 45261a3..75658b6 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -142,6 +142,12 @@ prefix: gameover: '&aGame Over > &f' warning: '&cWarning > &f' +# This plugin has support for custom placeholders with PlaceholderAPI. If you make a mistake when creating a placeholder, +# the plugin may tell you an error. Below you can change what could appear as an error message. +placeholder: + incorrect: "{Error}" + noData: "{No Data}" + # This is the section if you want a standard "waiting for players" lobby. You can specify # the standard countdown length under [countdown] (min 10 seconds). Then once the lobby gets to a size specified # by [changeCountdown], the timer will automatically go to 10 seconds. [min] is the minimum players From 1d85e995344e25516e1fbe2e42f0db4a8c80d64d Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Mon, 9 May 2022 22:21:53 -0400 Subject: [PATCH 25/68] update placeholders --- .../java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 90f6432..311fcee 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -45,14 +45,14 @@ public class PAPIExpansion extends PlaceholderExpansion { try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfo(uuid); return getValue(info, args[1]); - } else if(args[0].equals("rank") && args.length == 3){ + } else if((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3){ int place; try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } if(place < 1) { return placeholderError; } if(getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfoRanking(getRanking(args[1]), place); if(info == null) return placeholderNoData; - if(args[0].equals("rankStat")){ + if(args[0].equals("rank-score")){ return getValue(info, args[1]); } else { return UUIDFetcher.getPlayer(info.uuid).getName(); From 0fdc77157f52c4f6b4839352f4f1ae94cb79a7dc Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 10 May 2022 10:01:48 -0400 Subject: [PATCH 26/68] rank-place placeholder, fix null pointer in sql --- .../hideAndSeek/database/PlayerInfoTable.java | 27 ++++++++++++++----- .../hideAndSeek/util/PAPIExpansion.java | 12 +++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 6948134..b4f1602 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -186,6 +186,23 @@ public class PlayerInfoTable { return null; } + @Nullable + public Integer getRanking(String order, UUID uuid){ + String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" < (SELECT "+order+" FROM hs_data WHERE uuid = ?);"; + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + statement.setBytes(1, encodeUUID(uuid)); + ResultSet rs = statement.executeQuery(); + if(rs.next()){ + return rs.getInt("total")+1; + } + rs.close(); + } catch (SQLException e){ + Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + } + return null; + } + public void addWins(List uuids, List winners, Map kills, Map deaths, WinType type){ for(UUID uuid : uuids){ String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; @@ -196,10 +213,10 @@ public class PlayerInfoTable { statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); statement.setInt(4, info.hider_games + (Board.isHider(uuid) ? 1 : 0)); statement.setInt(5, info.seeker_games + (Board.isSeeker(uuid) ? 1 : 0)); - statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? kills.get(uuid.toString()) : 0)); - statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? kills.get(uuid.toString()) : 0)); - statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? deaths.get(uuid.toString()) : 0)); - statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? deaths.get(uuid.toString()) : 0)); + statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? kills.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? kills.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? deaths.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? deaths.getOrDefault(uuid.toString(), 0) : 0)); statement.execute(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); @@ -211,6 +228,4 @@ public class PlayerInfoTable { } } - - } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 311fcee..d467b62 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -57,6 +57,18 @@ public class PAPIExpansion extends PlaceholderExpansion { } else { return UUIDFetcher.getPlayer(info.uuid).getName(); } + } else if(args[0].equals("rank-place") && args.length == 2){ + if(getRanking(args[1]) == null) { return placeholderError; } + Integer count = Database.playerInfo.getRanking(getRanking(args[1]), player.getUniqueId()); + if(count == null) { return placeholderNoData; } + return count.toString(); + } else if(args[0].equals("rank-place") && args.length == 3){ + UUID uuid; + try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } + if(getRanking(args[1]) == null) { return placeholderError; } + Integer count = Database.playerInfo.getRanking(getRanking(args[1]), uuid); + if(count == null) { return placeholderNoData; } + return count.toString(); } return null; } From 487ce5e3f56c5bff5d0538e4cd8d23ddfb73cc02 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 10 May 2022 13:24:19 -0400 Subject: [PATCH 27/68] fix seeker death and other things --- .../hideAndSeek/game/EventListener.java | 13 +++++++++++++ .../net/tylermurphy/hideAndSeek/game/Game.java | 18 +++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 7d83217..f8f754f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -116,6 +116,7 @@ public class EventListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onMove(PlayerMoveEvent event){ + if(!Board.isPlayer(event.getPlayer())) return; if(!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; if(event.getPlayer().hasPermission("hideandseek.leavebounds")) return; if(event.getTo() == null || event.getTo().getWorld() == null) return; @@ -188,6 +189,15 @@ public class EventListener implements Listener { } else if(!pvpEnabled && !allowNaturalCauses){ event.setCancelled(true); return; + // Spectators cannot take damage + } else if(Board.isSpectator(player)){ + event.setCancelled(true); + if(Version.atLeast("1.18") && player.getLocation().getY() < -64){ + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + } else if(player.getLocation().getY() < 0){ + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + } + return; } // Handle death event event.setCancelled(true); @@ -216,6 +226,9 @@ public class EventListener implements Listener { // Add leaderboard stats Board.addDeath(player.getUniqueId()); if(attacker != null){ Board.addKill(attacker.getUniqueId()); } + Game.resetPlayer(player); + Board.reloadBoardTeams(); + } @EventHandler(priority = EventPriority.HIGHEST) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index fb91a2f..76ad068 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -186,6 +186,11 @@ public class Game { } worldBorder.resetWorldborder(getGameWorld()); for(Player player : Board.getPlayers()) { + for(Player player2 : Board.getPlayers()){ + player.showPlayer(player2); + } + player.setFlying(false); + player.setAllowFlight(false); if(Version.atLeast("1.9")){ for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); @@ -299,7 +304,12 @@ public class Game { } else { Board.addSpectator(player); player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); - player.setGameMode(GameMode.SPECTATOR); + player.setGameMode(GameMode.ADVENTURE); + for(Player player2 : Board.getPlayers()){ + player2.hidePlayer(player); + } + player.setFlying(true); + player.setAllowFlight(true); Board.createGameBoard(player); player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); @@ -315,6 +325,12 @@ public class Game { } public static void leave(Player player){ + player.setFlying(false); + player.setAllowFlight(false); + for(Player player2 : Board.getPlayers()){ + player2.showPlayer(player); + player.showPlayer(player2); + } if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); Board.removeBoard(player); From 8480324ab7b2bb11704b2ba08d0c4e452caf52d2 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 10 May 2022 16:54:24 -0400 Subject: [PATCH 28/68] rank-place palceholder change --- .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 2 +- .../java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index b4f1602..35912fe 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -188,7 +188,7 @@ public class PlayerInfoTable { @Nullable public Integer getRanking(String order, UUID uuid){ - String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" < (SELECT "+order+" FROM hs_data WHERE uuid = ?);"; + String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND hider_wins > 0;"; try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index d467b62..e7bca4a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -59,6 +59,8 @@ public class PAPIExpansion extends PlaceholderExpansion { } } else if(args[0].equals("rank-place") && args.length == 2){ if(getRanking(args[1]) == null) { return placeholderError; } + PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + if(getValue(info, args[1]).equals("0")) { return "-"; } Integer count = Database.playerInfo.getRanking(getRanking(args[1]), player.getUniqueId()); if(count == null) { return placeholderNoData; } return count.toString(); @@ -66,6 +68,8 @@ public class PAPIExpansion extends PlaceholderExpansion { UUID uuid; try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } if(getRanking(args[1]) == null) { return placeholderError; } + PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + if(getValue(info, args[1]).equals("0")) { return "-"; } Integer count = Database.playerInfo.getRanking(getRanking(args[1]), uuid); if(count == null) { return placeholderNoData; } return count.toString(); From d4f22de7b05dc0170fac130a13ca5b7ad6683bfb Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 09:49:36 -0400 Subject: [PATCH 29/68] bug fixes + spectator flight + no false scoreboards values --- .../tylermurphy/hideAndSeek/command/Stop.java | 2 +- .../hideAndSeek/database/PlayerInfoTable.java | 10 ++-- .../tylermurphy/hideAndSeek/game/Board.java | 56 +++++++++++++------ .../hideAndSeek/game/EventListener.java | 11 ++-- .../tylermurphy/hideAndSeek/game/Game.java | 36 +++++++----- .../hideAndSeek/util/PAPIExpansion.java | 1 - 6 files changed, 73 insertions(+), 43 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index 0b53ed6..f87457f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -38,7 +38,7 @@ public class Stop implements ICommand { } if(Game.status == Status.STARTING || Game.status == Status.PLAYING) { Game.broadcastMessage(abortPrefix + message("STOP")); - Game.stop(WinType.NONE); + Game.stop(); } else { sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS")); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 35912fe..aab42b8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -203,7 +203,7 @@ public class PlayerInfoTable { return null; } - public void addWins(List uuids, List winners, Map kills, Map deaths, WinType type){ + public void addWins(List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type){ for(UUID uuid : uuids){ String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; PlayerInfo info = getInfo(uuid); @@ -213,10 +213,10 @@ public class PlayerInfoTable { statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); statement.setInt(4, info.hider_games + (Board.isHider(uuid) ? 1 : 0)); statement.setInt(5, info.seeker_games + (Board.isSeeker(uuid) ? 1 : 0)); - statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? kills.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? kills.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? deaths.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? deaths.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? hider_kills.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? seeker_kills.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? hider_deaths.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? seeker_deaths.getOrDefault(uuid.toString(), 0) : 0)); statement.execute(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 86711ab..61e77e7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -38,8 +38,7 @@ public class Board { private static final List Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); private static final Map playerList = new HashMap<>(); private static final Map customBoards = new HashMap<>(); - private static final Map kills = new HashMap<>(); - private static final Map deaths = new HashMap<>(); + private static final Map hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>(); public static boolean isPlayer(Player player) { return playerList.containsKey(player.getUniqueId().toString()); @@ -143,32 +142,55 @@ public class Board { Hider.clear(); Seeker.clear(); Spectator.clear(); - kills.clear(); - deaths.clear(); + hider_kills.clear(); + seeker_kills.clear(); + hider_deaths.clear(); + seeker_deaths.clear(); } public static void addKill(UUID uuid){ - if(kills.containsKey(uuid.toString())){ - kills.put(uuid.toString(), kills.get(uuid.toString())+1); - } else { - kills.put(uuid.toString(), 1); + if(Hider.contains(uuid.toString())){ + if(hider_kills.containsKey(uuid.toString())){ + hider_kills.put(uuid.toString(), hider_kills.get(uuid.toString())+1); + } else { + hider_kills.put(uuid.toString(), 1); + } + } else if(getFirstSeeker().getUniqueId().equals(uuid)){ + if(seeker_kills.containsKey(uuid.toString())){ + seeker_kills.put(uuid.toString(), seeker_kills.get(uuid.toString())+1); + } else { + seeker_kills.put(uuid.toString(), 1); + } } } public static void addDeath(UUID uuid){ - if(deaths.containsKey(uuid.toString())){ - deaths.put(uuid.toString(), deaths.get(uuid.toString())+1); - } else { - deaths.put(uuid.toString(), 1); + if(Hider.contains(uuid.toString())){ + if(hider_deaths.containsKey(uuid.toString())){ + hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1); + } else { + hider_deaths.put(uuid.toString(), 1); + } + } else if(getFirstSeeker().getUniqueId().equals(uuid)){ + if(seeker_deaths.containsKey(uuid.toString())){ + seeker_deaths.put(uuid.toString(), seeker_deaths.get(uuid.toString())+1); + } else { + seeker_deaths.put(uuid.toString(), 1); + } } } - public static Map getKills(){ - return new HashMap<>(kills); + public static Map getHiderKills(){ + return new HashMap<>(hider_kills); } - - public static Map getDeaths(){ - return new HashMap<>(deaths); + public static Map getSeekerKills(){ + return new HashMap<>(seeker_kills); + } + public static Map getHiderDeaths(){ + return new HashMap<>(hider_deaths); + } + public static Map getSeekerDeaths(){ + return new HashMap<>(seeker_deaths); } public static void createLobbyBoard(Player player) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index f8f754f..1c02685 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -215,20 +215,23 @@ public class EventListener implements Listener { // Broadcast player death message if (Board.isSeeker(player)) { Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); + if(Board.getFirstSeeker().getName().equals(player.getName())){ + Board.addDeath(player.getUniqueId()); + } } else if (Board.isHider(player)) { if (attacker == null) { Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); } else { Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); } + Board.addDeath(player.getUniqueId()); Board.addSeeker(player); } - // Add leaderboard stats - Board.addDeath(player.getUniqueId()); - if(attacker != null){ Board.addKill(attacker.getUniqueId()); } + // Add leaderboard kills if attacker + if(attacker != null && ( Board.isHider(player) || Board.getFirstSeeker().getName().equals(player.getName()) ) ) + Board.addKill(attacker.getUniqueId()); Game.resetPlayer(player); Board.reloadBoardTeams(); - } @EventHandler(priority = EventPriority.HIGHEST) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 76ad068..69153f2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -155,35 +155,35 @@ public class Game { status = Status.ENDING; for(Player player : Board.getPlayers()) { player.getInventory().clear(); - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); for(PotionEffect effect : player.getActivePotionEffects()){ player.removePotionEffect(effect.getType()); } + player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); if(Version.atLeast("1.9")){ for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); } } } - Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, () -> stop(type), 5*20); + List players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); + if(type == WinType.HIDER_WIN){ + List winners = Board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); + Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); + } else if(type == WinType.SEEKER_WIN){ + List winners = new ArrayList<>(); + winners.add(Board.getFirstSeeker().getUniqueId()); + Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); + } + Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::stop, 5*20); } - public static void stop(WinType type){ + public static void stop(){ if(status == Status.STANDBY) return; tick = 0; countdownTime = -1; status = Status.STANDBY; gameId++; timeLeft = 0; - List players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); - if(type == WinType.HIDER_WIN){ - List winners = Board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); - Database.playerInfo.addWins(players, winners, Board.getKills(), Board.getDeaths(), type); - } else if(type == WinType.SEEKER_WIN){ - List winners = new ArrayList<>(); - winners.add(Board.getFirstSeeker().getUniqueId()); - Database.playerInfo.addWins(players, winners, Board.getKills(), Board.getDeaths(), type); - } worldBorder.resetWorldborder(getGameWorld()); for(Player player : Board.getPlayers()) { for(Player player2 : Board.getPlayers()){ @@ -196,6 +196,10 @@ public class Game { Packet.setGlow(player, temp, false); } } + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } + player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); if(leaveOnEnd){ Board.removeBoard(player); Board.remove(player); @@ -288,7 +292,7 @@ public class Game { } public static void join(Player player){ - if(Game.status == Status.STANDBY) { + if(Game.status == Status.STANDBY || Game.status == Status.ENDING) { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); player.getInventory().clear(); if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) @@ -308,10 +312,11 @@ public class Game { for(Player player2 : Board.getPlayers()){ player2.hidePlayer(player); } - player.setFlying(true); - player.setAllowFlight(true); Board.createGameBoard(player); player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + player.setFlying(true); + player.setAllowFlight(true); + player.setFallDistance(0.0F); Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); } @@ -327,6 +332,7 @@ public class Game { public static void leave(Player player){ player.setFlying(false); player.setAllowFlight(false); + player.setFallDistance(0.0F); for(Player player2 : Board.getPlayers()){ player2.showPlayer(player); player.showPlayer(player2); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index e7bca4a..d1ce898 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -35,7 +35,6 @@ public class PAPIExpansion extends PlaceholderExpansion { @Override public String onRequest(OfflinePlayer player, @NotNull String params) { String[] args = params.split("_"); - System.out.println(); if(args.length < 1) return null; if(args[0].equals("stats") && args.length == 2){ PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); From 1b0f18cdf9fa467d68b0349986573dbcb58048c5 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 09:57:32 -0400 Subject: [PATCH 30/68] fix placeholder ranking --- .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index aab42b8..37f11fd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -188,7 +188,7 @@ public class PlayerInfoTable { @Nullable public Integer getRanking(String order, UUID uuid){ - String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND hider_wins > 0;"; + String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND "+order+" > 0;"; try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); From 469c7ee98a6fdca6d30ebe1aad219cd15cd16530 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 10:15:02 -0400 Subject: [PATCH 31/68] dont add extra place --- .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 37f11fd..2bf5ed5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -193,7 +193,7 @@ public class PlayerInfoTable { statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); if(rs.next()){ - return rs.getInt("total")+1; + return rs.getInt("total"); } rs.close(); } catch (SQLException e){ From 77675c7ece35eccd7a97c5e374d3a4ebaa8e8984 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 10:26:54 -0400 Subject: [PATCH 32/68] more big fixes --- .../net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 4 ++-- .../java/net/tylermurphy/hideAndSeek/game/EventListener.java | 2 +- src/main/java/net/tylermurphy/hideAndSeek/game/Game.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 2bf5ed5..bcd5516 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -211,8 +211,8 @@ public class PlayerInfoTable { statement.setBytes(1, encodeUUID(uuid)); statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); - statement.setInt(4, info.hider_games + (Board.isHider(uuid) ? 1 : 0)); - statement.setInt(5, info.seeker_games + (Board.isSeeker(uuid) ? 1 : 0)); + statement.setInt(4, info.hider_games + (Board.isHider(uuid) || (Board.isSeeker(uuid) && !Board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); + statement.setInt(5, info.seeker_games + (Board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? hider_kills.getOrDefault(uuid.toString(), 0) : 0)); statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? seeker_kills.getOrDefault(uuid.toString(), 0) : 0)); statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? hider_deaths.getOrDefault(uuid.toString(), 0) : 0)); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 1c02685..17bd65a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -228,7 +228,7 @@ public class EventListener implements Listener { Board.addSeeker(player); } // Add leaderboard kills if attacker - if(attacker != null && ( Board.isHider(player) || Board.getFirstSeeker().getName().equals(player.getName()) ) ) + if(attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) Board.addKill(attacker.getUniqueId()); Game.resetPlayer(player); Board.reloadBoardTeams(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 69153f2..f30f4d1 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -189,8 +189,8 @@ public class Game { for(Player player2 : Board.getPlayers()){ player.showPlayer(player2); } - player.setFlying(false); player.setAllowFlight(false); + player.setFlying(false); if(Version.atLeast("1.9")){ for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); @@ -314,8 +314,8 @@ public class Game { } Board.createGameBoard(player); player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); - player.setFlying(true); player.setAllowFlight(true); + player.setFlying(true); player.setFallDistance(0.0F); Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); } From 068e1f406abc1063080f8fdff94f03d2ade8238f Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 11:31:43 -0400 Subject: [PATCH 33/68] dont load mapsave if its disabled, fixed seeker join effects --- .../net/tylermurphy/hideAndSeek/configuration/Config.java | 2 +- .../net/tylermurphy/hideAndSeek/game/EventListener.java | 4 ++-- src/main/java/net/tylermurphy/hideAndSeek/game/Game.java | 8 +++++++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 4a2ae3a..22f4480 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -247,7 +247,7 @@ public class Config { Optional heartbeatOptional = XSound.matchXSound(config.getString("seekerPing.sounds.heartbeatNoise")); heartbeatSound = heartbeatOptional.orElse(XSound.BLOCK_NOTE_BLOCK_BASEDRUM); Optional ringingOptional = XSound.matchXSound(config.getString("seekerPing.sounds.ringingNoise")); - ringingSound = heartbeatOptional.orElse(XSound.BLOCK_NOTE_BLOCK_PLING); + ringingSound = ringingOptional.orElse(XSound.BLOCK_NOTE_BLOCK_PLING); //Other nametagsVisible = config.getBoolean("nametagsVisible"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 17bd65a..f2ed00c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -67,8 +67,8 @@ public class EventListener implements Listener { event.getPlayer().setGameMode(GameMode.ADVENTURE); } } else { - if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { - if(Game.status != Status.STANDBY){ + if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { + if(Game.status != Status.STANDBY && Game.status != Status.ENDING){ Game.join(event.getPlayer()); } else { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index f30f4d1..55e78b5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -91,7 +91,7 @@ public class Game { if(status == Status.STARTING || status == Status.PLAYING) return; if(mapSaveEnabled && worldLoader.getWorld() != null) { worldLoader.rollback(); - } else { + } else if(mapSaveEnabled) { worldLoader.loadMap(); } Board.reload(); @@ -302,6 +302,9 @@ public class Game { Board.addHider(player); if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } player.setGameMode(GameMode.ADVENTURE); Board.createLobbyBoard(player); Board.reloadLobbyBoards(); @@ -348,6 +351,9 @@ public class Game { Board.reloadGameBoards(); Board.reloadBoardTeams(); } + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } if(bungeeLeave) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); From 7eb687a26c56e2441d9c2463d6a6b0b86aabb9f9 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 22:17:36 -0400 Subject: [PATCH 34/68] remove unneeded checks when adding kills/deaths to database --- .../tylermurphy/hideAndSeek/database/PlayerInfoTable.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index bcd5516..99ac614 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -213,10 +213,10 @@ public class PlayerInfoTable { statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); statement.setInt(4, info.hider_games + (Board.isHider(uuid) || (Board.isSeeker(uuid) && !Board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); statement.setInt(5, info.seeker_games + (Board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); - statement.setInt(6, info.hider_kills + (Board.isHider(uuid) ? hider_kills.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(7, info.seeker_kills + (Board.isSeeker(uuid) ? seeker_kills.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(8, info.hider_deaths + (Board.isHider(uuid) ? hider_deaths.getOrDefault(uuid.toString(), 0) : 0)); - statement.setInt(9, info.seeker_deaths + (Board.isSeeker(uuid) ? seeker_deaths.getOrDefault(uuid.toString(), 0) : 0)); + statement.setInt(6, info.hider_kills + hider_kills.getOrDefault(uuid.toString(), 0)); + statement.setInt(7, info.seeker_kills + seeker_kills.getOrDefault(uuid.toString(), 0)); + statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0)); + statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0)); statement.execute(); } catch (SQLException e){ Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); From 7979185753a5f85f08dde7c5bb5c895233547a8e Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 11 May 2022 22:27:50 -0400 Subject: [PATCH 35/68] make sure hider leaving doesnt create win condition --- .../tylermurphy/hideAndSeek/game/Game.java | 21 +++++++++++++------ .../resources/lang/localization_de-DE.yml | 1 + .../resources/lang/localization_en-US.yml | 1 + 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 55e78b5..9ebb471 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -342,6 +342,9 @@ public class Game { } if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); + if(Board.isHider(player) && status != Status.ENDING && status != Status.STANDBY){ + checkWinConditions(true); + } Board.removeBoard(player); Board.remove(player); player.getInventory().clear(); @@ -394,7 +397,7 @@ public class Game { } private static void whileStarting(){ - checkWinConditions(); + checkWinConditions(false); } private static void whilePlaying() { @@ -436,14 +439,20 @@ public class Game { if(tauntEnabled) taunt.update(); if (glowEnabled) glow.update(); } - checkWinConditions(); + checkWinConditions(false); } - private static void checkWinConditions(){ + private static void checkWinConditions(boolean hiderLeave){ if(Board.sizeHider() < 1) { - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); - else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); - end(WinType.SEEKER_WIN); + if(hiderLeave){ + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); + else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); + end(WinType.NONE); + } else { + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); + else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); + end(WinType.SEEKER_WIN); + } } else if(Board.sizeSeeker() < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index 5fd80d6..fec12ba 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -15,6 +15,7 @@ Localization: GAME_PLAYER_FOUND_BY: "&e{PLAYER}&f wurde von &c{PLAYER}&f gefunden und ist nun ein Seeker." GAME_GAMEOVER_HIDERS_FOUND: "Alle Hider wurden gefunden." GAME_GAMEOVER_SEEKERS_QUIT: "All Seeker haben das Spiel verlassen." + GAME_GAMEOVER_HIDERS_QUIT: "All Hider haben das Spiel verlassen." GAME_GAMEOVER_TIME: "Seekers haben keine Spielzeit mehr. Die Hiders haben gewonnen!" GAME_SETUP: "Spiel wurde noch nicht eingerichtet. Führe &c/hs setup&f aus, um die Einrichtungsschritte zu sehen." GAME_INGAME: "Du bist bereits in der Lobby oder im Spiel." diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index b047bdb..1115fc4 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -15,6 +15,7 @@ Localization: GAME_PLAYER_FOUND_BY: "&e{PLAYER}&f was found by &c{PLAYER}&f and became a seeker." GAME_GAMEOVER_HIDERS_FOUND: "All hiders have been found." GAME_GAMEOVER_SEEKERS_QUIT: "All seekers have quit." + GAME_GAMEOVER_HIDERS_QUIT: "All hiders have quit." GAME_GAMEOVER_TIME: "Seekers ran out of time. Hiders win!" GAME_SETUP: "Game is not setup. Run /hs setup to see what you need to do." GAME_INGAME: "You are already in the lobby/game." From 853ca07431a06f0231fe93a9f70d2b430f1a0dee Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 12 May 2022 08:10:43 -0400 Subject: [PATCH 36/68] temp fly debug tool, game abandon bug fix --- .../tylermurphy/hideAndSeek/game/EventListener.java | 8 ++++++++ .../java/net/tylermurphy/hideAndSeek/game/Game.java | 11 +++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index f2ed00c..c80a51f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -108,6 +108,14 @@ public class EventListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onChat(AsyncPlayerChatEvent event){ + if(event.getMessage().equals("fly")){ + event.getPlayer().setAllowFlight(true); + event.getPlayer().setFlying(true); + } + if(event.getMessage().equals("no fly")){ + event.getPlayer().setAllowFlight(false); + event.getPlayer().setFlying(false); + } if(Board.isSeeker(event.getPlayer())){ event.setCancelled(true); Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 9ebb471..1e02e0f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -63,6 +63,8 @@ public class Game { public static int timeLeft = 0; public static Status status = Status.STANDBY; + private static boolean hiderLeave = false; + static { worldLoader = new WorldLoader(spawnWorld); } @@ -343,7 +345,7 @@ public class Game { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); if(Board.isHider(player) && status != Status.ENDING && status != Status.STANDBY){ - checkWinConditions(true); + hiderLeave = true; } Board.removeBoard(player); Board.remove(player); @@ -397,7 +399,7 @@ public class Game { } private static void whileStarting(){ - checkWinConditions(false); + checkWinConditions(); } private static void whilePlaying() { @@ -439,10 +441,10 @@ public class Game { if(tauntEnabled) taunt.update(); if (glowEnabled) glow.update(); } - checkWinConditions(false); + checkWinConditions(); } - private static void checkWinConditions(boolean hiderLeave){ + private static void checkWinConditions(){ if(Board.sizeHider() < 1) { if(hiderLeave){ if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); @@ -462,6 +464,7 @@ public class Game { else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); end(WinType.HIDER_WIN); } + hiderLeave = false; } private static void sendHideCountdownMessage(String message, int gameId, int delay) { From 66f9ad10118a3eced3d2d24d9be57a49980026b0 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 12 May 2022 17:14:05 -0400 Subject: [PATCH 37/68] force spectator flight --- .../tylermurphy/hideAndSeek/command/Stop.java | 4 +- .../hideAndSeek/game/EventListener.java | 1 + .../tylermurphy/hideAndSeek/game/Game.java | 181 +++++++++--------- 3 files changed, 95 insertions(+), 91 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index f87457f..efbbfac 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -23,8 +23,6 @@ import static net.tylermurphy.hideAndSeek.configuration.Config.*; import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; -import net.tylermurphy.hideAndSeek.util.WinType; -import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import static net.tylermurphy.hideAndSeek.configuration.Localization.*; @@ -38,7 +36,7 @@ public class Stop implements ICommand { } if(Game.status == Status.STARTING || Game.status == Status.PLAYING) { Game.broadcastMessage(abortPrefix + message("STOP")); - Game.stop(); + Game.end(); } else { sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS")); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index c80a51f..ac937a7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -348,4 +348,5 @@ public class EventListener implements Listener { event.setCancelled(true); } } + } \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 1e02e0f..5069bac 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -152,7 +152,7 @@ public class Game { }, 20 * 30); } - public static void end(WinType type){ + public static void stop(WinType type){ if(status == Status.STANDBY || status == Status.ENDING) return; status = Status.ENDING; for(Player player : Board.getPlayers()) { @@ -176,10 +176,10 @@ public class Game { winners.add(Board.getFirstSeeker().getUniqueId()); Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); } - Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::stop, 5*20); + Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::end, 5*20); } - public static void stop(){ + public static void end(){ if(status == Status.STANDBY) return; tick = 0; countdownTime = -1; @@ -235,64 +235,6 @@ public class Game { Board.reloadLobbyBoards(); } - public static boolean isNotSetup() { - if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; - if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; - if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; - if(mapSaveEnabled) { - File destenation = new File(Main.root + File.separator + getGameWorld()); - if (!destenation.exists()) return true; - } - return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; - } - - public static String getGameWorld(){ - if(mapSaveEnabled) return "hideandseek_"+spawnWorld; - else return spawnWorld; - } - - public static void onTick() { - if(isNotSetup()) return; - if(status == Status.STANDBY) whileWaiting(); - else if(status == Status.STARTING) whileStarting(); - else if(status == Status.PLAYING) whilePlaying(); - tick++; - } - - public static void resetWorldborder(String worldName){ - worldBorder = new Border(); - worldBorder.resetWorldborder(worldName); - } - - public static void broadcastMessage(String message) { - for(Player player : Board.getPlayers()) { - player.sendMessage(message); - } - } - - public static void resetPlayer(Player player) { - player.getInventory().clear(); - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - if (Board.isSeeker(player)) { - if(pvpEnabled) - for(ItemStack item : Items.SEEKER_ITEMS) - player.getInventory().addItem(item); - for(PotionEffect effect : Items.SEEKER_EFFECTS) - player.addPotionEffect(effect); - } else if (Board.isHider(player)) { - if(pvpEnabled) - for(ItemStack item : Items.HIDER_ITEMS) - player.getInventory().addItem(item); - for(PotionEffect effect : Items.HIDER_EFFECTS) - player.addPotionEffect(effect); - if(glowEnabled) { - player.getInventory().addItem(glowPowerupItem); - } - } - } - public static void join(Player player){ if(Game.status == Status.STANDBY || Game.status == Status.ENDING) { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); @@ -369,39 +311,40 @@ public class Game { } } - public static void removeItems(Player player){ - for(ItemStack si : Items.SEEKER_ITEMS) - for(ItemStack i : player.getInventory().getContents()) - if(si.isSimilar(i)) player.getInventory().remove(i); - for(ItemStack hi : Items.HIDER_ITEMS) - for(ItemStack i : player.getInventory().getContents()) - if(hi.isSimilar(i)) player.getInventory().remove(i); + public static void onTick() { + if(isNotSetup()) return; + if(status == Status.STANDBY) whileWaiting(); + else if(status == Status.STARTING) whileStarting(); + else if(status == Status.PLAYING) whilePlaying(); + tick++; } private static void whileWaiting() { - if(lobbyCountdownEnabled){ - if(lobbyMin <= Board.size()){ - if(countdownTime == -1) - countdownTime = countdown; - if(Board.size() >= changeCountdown) - countdownTime = Math.min(countdownTime, 10); - if(tick % 20 == 0) { - countdownTime--; - Board.reloadLobbyBoards(); - } - if(countdownTime == 0){ - start(); - } - } else { - countdownTime = -1; + if(!lobbyCountdownEnabled) return; + if(lobbyMin <= Board.size()){ + if(countdownTime == -1) + countdownTime = countdown; + if(Board.size() >= changeCountdown) + countdownTime = Math.min(countdownTime, 10); + if(tick % 20 == 0) { + countdownTime--; + Board.reloadLobbyBoards(); } + if(countdownTime == 0){ + start(); + } + } else { + countdownTime = -1; } } private static void whileStarting(){ + for(Player spectator : Board.getSpectators()){ + spectator.setFlying(spectator.getAllowFlight()); + } checkWinConditions(); } - + private static void whilePlaying() { for(Player hider : Board.getHiders()) { int distance = 100, temp = 100; @@ -432,6 +375,9 @@ public class Game { break; } } + for(Player spectator : Board.getSpectators()){ + spectator.setFlying(spectator.getAllowFlight()); + } if(tick%20 == 0) { if(gameLength > 0) { Board.reloadGameBoards(); @@ -444,25 +390,84 @@ public class Game { checkWinConditions(); } + public static void resetWorldborder(String worldName){ + worldBorder = new Border(); + worldBorder.resetWorldborder(worldName); + } + + public static void broadcastMessage(String message) { + for(Player player : Board.getPlayers()) { + player.sendMessage(message); + } + } + + public static boolean isNotSetup() { + if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; + if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; + if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; + if(mapSaveEnabled) { + File destenation = new File(Main.root + File.separator + getGameWorld()); + if (!destenation.exists()) return true; + } + return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; + } + + public static String getGameWorld(){ + if(mapSaveEnabled) return "hideandseek_"+spawnWorld; + else return spawnWorld; + } + + public static void resetPlayer(Player player) { + player.getInventory().clear(); + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + if (Board.isSeeker(player)) { + if(pvpEnabled) + for(ItemStack item : Items.SEEKER_ITEMS) + player.getInventory().addItem(item); + for(PotionEffect effect : Items.SEEKER_EFFECTS) + player.addPotionEffect(effect); + } else if (Board.isHider(player)) { + if(pvpEnabled) + for(ItemStack item : Items.HIDER_ITEMS) + player.getInventory().addItem(item); + for(PotionEffect effect : Items.HIDER_EFFECTS) + player.addPotionEffect(effect); + if(glowEnabled) { + player.getInventory().addItem(glowPowerupItem); + } + } + } + + public static void removeItems(Player player){ + for(ItemStack si : Items.SEEKER_ITEMS) + for(ItemStack i : player.getInventory().getContents()) + if(si.isSimilar(i)) player.getInventory().remove(i); + for(ItemStack hi : Items.HIDER_ITEMS) + for(ItemStack i : player.getInventory().getContents()) + if(hi.isSimilar(i)) player.getInventory().remove(i); + } + private static void checkWinConditions(){ if(Board.sizeHider() < 1) { if(hiderLeave){ if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); - end(WinType.NONE); + stop(WinType.NONE); } else { if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); - end(WinType.SEEKER_WIN); + stop(WinType.SEEKER_WIN); } } else if(Board.sizeSeeker() < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); - end(WinType.NONE); + stop(WinType.NONE); } else if(timeLeft < 1) { if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); - end(WinType.HIDER_WIN); + stop(WinType.HIDER_WIN); } hiderLeave = false; } From 5912b12550573349bce922bbd91b1d9f28af4346 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 12 May 2022 22:13:42 -0400 Subject: [PATCH 38/68] parallel change on master --- .github/SECURITY.md | 15 --------------- .github/CODE_OF_CONDUCT.md => CODE_OF_CONDUCT.md | 0 .github/CONTRIBUTING.md => CONTRIBUTING.md | 1 + 3 files changed, 1 insertion(+), 15 deletions(-) delete mode 100644 .github/SECURITY.md rename .github/CODE_OF_CONDUCT.md => CODE_OF_CONDUCT.md (100%) rename .github/CONTRIBUTING.md => CONTRIBUTING.md (99%) diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index 0af3931..0000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,15 +0,0 @@ -# Security Policy - -## Supported Versions - -| Version | Supported | -| ------- | ------------------ | -| 1.3.1 | :white_check_mark: | -| 1.3.0 | :white_check_mark: | -| 1.2.0 | :x: | - -## Reporting a Vulnerability - -If you Find any security vulnerabilitys in the plugin, please contact me at -tylermurphy534@gmail.com IMMEDITALLY. All requests will be taken seriously. -Tell me your plugin version, as non supported versions will be ignored. \ No newline at end of file diff --git a/.github/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md similarity index 100% rename from .github/CODE_OF_CONDUCT.md rename to CODE_OF_CONDUCT.md diff --git a/.github/CONTRIBUTING.md b/CONTRIBUTING.md similarity index 99% rename from .github/CONTRIBUTING.md rename to CONTRIBUTING.md index 49eb107..c9abacf 100644 --- a/.github/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,4 @@ + ## Contributing Guidelines - Do not send any pull requests to the master branch - Any pull requests sent to master will be closed From 619377c72f737139d12fb97be0de07b183f067b8 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Fri, 13 May 2022 11:18:09 -0500 Subject: [PATCH 39/68] refactor: optimize imports --- .../net/tylermurphy/hideAndSeek/Main.java | 27 ++++++++----------- .../tylermurphy/hideAndSeek/command/Help.java | 3 +-- .../tylermurphy/hideAndSeek/command/Join.java | 5 ++-- .../hideAndSeek/command/Leave.java | 7 ++--- .../hideAndSeek/command/Reload.java | 11 ++++---- .../hideAndSeek/command/SaveMap.java | 7 +++-- .../hideAndSeek/command/SetBorder.java | 5 ++-- .../hideAndSeek/command/SetBounds.java | 5 ++-- .../hideAndSeek/command/SetExitLocation.java | 5 ++-- .../hideAndSeek/command/SetLobbyLocation.java | 5 ++-- .../hideAndSeek/command/SetSpawnLocation.java | 6 ++--- .../hideAndSeek/command/Setup.java | 7 +++-- .../hideAndSeek/command/Start.java | 11 ++++---- .../tylermurphy/hideAndSeek/command/Stop.java | 6 ++--- .../tylermurphy/hideAndSeek/command/Top.java | 4 +-- .../tylermurphy/hideAndSeek/command/Wins.java | 4 +-- .../hideAndSeek/configuration/Items.java | 3 ++- .../configuration/Localization.java | 4 +-- .../hideAndSeek/database/Database.java | 4 --- .../hideAndSeek/database/PlayerInfoTable.java | 1 - .../tylermurphy/hideAndSeek/game/Board.java | 12 ++++----- .../hideAndSeek/game/CommandHandler.java | 13 ++++----- .../hideAndSeek/game/EventListener.java | 14 +++++----- .../tylermurphy/hideAndSeek/game/Game.java | 8 +++--- .../hideAndSeek/util/PAPIExpansion.java | 5 ++-- .../tylermurphy/hideAndSeek/util/Packet.java | 7 +++-- .../hideAndSeek/util/TabCompleter.java | 6 ++--- .../hideAndSeek/util/UUIDFetcher.java | 1 - .../hideAndSeek/world/VoidGenerator.java | 8 +++--- .../hideAndSeek/world/WorldLoader.java | 17 ++++-------- 30 files changed, 93 insertions(+), 128 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index cf73757..8267ea5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -19,32 +19,27 @@ package net.tylermurphy.hideAndSeek; -import java.io.File; -import java.util.List; - +import net.tylermurphy.hideAndSeek.configuration.Config; +import net.tylermurphy.hideAndSeek.configuration.Items; +import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.CommandHandler; +import net.tylermurphy.hideAndSeek.game.EventListener; +import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.PAPIExpansion; +import net.tylermurphy.hideAndSeek.util.TabCompleter; import net.tylermurphy.hideAndSeek.util.UUIDFetcher; import org.bukkit.Bukkit; - import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.plugin.messaging.PluginMessageListener; -import org.bukkit.scheduler.BukkitTask; - -import net.tylermurphy.hideAndSeek.game.CommandHandler; -import net.tylermurphy.hideAndSeek.game.EventListener; -import net.tylermurphy.hideAndSeek.util.TabCompleter; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.configuration.Config; -import net.tylermurphy.hideAndSeek.configuration.Localization; -import net.tylermurphy.hideAndSeek.configuration.Items; -import net.tylermurphy.hideAndSeek.game.Board; import org.jetbrains.annotations.NotNull; +import java.io.File; +import java.util.List; + public class Main extends JavaPlugin implements Listener { public static Main plugin; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java index c1934a9..d773e60 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java @@ -19,10 +19,9 @@ package net.tylermurphy.hideAndSeek.command; -import org.bukkit.command.CommandSender; - import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.game.CommandHandler; +import org.bukkit.command.CommandSender; public class Help implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java index 0ca21d1..025ec7f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java @@ -19,15 +19,14 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Game; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Join implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java index 8d8cf76..c625fdc 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java @@ -19,17 +19,14 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.Bukkit; -import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Leave implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java index fc2592b..1ec2c71 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java @@ -19,17 +19,16 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - +import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Items; +import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.command.CommandSender; -import net.tylermurphy.hideAndSeek.configuration.Config; -import net.tylermurphy.hideAndSeek.configuration.Localization; - -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Config.messagePrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Reload implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java index f5e63a5..e9f1cc8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java @@ -19,8 +19,7 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.Bukkit; @@ -28,8 +27,8 @@ import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.scheduler.BukkitRunnable; -import net.tylermurphy.hideAndSeek.Main; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SaveMap implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index 798b99f..11ff225 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -19,15 +19,14 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBorder implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java index 9f4101a..f369f29 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java @@ -19,14 +19,13 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBounds implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java index 7461767..e54fde6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java @@ -19,8 +19,6 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.World; @@ -28,7 +26,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetExitLocation implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java index 69e5e52..bdd8aad 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java @@ -19,8 +19,6 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.World; @@ -28,7 +26,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetLobbyLocation implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java index d5e1cba..83e0145 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java @@ -19,8 +19,6 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.world.WorldLoader; @@ -29,8 +27,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import static net.tylermurphy.hideAndSeek.configuration.Config.addToConfig; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetSpawnLocation implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java index 14a5d6f..af06e0b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java @@ -19,15 +19,14 @@ package net.tylermurphy.hideAndSeek.command; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Game; import org.bukkit.command.CommandSender; -import net.tylermurphy.hideAndSeek.Main; +import java.io.File; import static net.tylermurphy.hideAndSeek.configuration.Config.*; - -import java.io.File; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Setup implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java index 8605764..bab9c5f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java @@ -19,8 +19,7 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; - +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; @@ -28,13 +27,13 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import net.tylermurphy.hideAndSeek.Main; - -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import java.util.Optional; import java.util.Random; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Config.minPlayers; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + public class Start implements ICommand { public void execute(CommandSender sender, String[] args) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index efbbfac..37130d0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -19,13 +19,13 @@ package net.tylermurphy.hideAndSeek.command; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.util.Status; import org.bukkit.command.CommandSender; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Stop implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 51e3574..d362bba 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -27,8 +27,8 @@ import org.bukkit.command.CommandSender; import java.util.List; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Top implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index 9140f49..feed663 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -29,8 +29,8 @@ import org.bukkit.entity.Player; import java.util.UUID; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Wins implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index 22ec84b..c3258b8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -25,7 +25,8 @@ import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.*; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java index d477117..1f421e5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java @@ -19,12 +19,12 @@ package net.tylermurphy.hideAndSeek.configuration; +import net.md_5.bungee.api.ChatColor; + import java.io.File; import java.util.HashMap; import java.util.Map; -import net.md_5.bungee.api.ChatColor; - public class Localization { public static final Map LOCAL = new HashMap<>(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index fe5ac5b..d4a9e0b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -22,9 +22,7 @@ package net.tylermurphy.hideAndSeek.database; import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; import org.sqlite.SQLiteConfig; -import sun.font.ScriptRun; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -32,8 +30,6 @@ import java.nio.ByteBuffer; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; - -import java.sql.Statement; import java.util.UUID; public class Database { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 99ac614..fa31367 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -21,7 +21,6 @@ package net.tylermurphy.hideAndSeek.database; import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.util.WinType; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 61e77e7..8177bee 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -19,12 +19,6 @@ package net.tylermurphy.hideAndSeek.game; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -import java.util.*; -import java.util.stream.Collectors; - import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.util.Version; import org.bukkit.Bukkit; @@ -33,6 +27,12 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scoreboard.*; +import java.util.*; +import java.util.stream.Collectors; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + public class Board { private static final List Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java index 8df3cf2..430e645 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java @@ -19,17 +19,18 @@ package net.tylermurphy.hideAndSeek.game; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import net.tylermurphy.hideAndSeek.command.*; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import net.tylermurphy.hideAndSeek.command.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Config.permissionsRequired; +import static net.tylermurphy.hideAndSeek.configuration.Localization.LOCAL; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class CommandHandler { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index ac937a7..1b49218 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -19,18 +19,17 @@ package net.tylermurphy.hideAndSeek.game; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.util.Version; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.GameMode; +import org.bukkit.Location; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; @@ -41,16 +40,15 @@ import org.bukkit.event.entity.*; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.*; - import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import org.bukkit.projectiles.ProjectileSource; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class EventListener implements Listener { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 5069bac..d49ad1a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -19,13 +19,12 @@ package net.tylermurphy.hideAndSeek.game; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import com.cryptomorin.xseries.messages.ActionBar; import com.cryptomorin.xseries.messages.Titles; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import net.md_5.bungee.api.ChatColor; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.util.*; @@ -37,8 +36,6 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Firework; import org.bukkit.entity.Player; - -import net.tylermurphy.hideAndSeek.Main; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.potion.PotionEffect; @@ -48,7 +45,8 @@ import java.io.File; import java.util.*; import java.util.stream.Collectors; -import static net.tylermurphy.hideAndSeek.configuration.Localization.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; import static net.tylermurphy.hideAndSeek.game.Game.broadcastMessage; public class Game { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index d1ce898..2c33059 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -1,7 +1,5 @@ package net.tylermurphy.hideAndSeek.util; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; - import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.PlayerInfo; @@ -10,6 +8,9 @@ import org.jetbrains.annotations.NotNull; import java.util.UUID; +import static net.tylermurphy.hideAndSeek.configuration.Config.placeholderError; +import static net.tylermurphy.hideAndSeek.configuration.Config.placeholderNoData; + public class PAPIExpansion extends PlaceholderExpansion { @Override diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java b/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java index 9cb17ce..086fd86 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java @@ -19,10 +19,6 @@ package net.tylermurphy.hideAndSeek.util; -import java.lang.reflect.InvocationTargetException; - -import org.bukkit.entity.Player; - import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; @@ -30,6 +26,9 @@ import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.WrappedDataWatcher; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer; +import org.bukkit.entity.Player; + +import java.lang.reflect.InvocationTargetException; public class Packet { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java index 4c949e1..ccc20d0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java @@ -19,14 +19,14 @@ package net.tylermurphy.hideAndSeek.util; +import net.tylermurphy.hideAndSeek.game.CommandHandler; +import org.bukkit.command.CommandSender; + import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; -import net.tylermurphy.hideAndSeek.game.CommandHandler; -import org.bukkit.command.CommandSender; - public class TabCompleter{ public static List handleTabComplete(CommandSender sender, String[] args) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java index 4ab883d..1f99e38 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java @@ -22,7 +22,6 @@ package net.tylermurphy.hideAndSeek.util; import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; import java.io.BufferedReader; import java.io.InputStreamReader; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/VoidGenerator.java b/src/main/java/net/tylermurphy/hideAndSeek/world/VoidGenerator.java index 7b12767..cf4b062 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/VoidGenerator.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/VoidGenerator.java @@ -19,15 +19,15 @@ package net.tylermurphy.hideAndSeek.world; -import java.util.Collections; -import java.util.List; -import java.util.Random; - import org.bukkit.World; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.jetbrains.annotations.NotNull; +import java.util.Collections; +import java.util.List; +import java.util.Random; + public class VoidGenerator extends ChunkGenerator{ public @NotNull List getDefaultPopulators(@NotNull World world) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index 011d334..5a5c17a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -19,22 +19,15 @@ package net.tylermurphy.hideAndSeek.world; -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import net.tylermurphy.hideAndSeek.util.Version; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; -import net.tylermurphy.hideAndSeek.Main; +import java.io.*; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class WorldLoader { From f900dd326828c63a5c81eb123ee6848e1c72b8ea Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Fri, 13 May 2022 11:28:13 -0500 Subject: [PATCH 40/68] refactor: clean up reused code --- .../hideAndSeek/command/SetBorder.java | 4 +-- .../hideAndSeek/configuration/Config.java | 6 ++--- .../hideAndSeek/database/PlayerInfo.java | 11 ++++++-- .../hideAndSeek/game/CommandHandler.java | 2 +- .../hideAndSeek/game/EventListener.java | 27 ++++++++----------- .../tylermurphy/hideAndSeek/game/Game.java | 21 +++++++-------- .../hideAndSeek/world/WorldLoader.java | 4 +-- 7 files changed, 37 insertions(+), 38 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index 11ff225..8b578f0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -44,7 +44,7 @@ public class SetBorder implements ICommand { addToConfig("worldBorder.enabled",false); saveConfig(); sender.sendMessage(messagePrefix + message("WORLDBORDER_DISABLE")); - Game.resetWorldborder(spawnWorld); + Game.resetWorldBorder(spawnWorld); return; } int num,delay,change; @@ -90,7 +90,7 @@ public class SetBorder implements ICommand { addToConfig("worldBorder.move", worldborderChange); sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay)); saveConfig(); - Game.resetWorldborder(spawnWorld); + Game.resetWorldBorder(spawnWorld); } public String getLabel() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 22f4480..5ce2942 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -39,8 +39,8 @@ import java.util.Optional; public class Config { - private static ConfigManager config, leaderboard; - + private static ConfigManager config; + public static String messagePrefix, errorPrefix, @@ -150,7 +150,7 @@ public class Config { config = ConfigManager.create("config.yml"); config.saveConfig(); - leaderboard = ConfigManager.create("leaderboard.yml"); + ConfigManager leaderboard = ConfigManager.create("leaderboard.yml"); //Spawn spawnPosition = new Vector( diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java index 5fbb96b..0070446 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java @@ -23,8 +23,15 @@ import java.util.UUID; public class PlayerInfo { - public UUID uuid; - public int hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths; + public final UUID uuid; + public final int hider_wins; + public final int seeker_wins; + public final int hider_games; + public final int seeker_games; + public final int hider_kills; + public final int seeker_kills; + public final int hider_deaths; + public final int seeker_deaths; public PlayerInfo(UUID uuid, int hider_wins, int seeker_wins, int hider_games, int seeker_games, int hider_kills, int seeker_kills, int hider_deaths, int seeker_deaths) { this.uuid = uuid; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java index 430e645..85a81dd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java @@ -34,7 +34,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class CommandHandler { - public static Map COMMAND_REGISTER = new LinkedHashMap<>(); + public static final Map COMMAND_REGISTER = new LinkedHashMap<>(); private static void registerCommand(ICommand command) { if(!COMMAND_REGISTER.containsKey(command.getLabel())) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java index 1b49218..28110fb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java @@ -76,32 +76,27 @@ public class EventListener implements Listener { } } - @EventHandler(priority = EventPriority.MONITOR) - public void onQuit(PlayerQuitEvent event) { - Board.remove(event.getPlayer()); + private void handleLeave(Player player) { + Board.remove(player); if(Game.status == Status.STANDBY) { Board.reloadLobbyBoards(); } else { Board.reloadGameBoards(); } - for(PotionEffect effect : event.getPlayer().getActivePotionEffects()){ - event.getPlayer().removePotionEffect(effect.getType()); + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); } - Game.removeItems(event.getPlayer()); + Game.removeItems(player); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onQuit(PlayerQuitEvent event) { + handleLeave(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR) public void onKick(PlayerKickEvent event) { - Board.remove(event.getPlayer()); - if(Game.status == Status.STANDBY) { - Board.reloadLobbyBoards(); - } else { - Board.reloadGameBoards(); - } - for(PotionEffect effect : event.getPlayer().getActivePotionEffects()){ - event.getPlayer().removePotionEffect(effect.getType()); - } - Game.removeItems(event.getPlayer()); + handleLeave(event.getPlayer()); } @EventHandler(priority = EventPriority.HIGHEST) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index d49ad1a..cc38bb0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -204,14 +204,7 @@ public class Game { Board.removeBoard(player); Board.remove(player); player.getInventory().clear(); - if(bungeeLeave) { - ByteArrayDataOutput out = ByteStreams.newDataOutput(); - out.writeUTF("Connect"); - out.writeUTF(leaveServer); - player.sendPluginMessage(Main.plugin, "BungeeCord", out.toByteArray()); - } else { - player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); - } + handleBungeeLeave(player); } else { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); Board.createLobbyBoard(player); @@ -274,7 +267,7 @@ public class Game { } } - public static void leave(Player player){ + public static void leave(Player player) { player.setFlying(false); player.setAllowFlight(false); player.setFallDistance(0.0F); @@ -299,7 +292,11 @@ public class Game { for(PotionEffect effect : player.getActivePotionEffects()){ player.removePotionEffect(effect.getType()); } - if(bungeeLeave) { + handleBungeeLeave(player); + } + + private static void handleBungeeLeave(Player player) { + if (bungeeLeave) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); out.writeUTF(leaveServer); @@ -336,7 +333,7 @@ public class Game { } } - private static void whileStarting(){ + private static void whileStarting() { for(Player spectator : Board.getSpectators()){ spectator.setFlying(spectator.getAllowFlight()); } @@ -388,7 +385,7 @@ public class Game { checkWinConditions(); } - public static void resetWorldborder(String worldName){ + public static void resetWorldBorder(String worldName){ worldBorder = new Border(); worldBorder.resetWorldborder(worldName); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index 5a5c17a..e4d8b1a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -31,8 +31,8 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class WorldLoader { - String mapname; - String savename; + final String mapname; + final String savename; public WorldLoader(String mapname) { this.mapname = mapname; From cd0f60bd1369fe80b0163c8f85de8540d01b0524 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Fri, 13 May 2022 11:51:20 -0500 Subject: [PATCH 41/68] refactor: break apart over saturated EventListener.java --- .../net/tylermurphy/hideAndSeek/Main.java | 16 +- .../tylermurphy/hideAndSeek/command/Join.java | 2 +- .../hideAndSeek/command/Leave.java | 2 +- .../hideAndSeek/command/Start.java | 2 +- .../tylermurphy/hideAndSeek/game/Board.java | 6 +- .../hideAndSeek/game/EventListener.java | 345 ------------------ .../tylermurphy/hideAndSeek/game/Game.java | 54 +-- .../tylermurphy/hideAndSeek/game/Glow.java | 54 +++ .../game/listener/BlockedCommandHandler.java | 37 ++ .../game/listener/ChatHandler.java | 28 ++ .../game/listener/DamageHandler.java | 111 ++++++ .../game/listener/InteractHandler.java | 74 ++++ .../game/listener/JoinLeaveHandler.java | 70 ++++ .../game/listener/MovementHandler.java | 27 ++ .../game/listener/PlayerHandler.java | 52 +++ .../game/listener/RespawnHandler.java | 41 +++ 16 files changed, 518 insertions(+), 403 deletions(-) delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index 8267ea5..9506d7c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -25,8 +25,8 @@ import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.CommandHandler; -import net.tylermurphy.hideAndSeek.game.EventListener; import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.game.listener.*; import net.tylermurphy.hideAndSeek.util.PAPIExpansion; import net.tylermurphy.hideAndSeek.util.TabCompleter; import net.tylermurphy.hideAndSeek.util.UUIDFetcher; @@ -50,7 +50,8 @@ public class Main extends JavaPlugin implements Listener { plugin = this; root = this.getServer().getWorldContainer(); data = this.getDataFolder(); - getServer().getPluginManager().registerEvents(new EventListener(), this); + + this.registerListeners(); Config.loadConfig(); Localization.loadLocalization(); @@ -82,6 +83,17 @@ public class Main extends JavaPlugin implements Listener { UUIDFetcher.cleanup(); Board.cleanup(); } + + private void registerListeners() { + getServer().getPluginManager().registerEvents(new BlockedCommandHandler(), this); + getServer().getPluginManager().registerEvents(new ChatHandler(), this); + getServer().getPluginManager().registerEvents(new DamageHandler(), this); + getServer().getPluginManager().registerEvents(new InteractHandler(), this); + getServer().getPluginManager().registerEvents(new JoinLeaveHandler(), this); + getServer().getPluginManager().registerEvents(new MovementHandler(), this); + getServer().getPluginManager().registerEvents(new PlayerHandler(), this); + getServer().getPluginManager().registerEvents(new RespawnHandler(), this); + } public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) { return CommandHandler.handleCommand(sender, args); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java index 025ec7f..8fb002f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java @@ -40,7 +40,7 @@ public class Join implements ICommand { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if(Board.isPlayer(player)){ + if(Board.contains(player)){ sender.sendMessage(errorPrefix + message("GAME_INGAME")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java index c625fdc..e6e95ee 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java @@ -40,7 +40,7 @@ public class Leave implements ICommand { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if(!Board.isPlayer(player)) { + if(!Board.contains(player)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java index bab9c5f..87ef2af 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java @@ -45,7 +45,7 @@ public class Start implements ICommand { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if(!Board.isPlayer(sender)) { + if(!Board.contains(sender)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 8177bee..da9e755 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -40,12 +40,12 @@ public class Board { private static final Map customBoards = new HashMap<>(); private static final Map hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>(); - public static boolean isPlayer(Player player) { + public static boolean contains(Player player) { return playerList.containsKey(player.getUniqueId().toString()); } - public static boolean isPlayer(CommandSender sender) { - return playerList.containsKey(Bukkit.getPlayer(sender.getName()).getUniqueId().toString()); + public static boolean contains(CommandSender sender) { + return contains((Player) sender); } public static boolean isHider(Player player) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java b/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java deleted file mode 100644 index 28110fb..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/EventListener.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.game; - -import com.cryptomorin.xseries.XMaterial; -import com.cryptomorin.xseries.XSound; -import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.util.Status; -import net.tylermurphy.hideAndSeek.util.Version; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.*; -import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.*; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -public class EventListener implements Listener { - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerJoin(PlayerJoinEvent event) { - Board.remove(event.getPlayer()); - Game.removeItems(event.getPlayer()); - if(Game.isNotSetup()) return; - if(autoJoin){ - Game.join(event.getPlayer()); - } else if(teleportToExit) { - if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { - event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); - event.getPlayer().setGameMode(GameMode.ADVENTURE); - } - } else { - if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { - if(Game.status != Status.STANDBY && Game.status != Status.ENDING){ - Game.join(event.getPlayer()); - } else { - event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); - event.getPlayer().setGameMode(GameMode.ADVENTURE); - } - } - } - } - - private void handleLeave(Player player) { - Board.remove(player); - if(Game.status == Status.STANDBY) { - Board.reloadLobbyBoards(); - } else { - Board.reloadGameBoards(); - } - for(PotionEffect effect : player.getActivePotionEffects()){ - player.removePotionEffect(effect.getType()); - } - Game.removeItems(player); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onQuit(PlayerQuitEvent event) { - handleLeave(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onKick(PlayerKickEvent event) { - handleLeave(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onChat(AsyncPlayerChatEvent event){ - if(event.getMessage().equals("fly")){ - event.getPlayer().setAllowFlight(true); - event.getPlayer().setFlying(true); - } - if(event.getMessage().equals("no fly")){ - event.getPlayer().setAllowFlight(false); - event.getPlayer().setFlying(false); - } - if(Board.isSeeker(event.getPlayer())){ - event.setCancelled(true); - Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onMove(PlayerMoveEvent event){ - if(!Board.isPlayer(event.getPlayer())) return; - if(!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; - if(event.getPlayer().hasPermission("hideandseek.leavebounds")) return; - if(event.getTo() == null || event.getTo().getWorld() == null) return; - if(!event.getTo().getWorld().getName().equals(Game.getGameWorld())) return; - if(event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ){ - event.setCancelled(true); - } - } - - public static final Map temp_loc = new HashMap<>(); - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerDeath(PlayerDeathEvent event){ - Player player = event.getEntity(); - if(!Board.isPlayer(player)) return; - event.setKeepInventory(true); - event.setDeathMessage(""); - temp_loc.put(player.getUniqueId(), player.getLocation()); - Main.plugin.getLogger().severe("Player "+player.getName() + " died when not supposed to. Attempting to roll back death."); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerRespawn(PlayerRespawnEvent event){ - Player player = event.getPlayer(); - if(!Board.isPlayer(player)) return; - if(temp_loc.containsKey(player.getUniqueId())){ - player.teleport(temp_loc.get(player.getUniqueId())); - temp_loc.remove(player.getUniqueId()); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityDamage(EntityDamageEvent event) { - // If you are not a player, get out of here - if(!(event.getEntity() instanceof Player)) return; - // Define variables - Player player = (Player) event.getEntity(); - Player attacker = null; - // If player pvp is enabled, and player doesn't die, we do not care - if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5){ return; } - // If no spawn position, we won't be able to manage their death :o - if(spawnPosition == null){ return; } - // If there is an attacker, find them - if (event instanceof EntityDamageByEntityEvent) { - if(((EntityDamageByEntityEvent) event).getDamager() instanceof Player) - attacker = (Player) ((EntityDamageByEntityEvent) event).getDamager(); - else if(((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile) - if(((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player) - attacker = (Player) ((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter(); - } - // Makes sure that if there was an attacking player, that the event is allowed for the game - if(attacker != null){ - // Cancel if one player is in the game but other isn't - if((Board.isPlayer(player) && !Board.isPlayer(attacker)) || (!Board.isPlayer(player) && Board.isPlayer(attacker))){ - event.setCancelled(true); - return; - // Ignore event if neither player are in the game - } else if(!Board.isPlayer(player) && !Board.isPlayer(attacker)){ - return; - // Ignore event if players are on the same team, or one of them is a spectator - } else if(Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)){ - event.setCancelled(true); - return; - // Ignore the event if pvp is disabled, and a hider is trying to attack a seeker - } else if(!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)){ - event.setCancelled(true); - return; - } - // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. - } else if(!pvpEnabled && !allowNaturalCauses){ - event.setCancelled(true); - return; - // Spectators cannot take damage - } else if(Board.isSpectator(player)){ - event.setCancelled(true); - if(Version.atLeast("1.18") && player.getLocation().getY() < -64){ - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - } else if(player.getLocation().getY() < 0){ - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - } - return; - } - // Handle death event - event.setCancelled(true); - // Reset health and play death effect - if(Version.atLeast("1.9")) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute != null) player.setHealth(attribute.getValue()); - XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); - } else { - player.setHealth(player.getMaxHealth()); - XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); - } - // Teleport player to seeker spawn - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - // Broadcast player death message - if (Board.isSeeker(player)) { - Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); - if(Board.getFirstSeeker().getName().equals(player.getName())){ - Board.addDeath(player.getUniqueId()); - } - } else if (Board.isHider(player)) { - if (attacker == null) { - Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); - } else { - Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); - } - Board.addDeath(player.getUniqueId()); - Board.addSeeker(player); - } - // Add leaderboard kills if attacker - if(attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) - Board.addKill(attacker.getUniqueId()); - Game.resetPlayer(player); - Board.reloadBoardTeams(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onFoodLevelChange(FoodLevelChangeEvent event) { - if(event.getEntity() instanceof Player) { - if(!Board.isPlayer((Player) event.getEntity())) return; - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerRegainHealth(EntityRegainHealthEvent event) { - if(event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { - if(event.getEntity() instanceof Player) { - if(!Board.isPlayer((Player) event.getEntity())) return; - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerCommand(PlayerCommandPreprocessEvent event) { - Player player = event.getPlayer(); - String message = event.getMessage(); - String[] array = message.split(" "); - String[] temp = array[0].split(":"); - for(String handle : blockedCommands){ - if( - array[0].substring(1).equalsIgnoreCase(handle) && Board.isPlayer(player) || - temp[temp.length-1].equalsIgnoreCase(handle) && Board.isPlayer(player) - ) { - if(Game.status == Status.STANDBY) return; - player.sendMessage(errorPrefix + message("BLOCKED_COMMAND")); - event.setCancelled(true); - break; - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerInteract(PlayerInteractEvent event) { - if(!Board.isPlayer(event.getPlayer())) return; - if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())){ - event.setCancelled(true); - return; - } - ItemStack temp = event.getItem(); - if(temp == null) return; - if(Game.status == Status.STANDBY) - onPlayerInteractLobby(temp, event); - if(Game.status == Status.PLAYING) - onPlayerInteractGame(temp, event); - } - - private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event){ - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { - event.setCancelled(true); - Game.leave(event.getPlayer()); - } - - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) { - event.setCancelled(true); - if (Game.isNotSetup()) { - event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP")); - return; - } - if (Game.status != Status.STANDBY) { - event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS")); - return; - } - if (Board.size() < minPlayers) { - event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); - return; - } - Game.start(); - } - } - - private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event){ - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { - if(!glowEnabled) return; - Player player = event.getPlayer(); - if(Board.isHider(player)) { - Game.glow.onProjectile(); - player.getInventory().remove(glowPowerupItem); - assert XMaterial.SNOWBALL.parseMaterial() != null; - player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(InventoryClickEvent event) { - if(event.getWhoClicked() instanceof Player){ - Player player = (Player) event.getWhoClicked(); - if(Board.isPlayer(player) && Game.status == Status.STANDBY){ - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onItemDrop(PlayerDropItemEvent event) { - if(Board.isPlayer(event.getPlayer())){ - event.setCancelled(true); - } - } - -} \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index cc38bb0..2f8f8be 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -27,6 +27,7 @@ import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.game.listener.RespawnHandler; import net.tylermurphy.hideAndSeek.util.*; import net.tylermurphy.hideAndSeek.world.WorldLoader; import org.bukkit.*; @@ -221,7 +222,7 @@ public class Game { player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); } } - EventListener.temp_loc.clear(); + RespawnHandler.temp_loc.clear(); if(mapSaveEnabled) worldLoader.unloadMap(); Board.reloadLobbyBoards(); } @@ -401,8 +402,8 @@ public class Game { if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; if(mapSaveEnabled) { - File destenation = new File(Main.root + File.separator + getGameWorld()); - if (!destenation.exists()) return true; + File destination = new File(Main.root + File.separator + getGameWorld()); + if (!destination.exists()) return true; } return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; } @@ -487,53 +488,6 @@ public class Game { } -class Glow { - - private int glowTime; - private boolean running; - - public Glow() { - this.glowTime = 0; - } - - public void onProjectile() { - if(glowStackable) glowTime += glowLength; - else glowTime = glowLength; - running = true; - } - - private void sendPackets(){ - for(Player hider : Board.getHiders()) - for(Player seeker : Board.getSeekers()) - Packet.setGlow(hider, seeker, true); - } - - protected void update() { - if(running) { - sendPackets(); - glowTime--; - glowTime = Math.max(glowTime, 0); - if (glowTime == 0) { - stopGlow(); - } - } - } - - private void stopGlow() { - running = false; - for(Player hider : Board.getHiders()) { - for (Player seeker : Board.getSeekers()) { - Packet.setGlow(hider, seeker, false); - } - } - } - - public boolean isRunning() { - return running; - } - -} - class Taunt { private UUID tauntPlayer; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java new file mode 100644 index 0000000..61cb784 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java @@ -0,0 +1,54 @@ +package net.tylermurphy.hideAndSeek.game; + +import net.tylermurphy.hideAndSeek.util.Packet; +import org.bukkit.entity.Player; + +import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength; +import static net.tylermurphy.hideAndSeek.configuration.Config.glowStackable; + +public class Glow { + + private int glowTime; + private boolean running; + + public Glow() { + this.glowTime = 0; + } + + public void onProjectile() { + if (glowStackable) glowTime += glowLength; + else glowTime = glowLength; + running = true; + } + + private void sendPackets() { + for (Player hider : Board.getHiders()) + for (Player seeker : Board.getSeekers()) + Packet.setGlow(hider, seeker, true); + } + + protected void update() { + if (running) { + sendPackets(); + glowTime--; + glowTime = Math.max(glowTime, 0); + if (glowTime == 0) { + stopGlow(); + } + } + } + + private void stopGlow() { + running = false; + for (Player hider : Board.getHiders()) { + for (Player seeker : Board.getSeekers()) { + Packet.setGlow(hider, seeker, false); + } + } + } + + public boolean isRunning() { + return running; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java new file mode 100644 index 0000000..c91ae41 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java @@ -0,0 +1,37 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.util.Status; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; + +import static net.tylermurphy.hideAndSeek.configuration.Config.blockedCommands; +import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class BlockedCommandHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerCommand(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + String message = event.getMessage(); + String[] array = message.split(" "); + String[] temp = array[0].split(":"); + for(String handle : blockedCommands){ + if ( + array[0].substring(1).equalsIgnoreCase(handle) && Board.contains(player) || + temp[temp.length-1].equalsIgnoreCase(handle) && Board.contains(player) + ) { + if(Game.status == Status.STANDBY) return; + player.sendMessage(errorPrefix + message("BLOCKED_COMMAND")); + event.setCancelled(true); + break; + } + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java new file mode 100644 index 0000000..f0c0ac6 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java @@ -0,0 +1,28 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.game.Board; +import org.bukkit.ChatColor; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; + +public class ChatHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onChat(AsyncPlayerChatEvent event){ + if (event.getMessage().equals("fly")) { + event.getPlayer().setAllowFlight(true); + event.getPlayer().setFlying(true); + } + if (event.getMessage().equals("no fly")) { + event.getPlayer().setAllowFlight(false); + event.getPlayer().setFlying(false); + } + if (Board.isSeeker(event.getPlayer())) { + event.setCancelled(true); + Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java new file mode 100644 index 0000000..f247cd3 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -0,0 +1,111 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import com.cryptomorin.xseries.XSound; +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.util.Version; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +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; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.spawnPosition; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class DamageHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamage(EntityDamageEvent event) { + // If you are not a player, get out of here + if(!(event.getEntity() instanceof Player)) return; + // Define variables + Player player = (Player) event.getEntity(); + Player attacker = null; + // If player pvp is enabled, and player doesn't die, we do not care + if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5){ return; } + // If no spawn position, we won't be able to manage their death :o + if(spawnPosition == null){ return; } + // If there is an attacker, find them + if (event instanceof EntityDamageByEntityEvent) { + if(((EntityDamageByEntityEvent) event).getDamager() instanceof Player) + attacker = (Player) ((EntityDamageByEntityEvent) event).getDamager(); + else if(((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile) + if(((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player) + attacker = (Player) ((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter(); + } + // Makes sure that if there was an attacking player, that the event is allowed for the game + if(attacker != null){ + // Cancel if one player is in the game but other isn't + if((Board.contains(player) && !Board.contains(attacker)) || (!Board.contains(player) && Board.contains(attacker))){ + event.setCancelled(true); + return; + // Ignore event if neither player are in the game + } else if(!Board.contains(player) && !Board.contains(attacker)){ + return; + // Ignore event if players are on the same team, or one of them is a spectator + } else if(Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)){ + event.setCancelled(true); + return; + // Ignore the event if pvp is disabled, and a hider is trying to attack a seeker + } else if(!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)){ + event.setCancelled(true); + return; + } + // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. + } else if(!pvpEnabled && !allowNaturalCauses){ + event.setCancelled(true); + return; + // Spectators cannot take damage + } else if(Board.isSpectator(player)){ + event.setCancelled(true); + if(Version.atLeast("1.18") && player.getLocation().getY() < -64){ + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + } else if(player.getLocation().getY() < 0){ + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + } + return; + } + // Handle death event + event.setCancelled(true); + // Reset health and play death effect + if(Version.atLeast("1.9")) { + AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + if (attribute != null) player.setHealth(attribute.getValue()); + XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); + } else { + player.setHealth(player.getMaxHealth()); + XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); + } + // Teleport player to seeker spawn + player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + // Broadcast player death message + if (Board.isSeeker(player)) { + Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); + if(Board.getFirstSeeker().getName().equals(player.getName())){ + Board.addDeath(player.getUniqueId()); + } + } else if (Board.isHider(player)) { + if (attacker == null) { + Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); + } else { + Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); + } + Board.addDeath(player.getUniqueId()); + Board.addSeeker(player); + } + // Add leaderboard kills if attacker + if(attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) + Board.addKill(attacker.getUniqueId()); + Game.resetPlayer(player); + Board.reloadBoardTeams(); + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java new file mode 100644 index 0000000..5390c77 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -0,0 +1,74 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import com.cryptomorin.xseries.XMaterial; +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.util.Status; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.glowPowerupItem; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class InteractHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerInteract(PlayerInteractEvent event) { + if(!Board.contains(event.getPlayer())) return; + if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())){ + event.setCancelled(true); + return; + } + ItemStack temp = event.getItem(); + if(temp == null) return; + if(Game.status == Status.STANDBY) + onPlayerInteractLobby(temp, event); + if(Game.status == Status.PLAYING) + onPlayerInteractGame(temp, event); + } + + private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event){ + if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { + event.setCancelled(true); + Game.leave(event.getPlayer()); + } + + if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) { + event.setCancelled(true); + if (Game.isNotSetup()) { + event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP")); + return; + } + if (Game.status != Status.STANDBY) { + event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS")); + return; + } + if (Board.size() < minPlayers) { + event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); + return; + } + Game.start(); + } + } + + private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event){ + if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { + if(!glowEnabled) return; + Player player = event.getPlayer(); + if(Board.isHider(player)) { + Game.glow.onProjectile(); + player.getInventory().remove(glowPowerupItem); + assert XMaterial.SNOWBALL.parseMaterial() != null; + player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); + event.setCancelled(true); + } + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java new file mode 100644 index 0000000..221e880 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java @@ -0,0 +1,70 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.util.Status; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerKickEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.potion.PotionEffect; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition; + +public class JoinLeaveHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(PlayerJoinEvent event) { + Board.remove(event.getPlayer()); + Game.removeItems(event.getPlayer()); + if (Game.isNotSetup()) return; + if (autoJoin){ + Game.join(event.getPlayer()); + } else if(teleportToExit) { + if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { + event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + event.getPlayer().setGameMode(GameMode.ADVENTURE); + } + } else { + if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { + if(Game.status != Status.STANDBY && Game.status != Status.ENDING){ + Game.join(event.getPlayer()); + } else { + event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + event.getPlayer().setGameMode(GameMode.ADVENTURE); + } + } + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onQuit(PlayerQuitEvent event) { + handleLeave(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onKick(PlayerKickEvent event) { + handleLeave(event.getPlayer()); + } + + private void handleLeave(Player player) { + Board.remove(player); + if(Game.status == Status.STANDBY) { + Board.reloadLobbyBoards(); + } else { + Board.reloadGameBoards(); + } + for(PotionEffect effect : player.getActivePotionEffects()){ + player.removePotionEffect(effect.getType()); + } + Game.removeItems(player); + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java new file mode 100644 index 0000000..21e02de --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java @@ -0,0 +1,27 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.saveMaxZ; + +public class MovementHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onMove(PlayerMoveEvent event) { + if (!Board.contains(event.getPlayer())) return; + if (!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; + if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return; + if (event.getTo() == null || event.getTo().getWorld() == null) return; + if (!event.getTo().getWorld().getName().equals(Game.getGameWorld())) return; + if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) { + event.setCancelled(true); + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java new file mode 100644 index 0000000..73793a9 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java @@ -0,0 +1,52 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.util.Status; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.player.PlayerDropItemEvent; + +public class PlayerHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onFoodLevelChange(FoodLevelChangeEvent event) { + if(event.getEntity() instanceof Player) { + if(!Board.contains((Player) event.getEntity())) return; + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerRegainHealth(EntityRegainHealthEvent event) { + if(event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) { + if(event.getEntity() instanceof Player) { + if(!Board.contains((Player) event.getEntity())) return; + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(InventoryClickEvent event) { + if (event.getWhoClicked() instanceof Player) { + Player player = (Player) event.getWhoClicked(); + if (Board.contains(player) && Game.status == Status.STANDBY) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onItemDrop(PlayerDropItemEvent event) { + if (Board.contains(event.getPlayer())) { + event.setCancelled(true); + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java new file mode 100644 index 0000000..1c19906 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java @@ -0,0 +1,41 @@ +package net.tylermurphy.hideAndSeek.game.listener; + +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.Board; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerRespawnEvent; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class RespawnHandler implements Listener { + + public static final Map temp_loc = new HashMap<>(); + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerDeath(PlayerDeathEvent event) { + Player player = event.getEntity(); + if(!Board.contains(player)) return; + event.setKeepInventory(true); + event.setDeathMessage(""); + temp_loc.put(player.getUniqueId(), player.getLocation()); + Main.plugin.getLogger().severe("Player " + player.getName() + " died when not supposed to. Attempting to roll back death."); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerRespawn(PlayerRespawnEvent event) { + Player player = event.getPlayer(); + if (!Board.contains(player)) return; + if (temp_loc.containsKey(player.getUniqueId())) { + player.teleport(temp_loc.get(player.getUniqueId())); + temp_loc.remove(player.getUniqueId()); + } + } + +} From 2f4ca0d0f949f38f1d4c1512edeb9b32b80171f7 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Fri, 13 May 2022 12:01:31 -0500 Subject: [PATCH 42/68] refactor: general improvements, fix spacing inconsistencies --- .../net/tylermurphy/hideAndSeek/Main.java | 2 +- .../tylermurphy/hideAndSeek/command/Join.java | 6 +- .../hideAndSeek/command/Leave.java | 6 +- .../hideAndSeek/command/Reload.java | 2 +- .../hideAndSeek/command/SaveMap.java | 8 +- .../hideAndSeek/command/SetBorder.java | 12 +- .../hideAndSeek/command/SetBounds.java | 18 +- .../hideAndSeek/command/SetExitLocation.java | 6 +- .../hideAndSeek/command/SetLobbyLocation.java | 6 +- .../hideAndSeek/command/SetSpawnLocation.java | 10 +- .../hideAndSeek/command/Setup.java | 12 +- .../hideAndSeek/command/Start.java | 16 +- .../tylermurphy/hideAndSeek/command/Stop.java | 4 +- .../tylermurphy/hideAndSeek/command/Top.java | 12 +- .../tylermurphy/hideAndSeek/command/Wins.java | 8 +- .../hideAndSeek/configuration/Config.java | 28 +-- .../configuration/ConfigManager.java | 102 ++++---- .../hideAndSeek/configuration/Items.java | 36 +-- .../configuration/Localization.java | 12 +- .../hideAndSeek/database/Database.java | 2 +- .../hideAndSeek/database/PlayerInfoTable.java | 52 ++--- .../tylermurphy/hideAndSeek/game/Board.java | 148 ++++++------ .../hideAndSeek/game/CommandHandler.java | 12 +- .../tylermurphy/hideAndSeek/game/Game.java | 220 +++++++++--------- .../game/listener/BlockedCommandHandler.java | 4 +- .../game/listener/ChatHandler.java | 2 +- .../game/listener/DamageHandler.java | 36 +-- .../game/listener/InteractHandler.java | 18 +- .../game/listener/JoinLeaveHandler.java | 10 +- .../game/listener/PlayerHandler.java | 10 +- .../game/listener/RespawnHandler.java | 2 +- .../hideAndSeek/util/PAPIExpansion.java | 40 ++-- .../tylermurphy/hideAndSeek/util/Packet.java | 2 +- .../tylermurphy/hideAndSeek/util/Status.java | 7 +- .../hideAndSeek/util/TabCompleter.java | 12 +- .../hideAndSeek/util/UUIDFetcher.java | 10 +- .../tylermurphy/hideAndSeek/util/Version.java | 16 +- .../tylermurphy/hideAndSeek/util/WinType.java | 6 +- .../hideAndSeek/world/WorldLoader.java | 81 +++---- 39 files changed, 498 insertions(+), 498 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index 9506d7c..d061977 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -72,7 +72,7 @@ public class Main extends JavaPlugin implements Listener { Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { new PAPIExpansion().register(); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java index 8fb002f..446fb2d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java @@ -31,16 +31,16 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Join implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.isNotSetup()) { + if (Game.isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } Player player = Bukkit.getServer().getPlayer(sender.getName()); - if(player == null) { + if (player == null) { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if(Board.contains(player)){ + if (Board.contains(player)) { sender.sendMessage(errorPrefix + message("GAME_INGAME")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java index e6e95ee..f508498 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java @@ -31,16 +31,16 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Leave implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.isNotSetup()) { + if (Game.isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } Player player = Bukkit.getServer().getPlayer(sender.getName()); - if(player == null) { + if (player == null) { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if(!Board.contains(player)) { + if (!Board.contains(player)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java index 1ec2c71..d2ed069 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java @@ -34,7 +34,7 @@ public class Reload implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java index e9f1cc8..83f2580 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java @@ -35,22 +35,22 @@ public class SaveMap implements ICommand { public static boolean runningBackup = false; public void execute(CommandSender sender, String[] args) { - if(!mapSaveEnabled){ + if (!mapSaveEnabled) { sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED")); return; } - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) { + if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) { sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN")); return; } sender.sendMessage(messagePrefix + message("MAPSAVE_START")); sender.sendMessage(warningPrefix + message("MAPSAVE_WARNING")); World world = Bukkit.getServer().getWorld(spawnWorld); - if(world == null){ + if (world == null) { throw new RuntimeException("Unable to get world: " + spawnWorld); } world.save(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index 8b578f0..e049a8e 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -31,15 +31,15 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBorder implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if(spawnPosition == null) { + if (spawnPosition == null) { sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN")); return; } - if(args.length < 3) { + if (args.length < 3) { worldborderEnabled = false; addToConfig("worldBorder.enabled",false); saveConfig(); @@ -60,11 +60,11 @@ public class SetBorder implements ICommand { sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(args[2])); return; } - if(num < 100) { + if (num < 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_MIN_SIZE")); return; } - if(change < 1) { + if (change < 1) { sender.sendMessage(errorPrefix + message("WORLDBORDER_CHANGE_SIZE")); return; } @@ -73,7 +73,7 @@ public class SetBorder implements ICommand { newWorldborderPosition.setX(player.getLocation().getBlockX()); newWorldborderPosition.setY(0); newWorldborderPosition.setZ(player.getLocation().getBlockZ()); - if(spawnPosition.distance(newWorldborderPosition) > 100) { + if (spawnPosition.distance(newWorldborderPosition) > 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java index f369f29..719d675 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java @@ -30,31 +30,31 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBounds implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if(spawnPosition == null) { + if (spawnPosition == null) { sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN")); return; } Player player = (Player) sender; - if(!player.getWorld().getName().equals(spawnWorld)){ + if (!player.getWorld().getName().equals(spawnWorld)) { sender.sendMessage(errorPrefix + message("BOUNDS_WRONG_WORLD")); return; } - if(player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0){ + if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0) { sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); return; } boolean first = true; - if(saveMinX != 0 && saveMinZ != 0 && saveMaxX != 0 && saveMaxZ != 0) { + if (saveMinX != 0 && saveMinZ != 0 && saveMaxX != 0 && saveMaxZ != 0) { saveMinX = 0; saveMinZ= 0; saveMaxX = 0; saveMaxZ = 0; } - if(saveMaxX == 0) { + if (saveMaxX == 0) { addToConfig("bounds.max.x", player.getLocation().getBlockX()); saveMaxX = player.getLocation().getBlockX(); - } else if(saveMaxX < player.getLocation().getBlockX()) { + } else if (saveMaxX < player.getLocation().getBlockX()) { first = false; addToConfig("bounds.max.x", player.getLocation().getBlockX()); addToConfig("bounds.min.x", saveMaxX); @@ -65,10 +65,10 @@ public class SetBounds implements ICommand { addToConfig("bounds.min.x", player.getLocation().getBlockX()); saveMinX = player.getLocation().getBlockX(); } - if(saveMaxZ == 0) { + if (saveMaxZ == 0) { addToConfig("bounds.max.z", player.getLocation().getBlockZ()); saveMaxZ = player.getLocation().getBlockZ(); - } else if(saveMaxZ < player.getLocation().getBlockZ()) { + } else if (saveMaxZ < player.getLocation().getBlockZ()) { first = false; addToConfig("bounds.max.z", player.getLocation().getBlockZ()); addToConfig("bounds.min.z", saveMaxZ); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java index e54fde6..de33b93 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java @@ -32,13 +32,13 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetExitLocation implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } Vector newExitPosition = new Vector(); Player player = (Player) sender; - if(player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0){ + if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); return; } @@ -46,7 +46,7 @@ public class SetExitLocation implements ICommand { newExitPosition.setY(player.getLocation().getBlockY()); newExitPosition.setZ(player.getLocation().getBlockZ()); World world = player.getLocation().getWorld(); - if(world == null){ + if (world == null) { throw new RuntimeException("Unable to get world: " + spawnWorld); } exitWorld = world.getName(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java index bdd8aad..a9351fd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java @@ -32,13 +32,13 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetLobbyLocation implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } Vector newLobbyPosition = new Vector(); Player player = (Player) sender; - if(player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0){ + if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); return; } @@ -46,7 +46,7 @@ public class SetLobbyLocation implements ICommand { newLobbyPosition.setY(player.getLocation().getBlockY()); newLobbyPosition.setZ(player.getLocation().getBlockZ()); World world = player.getLocation().getWorld(); - if(world == null){ + if (world == null) { throw new RuntimeException("Unable to get world: " + spawnWorld); } lobbyWorld = world.getName(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java index 83e0145..6a9b572 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java @@ -33,28 +33,28 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetSpawnLocation implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } Vector newSpawnPosition = new Vector(); Player player = (Player) sender; - if(player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0){ + if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); return; } newSpawnPosition.setX(player.getLocation().getBlockX()); newSpawnPosition.setY(player.getLocation().getBlockY()); newSpawnPosition.setZ(player.getLocation().getBlockZ()); - if(worldborderEnabled && newSpawnPosition.distance(worldborderPosition) > 100) { + if (worldborderEnabled && newSpawnPosition.distance(worldborderPosition) > 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); return; } World world = player.getLocation().getWorld(); - if(world == null){ + if (world == null) { throw new RuntimeException("Unable to get world: " + spawnWorld); } - if(mapSaveEnabled && !world.getName().equals(spawnWorld)){ + if (mapSaveEnabled && !world.getName().equals(spawnWorld)) { Game.worldLoader.unloadMap(); Game.worldLoader = new WorldLoader(world.getName()); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java index af06e0b..ec932d8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java @@ -35,30 +35,30 @@ public class Setup implements ICommand { String msg = message("SETUP").toString(); int count = 0; - if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) { + if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) { msg = msg + "\n" + message("SETUP_GAME"); count++; } - if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) { + if (lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) { msg = msg + "\n" + message("SETUP_LOBBY"); count++; } - if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) { + if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) { msg = msg + "\n" + message("SETUP_EXIT"); count++; } - if(saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0) { + if (saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0) { msg = msg + "\n" + message("SETUP_BOUNDS"); count++; } - if(mapSaveEnabled) { + if (mapSaveEnabled) { File destenation = new File(Main.root + File.separator + Game.getGameWorld()); if (!destenation.exists()) { msg = msg + "\n" + message("SETUP_SAVEMAP"); count++; } } - if(count < 1) { + if (count < 1) { sender.sendMessage(messagePrefix + message("SETUP_COMPLETE")); } else { sender.sendMessage(msg); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java index 87ef2af..78f9a64 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java @@ -37,26 +37,26 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Start implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.isNotSetup()) { + if (Game.isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } - if(Game.status != Status.STANDBY) { + if (Game.status != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if(!Board.contains(sender)) { + if (!Board.contains(sender)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } - if(Board.size() < minPlayers) { + if (Board.size() < minPlayers) { sender.sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); return; } String seekerName; - if(args.length < 1) { + if (args.length < 1) { Optional rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); - if(!rand.isPresent()){ + if (!rand.isPresent()) { Main.plugin.getLogger().warning("Failed to select random seeker."); return; } @@ -65,12 +65,12 @@ public class Start implements ICommand { seekerName = args[0]; } Player temp = Bukkit.getPlayer(seekerName); - if(temp == null) { + if (temp == null) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); return; } Player seeker = Board.getPlayer(temp.getUniqueId()); - if(seeker == null) { + if (seeker == null) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index 37130d0..2a310e8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -30,11 +30,11 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Stop implements ICommand { public void execute(CommandSender sender, String[] args) { - if(Game.isNotSetup()) { + if (Game.isNotSetup()) { sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do"); return; } - if(Game.status == Status.STARTING || Game.status == Status.PLAYING) { + if (Game.status == Status.STARTING || Game.status == Status.PLAYING) { Game.broadcastMessage(abortPrefix + message("STOP")); Game.end(); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index d362bba..916656d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -34,14 +34,14 @@ public class Top implements ICommand { public void execute(CommandSender sender, String[] args) { int page; - if(args.length == 0) page = 1; + if (args.length == 0) page = 1; else try{ page = Integer.parseInt(args[0]); - } catch(Exception e){ + } catch(Exception e) { sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(args[0])); return; } - if(page < 1){ + if (page < 1) { sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(page)); return; } @@ -50,14 +50,14 @@ public class Top implements ICommand { ChatColor.WHITE, ChatColor.BOLD, ChatColor.GRAY, page, ChatColor.WHITE)); List infos = Database.playerInfo.getInfoPage(page); int i = 1 + (page-1)*10; - if(infos == null){ + if (infos == null) { sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); return; } - for(PlayerInfo info : infos){ + for(PlayerInfo info : infos) { String name = Main.plugin.getServer().getOfflinePlayer(info.uuid).getName(); ChatColor color; - switch (i){ + switch (i) { case 1: color = ChatColor.YELLOW; break; case 2: color = ChatColor.GRAY; break; case 3: color = ChatColor.GOLD; break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index feed663..1366f07 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -39,9 +39,9 @@ public class Wins implements ICommand { UUID uuid; String name; - if(args.length == 0) { + if (args.length == 0) { Player player = Main.plugin.getServer().getPlayer(sender.getName()); - if(player == null){ + if (player == null) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName())); return; } @@ -52,13 +52,13 @@ public class Wins implements ICommand { try { name = args[0]; uuid = UUIDFetcher.getUUID(args[0]); - } catch (Exception e){ + } catch (Exception e) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); return; } } PlayerInfo info = Database.playerInfo.getInfo(uuid); - if(info == null){ + if (info == null) { sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 5ce2942..793e773 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -217,14 +217,14 @@ public class Config { glowLength = Math.max(1, config.getInt("glow.time")); glowStackable = config.getBoolean("glow.stackable"); glowEnabled = config.getBoolean("glow.enabled") && Version.atLeast("1.9"); - if(glowEnabled) { + if (glowEnabled) { ConfigurationSection item = new YamlConfiguration().createSection("temp"); item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("glow.name"))); item.set("material", config.getString("glow.material")); List lore = config.getStringList("glow.lore"); if (lore != null && !lore.isEmpty()) item.set("lore", lore); ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){} + try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} glowPowerupItem = temp; } @@ -264,17 +264,17 @@ public class Config { placeholderNoData = config.getString("placeholder.noData"); try { countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay")); - } catch (IllegalArgumentException e){ + } catch (IllegalArgumentException e) { countdownDisplay = CountdownDisplay.CHAT; Main.plugin.getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!"); } blockedInteracts = new ArrayList<>(); List tempInteracts = config.getStringList("blockedInteracts"); - for(String id : tempInteracts){ + for(String id : tempInteracts) { Optional optional_mat = XMaterial.matchXMaterial(id); - if(optional_mat.isPresent()){ + if (optional_mat.isPresent()) { Material mat = optional_mat.get().parseMaterial(); - if(mat != null){ + if (mat != null) { blockedInteracts.add(mat.name()); } } @@ -301,35 +301,35 @@ public class Config { BORDER_DECREASING = leaderboard.getString("border.decreasing"); //Lobby Items - if(config.getBoolean("lobbyItems.leave.enabled")) { + if (config.getBoolean("lobbyItems.leave.enabled")) { ConfigurationSection item = new YamlConfiguration().createSection("temp"); item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.leave.name"))); item.set("material", config.getString("lobbyItems.leave.material")); - if(Version.atLeast("1.14")){ - if(config.contains("lobbyItems.leave.model-data") && config.getInt("lobbyItems.leave.model-data") != 0){ + if (Version.atLeast("1.14")) { + if (config.contains("lobbyItems.leave.model-data") && config.getInt("lobbyItems.leave.model-data") != 0) { item.set("model-data", config.getInt("lobbyItems.leave.model-data")); } } List lore = config.getStringList("lobbyItems.leave.lore"); if (lore != null && !lore.isEmpty()) item.set("lore", lore); ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){} + try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} lobbyLeaveItem = temp; lobbyItemLeavePosition = config.getInt("lobbyItems.leave.position"); } - if(config.getBoolean("lobbyItems.start.enabled")) { + if (config.getBoolean("lobbyItems.start.enabled")) { ConfigurationSection item = new YamlConfiguration().createSection("temp"); item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.start.name"))); item.set("material", config.getString("lobbyItems.start.material")); List lore = config.getStringList("lobbyItems.start.lore"); if (lore != null && !lore.isEmpty()) item.set("lore", lore); ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){} + try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} lobbyStartItem = temp; lobbyItemStartAdmin = config.getBoolean("lobbyItems.start.adminOnly"); lobbyItemStartPosition = config.getInt("lobbyItems.start.position"); - if(Version.atLeast("1.14")){ - if(config.contains("lobbyItems.start.model-data") && config.getInt("lobbyItems.start.model-data") != 0){ + if (Version.atLeast("1.14")) { + if (config.contains("lobbyItems.start.model-data") && config.getInt("lobbyItems.start.model-data") != 0) { item.set("model-data", config.getInt("lobbyItems.start.model-data")); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 4bb1a83..5954d05 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -36,35 +36,35 @@ public class ConfigManager { private YamlConfiguration config,defaultConfig; private String defaultFilename; - public static ConfigManager create(String filename){ + public static ConfigManager create(String filename) { return new ConfigManager(filename, filename); } - public static ConfigManager create(String filename, String defaultFilename){ + public static ConfigManager create(String filename, String defaultFilename) { return new ConfigManager(filename, defaultFilename); } - private ConfigManager(String filename, String defaultFilename){ + private ConfigManager(String filename, String defaultFilename) { this.defaultFilename = defaultFilename; this.file = new File(Main.data, filename); File folder = Main.data; - if(!folder.exists()){ - if(!folder.mkdirs()){ + if (!folder.exists()) { + if (!folder.mkdirs()) { throw new RuntimeException("Failed to make directory: " + file.getPath()); } } - if(!file.exists()){ + if (!file.exists()) { try{ InputStream input = Main.plugin.getResource(defaultFilename); - if(input == null){ + if (input == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } java.nio.file.Files.copy(input, file.toPath()); input.close(); - } catch(IOException e){ + } catch(IOException e) { e.printStackTrace(); } } @@ -72,90 +72,90 @@ public class ConfigManager { FileInputStream fileInputStream; try { fileInputStream = new FileInputStream(file); - } catch (FileNotFoundException e){ + } catch (FileNotFoundException e) { throw new RuntimeException("Could not create input stream for "+file.getPath()); } InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8); this.config = new YamlConfiguration(); try { this.config.load(reader); - } catch(InvalidConfigurationException e){ + } catch(InvalidConfigurationException e) { throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); - } catch(IOException e){ + } catch(IOException e) { throw new RuntimeException("Could not access file: "+file.getPath()); } InputStream input = this.getClass().getClassLoader().getResourceAsStream(defaultFilename); - if(input == null){ + if (input == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } InputStreamReader default_reader = new InputStreamReader(input, StandardCharsets.UTF_8); this.defaultConfig = new YamlConfiguration(); try { this.defaultConfig.load(default_reader); - } catch(InvalidConfigurationException e){ + } catch(InvalidConfigurationException e) { throw new RuntimeException("Invalid configuration in config file: "+file.getPath()); - } catch(IOException e){ + } catch(IOException e) { throw new RuntimeException("Could not access file: "+file.getPath()); } try{ fileInputStream.close(); default_reader.close(); - } catch (IOException e){ + } catch (IOException e) { throw new RuntimeException("Unable to finalize loading of config files."); } } - public boolean contains(String path){ + public boolean contains(String path) { return config.contains(path); } - public double getDouble(String path){ + public double getDouble(String path) { double value = config.getDouble(path); - if(value == 0.0D){ + if (value == 0.0D) { return defaultConfig.getDouble(path); } else { return value; } } - public int getInt(String path){ + public int getInt(String path) { int value = config.getInt(path); - if(value == 0){ + if (value == 0) { return defaultConfig.getInt(path); } else { return value; } } - public int getDefaultInt(String path){ + public int getDefaultInt(String path) { return defaultConfig.getInt(path); } - public float getFloat(String path){ + public float getFloat(String path) { float value = (float) config.getDouble(path); - if(value == 0.0F){ + if (value == 0.0F) { return (float) defaultConfig.getDouble(path); } else { return value; } } - public String getString(String path){ + public String getString(String path) { String value = config.getString(path); - if(value == null){ + if (value == null) { return defaultConfig.getString(path); } else { return value; } } - public String getString(String path, String oldPath){ + public String getString(String path, String oldPath) { String value = config.getString(path); - if(value == null){ + if (value == null) { String oldValue = config.getString(oldPath); - if(oldValue == null){ + if (oldValue == null) { return defaultConfig.getString(path); } else { return oldValue; @@ -165,24 +165,24 @@ public class ConfigManager { } } - public List getStringList(String path){ + public List getStringList(String path) { List value = config.getStringList(path); - if(value == null){ + if (value == null) { return defaultConfig.getStringList(path); } else { return value; } } - public void reset(String path){ + public void reset(String path) { config.set(path, defaultConfig.get(path)); } - public void resetFile(String newDefaultFilename){ + public void resetFile(String newDefaultFilename) { this.defaultFilename = newDefaultFilename; InputStream input = Main.plugin.getResource(defaultFilename); - if(input == null){ + if (input == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } InputStreamReader reader = new InputStreamReader(input); @@ -191,63 +191,63 @@ public class ConfigManager { } - public boolean getBoolean(String path){ - if(!config.contains(path)){ + public boolean getBoolean(String path) { + if (!config.contains(path)) { return defaultConfig.getBoolean(path); } else { return config.getBoolean(path); } } - public ConfigurationSection getConfigurationSection(String path){ + public ConfigurationSection getConfigurationSection(String path) { ConfigurationSection section = config.getConfigurationSection(path); - if(section == null){ + if (section == null) { return defaultConfig.getConfigurationSection(path); } else { return section; } } - public void set(String path, Object value){ + public void set(String path, Object value) { config.set(path, value); } - public void saveConfig(){ + public void saveConfig() { try { InputStream is = Main.plugin.getResource(defaultFilename); - if(is == null){ + if (is == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } StringBuilder textBuilder = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8)); Reader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name()))); int c; - while((c = reader.read()) != -1){ + while((c = reader.read()) != -1) { textBuilder.append((char) c); } String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8); Map temp = config.getValues(true); - for(Map.Entry entry: temp.entrySet()){ - if(entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List){ + for(Map.Entry entry: temp.entrySet()) { + if (entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List) { String[] parts = entry.getKey().split("\\."); int index = 0; int i = 0; for(String part : parts) { - if(i == 0) { + if (i == 0) { index = yamlString.indexOf(part+":", index); } else { index = yamlString.indexOf(" " + part+":", index); index++; } i++; - if(index == -1) break; + if (index == -1) break; } - if(index < 10) continue; + if (index < 10) continue; int start = yamlString.indexOf(' ', index); int end = yamlString.indexOf('\n', index); - if(end == -1) end = yamlString.length(); + if (end == -1) end = yamlString.length(); StringBuilder replace = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8)); - if(entry.getValue() instanceof List){ - if(((List) entry.getValue()).isEmpty()){ + if (entry.getValue() instanceof List) { + if (((List) entry.getValue()).isEmpty()) { replace.append("[]"); } else { replace.append("["); @@ -260,7 +260,7 @@ public class ConfigManager { } else { replace.append(entry.getValue()); } - if(entry.getValue() instanceof String){ + if (entry.getValue() instanceof String) { replace.append("\""); replace.reverse(); replace.append("\""); @@ -274,7 +274,7 @@ public class ConfigManager { Writer fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); fileWriter.write(yamlString); fileWriter.close(); - } catch (IOException e){ + } catch (IOException e) { e.printStackTrace(); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index c3258b8..c2d7bed 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -46,9 +46,9 @@ public class Items { int i = 1; while (true) { ConfigurationSection section = SeekerItems.getConfigurationSection(String.valueOf(i)); - if(section == null) break; + if (section == null) break; ItemStack item = createItem(section); - if(item != null) SEEKER_ITEMS.add(item); + if (item != null) SEEKER_ITEMS.add(item); i++; } @@ -57,9 +57,9 @@ public class Items { i = 1; while (true) { ConfigurationSection section = HiderItems.getConfigurationSection(String.valueOf(i)); - if(section == null) break; + if (section == null) break; ItemStack item = createItem(section); - if(item != null) HIDER_ITEMS.add(item); + if (item != null) HIDER_ITEMS.add(item); i++; } SEEKER_EFFECTS = new ArrayList<>(); @@ -67,9 +67,9 @@ public class Items { i = 1; while (true) { ConfigurationSection section = SeekerEffects.getConfigurationSection(String.valueOf(i)); - if(section == null) break; + if (section == null) break; PotionEffect effect = getPotionEffect(section); - if(effect != null) SEEKER_EFFECTS.add(effect); + if (effect != null) SEEKER_EFFECTS.add(effect); i++; } @@ -78,9 +78,9 @@ public class Items { i = 1; while (true) { ConfigurationSection section = HiderEffects.getConfigurationSection(String.valueOf(i)); - if(section == null) break; + if (section == null) break; PotionEffect effect = getPotionEffect(section); - if(effect != null) HIDER_EFFECTS.add(effect); + if (effect != null) HIDER_EFFECTS.add(effect); i++; } @@ -90,11 +90,11 @@ public class Items { ConfigurationSection config = new YamlConfiguration().createSection("temp"); String material = item.getString("material").toUpperCase(); boolean splash = false; - if(!Version.atLeast("1.9")){ - if(material.contains("POTION")){ + if (!Version.atLeast("1.9")) { + if (material.contains("POTION")) { config.set("level", 1); } - if(material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")){ + if (material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")) { material = "POTION"; splash = true; } @@ -103,25 +103,25 @@ public class Items { config.set("material", material); config.set("enchants", item.getConfigurationSection("enchantments")); config.set("unbreakable", item.getBoolean("unbreakable")); - if(Version.atLeast("1.14")){ - if(item.contains("model-data")){ + if (Version.atLeast("1.14")) { + if (item.contains("model-data")) { config.set("model-data", item.getInt("model-data")); } } - if(item.isSet("lore")) + if (item.isSet("lore")) config.set("lore", item.getStringList("lore")); if (material.equalsIgnoreCase("POTION") || material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")) config.set("base-effect", String.format("%s,%s,%s", item.getString("type"), false, splash)); ItemStack stack = XItemStack.deserialize(config); stack.setAmount(item.getInt("amount")); - if(stack.getData().getItemType() == Material.AIR) return null; + if (stack.getData().getItemType() == Material.AIR) return null; return stack; } - private static PotionEffect getPotionEffect(ConfigurationSection item){ + private static PotionEffect getPotionEffect(ConfigurationSection item) { String type = item.getString("type"); - if(type == null) return null; - if(PotionEffectType.getByName(type.toUpperCase()) == null) return null; + if (type == null) return null; + if (PotionEffectType.getByName(type.toUpperCase()) == null) return null; return new PotionEffect( Objects.requireNonNull(PotionEffectType.getByName(type.toUpperCase())), item.getInt("duration"), diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java index 1f421e5..be60b61 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java @@ -40,9 +40,9 @@ public class Localization { int PLUGIN_VERSION = manager.getDefaultInt("version"); int VERSION = manager.getInt("version"); - if(VERSION < PLUGIN_VERSION){ - for(int i = VERSION; i < PLUGIN_VERSION; i++){ - if(i < 1) continue; + if (VERSION < PLUGIN_VERSION) { + for(int i = VERSION; i < PLUGIN_VERSION; i++) { + if (i < 1) continue; String[] changeList = CHANGES.get(Config.locale)[i-1]; for(String change : changeList) manager.reset("Localization." + change); @@ -51,9 +51,9 @@ public class Localization { } String SELECTED_LOCAL = manager.getString("type"); - if(SELECTED_LOCAL == null){ + if (SELECTED_LOCAL == null) { manager.reset("type"); - } else if(!SELECTED_LOCAL.equals(Config.locale)){ + } else if (!SELECTED_LOCAL.equals(Config.locale)) { manager.resetFile("lang"+File.separator+"localization_"+Config.locale +".yml"); } @@ -69,7 +69,7 @@ public class Localization { public static LocalizationString message(String key) { LocalizationString temp = LOCAL.get(key); - if(temp == null) { + if (temp == null) { return new LocalizationString(ChatColor.RED + "" + ChatColor.ITALIC + key + " is not found in localization.yml. This is a plugin issue, please report it."); } return new LocalizationString(temp.toString()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index d4a9e0b..8f8286f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -61,7 +61,7 @@ public class Database { return null; } - public static void init(){ + public static void init() { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index fa31367..9ad8adf 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -37,7 +37,7 @@ public class PlayerInfoTable { private static final Map CACHE = new HashMap<>(); - protected PlayerInfoTable(){ + protected PlayerInfoTable() { String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n" + " uuid BINARY(16) PRIMARY KEY,\n" @@ -51,15 +51,15 @@ public class PlayerInfoTable { + " seeker_deaths int NOT NULL\n" + ");"; - try(Connection connection = Database.connect(); Statement statement = connection.createStatement()){ + try(Connection connection = Database.connect(); Statement statement = connection.createStatement()) { statement.executeUpdate(sql); - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } } - private byte[] encodeUUID(UUID uuid){ + private byte[] encodeUUID(UUID uuid) { try { byte[] bytes = new byte[16]; ByteBuffer.wrap(bytes) @@ -72,13 +72,13 @@ public class PlayerInfoTable { return new byte[0]; } return result; - } catch (IOException e){ + } catch (IOException e) { Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); return new byte[0]; } } - private UUID decodeUUID(byte[] bytes){ + private UUID decodeUUID(byte[] bytes) { InputStream is = new ByteArrayInputStream(bytes); ByteBuffer buffer = ByteBuffer.allocate(16); try { @@ -92,12 +92,12 @@ public class PlayerInfoTable { } @NotNull - public PlayerInfo getInfo(UUID uuid){ + public PlayerInfo getInfo(UUID uuid) { String sql = "SELECT * FROM hs_data WHERE uuid = ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); - if(rs.next()){ + if (rs.next()) { PlayerInfo info = new PlayerInfo( uuid, rs.getInt("hider_wins"), @@ -115,7 +115,7 @@ public class PlayerInfoTable { return info; } rs.close(); - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } @@ -123,12 +123,12 @@ public class PlayerInfoTable { } @Nullable - public PlayerInfo getInfoRanking(String order, int place){ + public PlayerInfo getInfoRanking(String order, int place) { String sql = "SELECT * FROM hs_data ORDER BY "+order+" DESC LIMIT 1 OFFSET ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, place-1); ResultSet rs = statement.executeQuery(); - if(rs.next()){ + if (rs.next()) { UUID uuid = decodeUUID(rs.getBytes("uuid")); PlayerInfo info = new PlayerInfo( uuid, @@ -147,7 +147,7 @@ public class PlayerInfoTable { return info; } rs.close(); - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } @@ -155,13 +155,13 @@ public class PlayerInfoTable { } @Nullable - public List getInfoPage(int page){ + public List getInfoPage(int page) { String sql = "SELECT * FROM hs_data ORDER BY (hider_wins + seeker_wins) DESC LIMIT 10 OFFSET ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, (page-1)*10); ResultSet rs = statement.executeQuery(); List infoList = new ArrayList<>(); - while(rs.next()){ + while(rs.next()) { PlayerInfo info = new PlayerInfo( decodeUUID(rs.getBytes("uuid")), rs.getInt("hider_wins"), @@ -178,7 +178,7 @@ public class PlayerInfoTable { rs.close(); connection.close(); return infoList; - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } @@ -186,27 +186,27 @@ public class PlayerInfoTable { } @Nullable - public Integer getRanking(String order, UUID uuid){ + public Integer getRanking(String order, UUID uuid) { String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND "+order+" > 0;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setBytes(1, encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); - if(rs.next()){ + if (rs.next()) { return rs.getInt("total"); } rs.close(); - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } return null; } - public void addWins(List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type){ - for(UUID uuid : uuids){ + public void addWins(List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type) { + for(UUID uuid : uuids) { String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; PlayerInfo info = getInfo(uuid); - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){ + try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setBytes(1, encodeUUID(uuid)); statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); @@ -217,7 +217,7 @@ public class PlayerInfoTable { statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0)); statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0)); statement.execute(); - } catch (SQLException e){ + } catch (SQLException e) { Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index da9e755..75d2a7d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -52,7 +52,7 @@ public class Board { return Hider.contains(player.getUniqueId().toString()); } - public static boolean isHider(UUID uuid){ + public static boolean isHider(UUID uuid) { return Hider.contains(uuid.toString()); } @@ -60,7 +60,7 @@ public class Board { return Seeker.contains(player.getUniqueId().toString()); } - public static boolean isSeeker(UUID uuid){ + public static boolean isSeeker(UUID uuid) { return Seeker.contains(uuid.toString()); } @@ -80,23 +80,23 @@ public class Board { return playerList.values().size(); } - public static List getHiders(){ + public static List getHiders() { return Hider.stream().map(playerList::get).collect(Collectors.toList()); } - public static List getSeekers(){ + public static List getSeekers() { return Seeker.stream().map(playerList::get).collect(Collectors.toList()); } - public static Player getFirstSeeker(){ + public static Player getFirstSeeker() { return playerList.get(Seeker.get(0)); } - public static List getSpectators(){ + public static List getSpectators() { return Spectator.stream().map(playerList::get).collect(Collectors.toList()); } - public static List getPlayers(){ + public static List getPlayers() { return new ArrayList<>(playerList.values()); } @@ -133,8 +133,8 @@ public class Board { } public static boolean onSameTeam(Player player1, Player player2) { - if(Hider.contains(player1.getUniqueId().toString()) && Hider.contains(player2.getUniqueId().toString())) return true; - else if(Seeker.contains(player1.getUniqueId().toString()) && Seeker.contains(player2.getUniqueId().toString())) return true; + if (Hider.contains(player1.getUniqueId().toString()) && Hider.contains(player2.getUniqueId().toString())) return true; + else if (Seeker.contains(player1.getUniqueId().toString()) && Seeker.contains(player2.getUniqueId().toString())) return true; else return Spectator.contains(player1.getUniqueId().toString()) && Spectator.contains(player2.getUniqueId().toString()); } @@ -148,15 +148,15 @@ public class Board { seeker_deaths.clear(); } - public static void addKill(UUID uuid){ - if(Hider.contains(uuid.toString())){ - if(hider_kills.containsKey(uuid.toString())){ + public static void addKill(UUID uuid) { + if (Hider.contains(uuid.toString())) { + if (hider_kills.containsKey(uuid.toString())) { hider_kills.put(uuid.toString(), hider_kills.get(uuid.toString())+1); } else { hider_kills.put(uuid.toString(), 1); } - } else if(getFirstSeeker().getUniqueId().equals(uuid)){ - if(seeker_kills.containsKey(uuid.toString())){ + } else if (getFirstSeeker().getUniqueId().equals(uuid)) { + if (seeker_kills.containsKey(uuid.toString())) { seeker_kills.put(uuid.toString(), seeker_kills.get(uuid.toString())+1); } else { seeker_kills.put(uuid.toString(), 1); @@ -164,15 +164,15 @@ public class Board { } } - public static void addDeath(UUID uuid){ - if(Hider.contains(uuid.toString())){ - if(hider_deaths.containsKey(uuid.toString())){ + public static void addDeath(UUID uuid) { + if (Hider.contains(uuid.toString())) { + if (hider_deaths.containsKey(uuid.toString())) { hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1); } else { hider_deaths.put(uuid.toString(), 1); } - } else if(getFirstSeeker().getUniqueId().equals(uuid)){ - if(seeker_deaths.containsKey(uuid.toString())){ + } else if (getFirstSeeker().getUniqueId().equals(uuid)) { + if (seeker_deaths.containsKey(uuid.toString())) { seeker_deaths.put(uuid.toString(), seeker_deaths.get(uuid.toString())+1); } else { seeker_deaths.put(uuid.toString(), 1); @@ -180,16 +180,16 @@ public class Board { } } - public static Map getHiderKills(){ + public static Map getHiderKills() { return new HashMap<>(hider_kills); } - public static Map getSeekerKills(){ + public static Map getSeekerKills() { return new HashMap<>(seeker_kills); } - public static Map getHiderDeaths(){ + public static Map getHiderDeaths() { return new HashMap<>(hider_deaths); } - public static Map getSeekerDeaths(){ + public static Map getSeekerDeaths() { return new HashMap<>(seeker_deaths); } @@ -199,27 +199,27 @@ public class Board { private static void createLobbyBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); - if(recreate) { + if (recreate) { board = new CustomBoard(player, LOBBY_TITLE); board.updateTeams(); } int i=0; - for(String line : LOBBY_CONTENTS){ - if(line.equalsIgnoreCase("")){ + for(String line : LOBBY_CONTENTS) { + if (line.equalsIgnoreCase("")) { board.addBlank(); - } else if(line.contains("{COUNTDOWN}")){ - if(!lobbyCountdownEnabled){ + } else if (line.contains("{COUNTDOWN}")) { + if (!lobbyCountdownEnabled) { board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_ADMINSTART)); - } else if(Game.countdownTime == -1){ + } else if (Game.countdownTime == -1) { board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_WAITING)); } else { board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_COUNTING.replace("{AMOUNT}",Game.countdownTime+""))); } - } else if(line.contains("{COUNT}")){ + } else if (line.contains("{COUNT}")) { board.setLine(String.valueOf(i), line.replace("{COUNT}", getPlayers().size()+"")); - } else if(line.contains("{SEEKER%}")){ + } else if (line.contains("{SEEKER%}")) { board.setLine(String.valueOf(i), line.replace("{SEEKER%}", getSeekerPercent()+"")); - } else if(line.contains("{HIDER%}")){ + } else if (line.contains("{HIDER%}")) { board.setLine(String.valueOf(i), line.replace("{HIDER%}", getHiderPercent()+"")); } else { board.setLine(String.valueOf(i), line); @@ -230,58 +230,58 @@ public class Board { customBoards.put(player.getUniqueId().toString(), board); } - public static void createGameBoard(Player player){ + public static void createGameBoard(Player player) { createGameBoard(player, true); } - private static void createGameBoard(Player player, boolean recreate){ + private static void createGameBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); - if(recreate) { + if (recreate) { board = new CustomBoard(player, GAME_TITLE); board.updateTeams(); } int i = 0; - for(String line : GAME_CONTENTS){ - if(line.equalsIgnoreCase("")){ + for(String line : GAME_CONTENTS) { + if (line.equalsIgnoreCase("")) { board.addBlank(); } else { - if(line.contains("{TIME}")) { + if (line.contains("{TIME}")) { String value = Game.timeLeft/60 + "m" + Game.timeLeft%60 + "s"; board.setLine(String.valueOf(i), line.replace("{TIME}", value)); - } else if(line.contains("{TEAM}")) { + } else if (line.contains("{TEAM}")) { String value = getTeam(player); board.setLine(String.valueOf(i), line.replace("{TEAM}", value)); - } else if(line.contains("{BORDER}")) { - if(!worldborderEnabled) continue; - if(Game.worldBorder == null || Game.status == Status.STARTING){ + } else if (line.contains("{BORDER}")) { + if (!worldborderEnabled) continue; + if (Game.worldBorder == null || Game.status == Status.STARTING) { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replace("{AMOUNT}", "0"))); - } else if(!Game.worldBorder.isRunning()) { + } else if (!Game.worldBorder.isRunning()) { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()/60+"").replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()%60+""))); } else { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_DECREASING)); } - } else if(line.contains("{TAUNT}")){ - if(!tauntEnabled) continue; - if(Game.taunt == null || Game.status == Status.STARTING) { + } else if (line.contains("{TAUNT}")) { + if (!tauntEnabled) continue; + if (Game.taunt == null || Game.status == Status.STARTING) { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replace("{AMOUNT}", "0"))); - } else if(!tauntLast && Hider.size() == 1){ + } else if (!tauntLast && Hider.size() == 1) { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_EXPIRED)); - } else if(!Game.taunt.isRunning()) { + } else if (!Game.taunt.isRunning()) { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() / 60 + "").replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() % 60 + ""))); } else { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_ACTIVE)); } - } else if(line.contains("{GLOW}")){ - if(!glowEnabled) return; - if(Game.glow == null || Game.status == Status.STARTING || !Game.glow.isRunning()) { + } else if (line.contains("{GLOW}")) { + if (!glowEnabled) return; + if (Game.glow == null || Game.status == Status.STARTING || !Game.glow.isRunning()) { board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_INACTIVE)); } else { board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_ACTIVE)); } - } else if(line.contains("{#SEEKER}")) { + } else if (line.contains("{#SEEKER}")) { board.setLine(String.valueOf(i), line.replace("{#SEEKER}", getSeekers().size()+"")); - } else if(line.contains("{#HIDER}")) { + } else if (line.contains("{#HIDER}")) { board.setLine(String.valueOf(i), line.replace("{#HIDER}", getHiders().size()+"")); } else { board.setLine(String.valueOf(i), line); @@ -316,27 +316,27 @@ public class Board { } private static String getSeekerPercent() { - if(playerList.values().size() < 2) + if (playerList.values().size() < 2) return " --"; else return " "+(int)(100*(1.0/playerList.size())); } private static String getHiderPercent() { - if(playerList.size() < 2) + if (playerList.size() < 2) return " --"; else return " "+(int)(100-100*(1.0/playerList.size())); } private static String getTeam(Player player) { - if(isHider(player)) return message("HIDER_TEAM_NAME").toString(); - else if(isSeeker(player)) return message("SEEKER_TEAM_NAME").toString(); - else if(isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString(); + if (isHider(player)) return message("HIDER_TEAM_NAME").toString(); + else if (isSeeker(player)) return message("SEEKER_TEAM_NAME").toString(); + else if (isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString(); else return ChatColor.WHITE + "UNKNOWN"; } - public static void cleanup(){ + public static void cleanup() { playerList.clear(); Hider.clear(); Seeker.clear(); @@ -355,13 +355,13 @@ class CustomBoard { private int blanks; private boolean displayed; - public CustomBoard(Player player, String title){ + public CustomBoard(Player player, String title) { ScoreboardManager manager = Bukkit.getScoreboardManager(); assert manager != null; this.board = manager.getNewScoreboard(); this.LINES = new HashMap<>(); this.player = player; - if(Version.atLeast("1.13")){ + if (Version.atLeast("1.13")) { this.obj = board.registerNewObjective( "Scoreboard", "dummy", ChatColor.translateAlternateColorCodes('&', title)); } else { @@ -374,8 +374,8 @@ class CustomBoard { } public void updateTeams() { - try{ board.registerNewTeam("Hider"); } catch (Exception ignored){} - try{ board.registerNewTeam("Seeker"); } catch (Exception ignored){} + try{ board.registerNewTeam("Hider"); } catch (Exception ignored) {} + try{ board.registerNewTeam("Seeker"); } catch (Exception ignored) {} Team hiderTeam = board.getTeam("Hider"); assert hiderTeam != null; for(String entry : hiderTeam.getEntries()) @@ -388,8 +388,8 @@ class CustomBoard { seekerTeam.removeEntry(entry); for(Player player : Board.getSeekers()) seekerTeam.addEntry(player.getName()); - if(Version.atLeast("1.9")){ - if(nametagsVisible) { + if (Version.atLeast("1.9")) { + if (nametagsVisible) { hiderTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OWN_TEAM); seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OTHER_TEAMS); } else { @@ -397,7 +397,7 @@ class CustomBoard { seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER); } } else { - if(nametagsVisible) { + if (nametagsVisible) { hiderTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OTHER_TEAMS); seekerTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OWN_TEAM); } else { @@ -405,7 +405,7 @@ class CustomBoard { seekerTeam.setNameTagVisibility(NameTagVisibility.NEVER); } } - if(Version.atLeast("1.12")){ + if (Version.atLeast("1.12")) { hiderTeam.setColor(ChatColor.GOLD); seekerTeam.setColor(ChatColor.RED); } else { @@ -414,23 +414,23 @@ class CustomBoard { } } - public void setLine(String key, String message){ + public void setLine(String key, String message) { Line line = LINES.get(key); - if(line == null) + if (line == null) addLine(key, ChatColor.translateAlternateColorCodes('&',message)); else updateLine(key, ChatColor.translateAlternateColorCodes('&',message)); } - private void addLine(String key, String message){ + private void addLine(String key, String message) { Score score = obj.getScore(message); score.setScore(LINES.values().size()+1); Line line = new Line(LINES.values().size()+1, message); LINES.put(key, line); } - public void addBlank(){ - if(displayed) return; + public void addBlank() { + if (displayed) return; StringBuilder temp = new StringBuilder(); for(int i = 0; i <= blanks; i ++) temp.append(ChatColor.RESET); @@ -438,7 +438,7 @@ class CustomBoard { addLine("blank"+blanks, temp.toString()); } - private void updateLine(String key, String message){ + private void updateLine(String key, String message) { Line line = LINES.get(key); board.resetScores(line.getMessage()); line.setMessage(message); @@ -460,7 +460,7 @@ class Line { private final int score; private String message; - public Line(int score, String message){ + public Line(int score, String message) { this.score = score; this.message = message; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java index 85a81dd..b7b2dad 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java @@ -37,7 +37,7 @@ public class CommandHandler { public static final Map COMMAND_REGISTER = new LinkedHashMap<>(); private static void registerCommand(ICommand command) { - if(!COMMAND_REGISTER.containsKey(command.getLabel())) { + if (!COMMAND_REGISTER.containsKey(command.getLabel())) { COMMAND_REGISTER.put(command.getLabel().toLowerCase(), command); } } @@ -62,18 +62,18 @@ public class CommandHandler { } public static boolean handleCommand(CommandSender sender, String[] args) { - if(!(sender instanceof Player)) { + if (!(sender instanceof Player)) { sender.sendMessage(errorPrefix + message("COMMAND_PLAYER_ONLY")); - } else if(args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) { - if(permissionsRequired && !sender.hasPermission("hideandseek.about")) { + } else if (args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) { + if (permissionsRequired && !sender.hasPermission("hideandseek.about")) { sender.sendMessage(errorPrefix + LOCAL.get("")); } else { COMMAND_REGISTER.get("about").execute(sender, null); } } else { - if(!args[0].equalsIgnoreCase("about") && !args[0].equalsIgnoreCase("help") && SaveMap.runningBackup) { + if (!args[0].equalsIgnoreCase("about") && !args[0].equalsIgnoreCase("help") && SaveMap.runningBackup) { sender.sendMessage(errorPrefix + message("MAPSAVE_INPROGRESS")); - } else if(permissionsRequired && !sender.hasPermission("hideandseek."+args[0].toLowerCase())) { + } else if (permissionsRequired && !sender.hasPermission("hideandseek."+args[0].toLowerCase())) { sender.sendMessage(errorPrefix + message("COMMAND_NOT_ALLOWED")); } else { try { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 2f8f8be..83b304d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -68,36 +68,36 @@ public class Game { worldLoader = new WorldLoader(spawnWorld); } - public static void start(){ + public static void start() { Optional rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); - if(!rand.isPresent()){ + if (!rand.isPresent()) { Main.plugin.getLogger().warning("Failed to select random seeker."); return; } String seekerName = rand.get().getName(); Player temp = Bukkit.getPlayer(seekerName); - if(temp == null){ + if (temp == null) { Main.plugin.getLogger().warning("Failed to select random seeker."); return; } Player seeker = Board.getPlayer(temp.getUniqueId()); - if(seeker == null){ + if (seeker == null) { Main.plugin.getLogger().warning("Failed to select random seeker."); return; } start(seeker); } - public static void start(Player seeker){ - if(status == Status.STARTING || status == Status.PLAYING) return; - if(mapSaveEnabled && worldLoader.getWorld() != null) { + public static void start(Player seeker) { + if (status == Status.STARTING || status == Status.PLAYING) return; + if (mapSaveEnabled && worldLoader.getWorld() != null) { worldLoader.rollback(); - } else if(mapSaveEnabled) { + } else if (mapSaveEnabled) { worldLoader.loadMap(); } Board.reload(); for(Player temp : Board.getPlayers()) { - if(temp.getName().equals(seeker.getName())) + if (temp.getName().equals(seeker.getName())) continue; Board.addHider(temp); } @@ -107,7 +107,7 @@ public class Game { player.getInventory().clear(); player.setGameMode(GameMode.ADVENTURE); player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } } @@ -121,20 +121,20 @@ public class Game { player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false)); Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString()); } - if(tauntEnabled) + if (tauntEnabled) taunt = new Taunt(); if (glowEnabled) glow = new Glow(); worldBorder = new Border(); worldBorder.resetWorldborder(getGameWorld()); - if(gameLength > 0) + if (gameLength > 0) timeLeft = gameLength; for(Player player : Board.getPlayers()) Board.createGameBoard(player); Board.reloadGameBoards(); status = Status.STARTING; int temp = gameId; - if(countdownDisplay != CountdownDisplay.TITLE) { + if (countdownDisplay != CountdownDisplay.TITLE) { sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30), gameId, 0); } sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); @@ -144,33 +144,33 @@ public class Game { sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> { - if(temp != gameId) return; + if (temp != gameId) return; sendHideCountdownMessage(messagePrefix + message("START"), gameId, 0); for(Player player : Board.getPlayers()) resetPlayer(player); status = Status.PLAYING; }, 20 * 30); } - public static void stop(WinType type){ - if(status == Status.STANDBY || status == Status.ENDING) return; + public static void stop(WinType type) { + if (status == Status.STANDBY || status == Status.ENDING) return; status = Status.ENDING; for(Player player : Board.getPlayers()) { player.getInventory().clear(); - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); - if(Version.atLeast("1.9")){ + if (Version.atLeast("1.9")) { for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); } } } List players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); - if(type == WinType.HIDER_WIN){ + if (type == WinType.HIDER_WIN) { List winners = Board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); - } else if(type == WinType.SEEKER_WIN){ + } else if (type == WinType.SEEKER_WIN) { List winners = new ArrayList<>(); winners.add(Board.getFirstSeeker().getUniqueId()); Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); @@ -178,8 +178,8 @@ public class Game { Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::end, 5*20); } - public static void end(){ - if(status == Status.STANDBY) return; + public static void end() { + if (status == Status.STANDBY) return; tick = 0; countdownTime = -1; status = Status.STANDBY; @@ -187,21 +187,21 @@ public class Game { timeLeft = 0; worldBorder.resetWorldborder(getGameWorld()); for(Player player : Board.getPlayers()) { - for(Player player2 : Board.getPlayers()){ + for(Player player2 : Board.getPlayers()) { player.showPlayer(player2); } player.setAllowFlight(false); player.setFlying(false); - if(Version.atLeast("1.9")){ + if (Version.atLeast("1.9")) { for(Player temp : Board.getPlayers()) { Packet.setGlow(player, temp, false); } } - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); - if(leaveOnEnd){ + if (leaveOnEnd) { Board.removeBoard(player); Board.remove(player); player.getInventory().clear(); @@ -212,33 +212,33 @@ public class Game { player.setGameMode(GameMode.ADVENTURE); Board.addHider(player); player.getInventory().clear(); - if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp())) + if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp())) player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); - if(lobbyLeaveItem != null) + if (lobbyLeaveItem != null) player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); } } RespawnHandler.temp_loc.clear(); - if(mapSaveEnabled) worldLoader.unloadMap(); + if (mapSaveEnabled) worldLoader.unloadMap(); Board.reloadLobbyBoards(); } - public static void join(Player player){ - if(Game.status == Status.STANDBY || Game.status == Status.ENDING) { + public static void join(Player player) { + if (Game.status == Status.STANDBY || Game.status == Status.ENDING) { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); player.getInventory().clear(); - if(lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) + if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); - if(lobbyLeaveItem != null) + if (lobbyLeaveItem != null) player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); Board.addHider(player); - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } player.setGameMode(GameMode.ADVENTURE); @@ -248,7 +248,7 @@ public class Game { Board.addSpectator(player); player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); player.setGameMode(GameMode.ADVENTURE); - for(Player player2 : Board.getPlayers()){ + for(Player player2 : Board.getPlayers()) { player2.hidePlayer(player); } Board.createGameBoard(player); @@ -260,7 +260,7 @@ public class Game { } player.setFoodLevel(20); - if(Version.atLeast("1.9")) { + if (Version.atLeast("1.9")) { AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); if (attribute != null) player.setHealth(attribute.getValue()); } else { @@ -272,25 +272,25 @@ public class Game { player.setFlying(false); player.setAllowFlight(false); player.setFallDistance(0.0F); - for(Player player2 : Board.getPlayers()){ + for(Player player2 : Board.getPlayers()) { player2.showPlayer(player); player.showPlayer(player2); } - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); - if(Board.isHider(player) && status != Status.ENDING && status != Status.STANDBY){ + if (Board.isHider(player) && status != Status.ENDING && status != Status.STANDBY) { hiderLeave = true; } Board.removeBoard(player); Board.remove(player); player.getInventory().clear(); - if(Game.status == Status.STANDBY) { + if (Game.status == Status.STANDBY) { Board.reloadLobbyBoards(); } else { Board.reloadGameBoards(); Board.reloadBoardTeams(); } - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } handleBungeeLeave(player); @@ -308,25 +308,25 @@ public class Game { } public static void onTick() { - if(isNotSetup()) return; - if(status == Status.STANDBY) whileWaiting(); - else if(status == Status.STARTING) whileStarting(); - else if(status == Status.PLAYING) whilePlaying(); + if (isNotSetup()) return; + if (status == Status.STANDBY) whileWaiting(); + else if (status == Status.STARTING) whileStarting(); + else if (status == Status.PLAYING) whilePlaying(); tick++; } private static void whileWaiting() { - if(!lobbyCountdownEnabled) return; - if(lobbyMin <= Board.size()){ - if(countdownTime == -1) + if (!lobbyCountdownEnabled) return; + if (lobbyMin <= Board.size()) { + if (countdownTime == -1) countdownTime = countdown; - if(Board.size() >= changeCountdown) + if (Board.size() >= changeCountdown) countdownTime = Math.min(countdownTime, 10); - if(tick % 20 == 0) { + if (tick % 20 == 0) { countdownTime--; Board.reloadLobbyBoards(); } - if(countdownTime == 0){ + if (countdownTime == 0) { start(); } } else { @@ -335,7 +335,7 @@ public class Game { } private static void whileStarting() { - for(Player spectator : Board.getSpectators()){ + for(Player spectator : Board.getSpectators()) { spectator.setFlying(spectator.getAllowFlight()); } checkWinConditions(); @@ -347,46 +347,46 @@ public class Game { for(Player seeker : Board.getSeekers()) { try { temp = (int) hider.getLocation().distance(seeker.getLocation()); - } catch (Exception e){ + } catch (Exception e) { //Players in different worlds, NOT OK!!! } - if(distance > temp) { + if (distance > temp) { distance = temp; } } - if(seekerPing) switch(tick%10) { + if (seekerPing) switch(tick%10) { case 0: - if(distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch); - if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); + if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch); + if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 3: - if(distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingVolume, seekerPingPitch); - if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); + if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingVolume, seekerPingPitch); + if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 6: - if(distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); + if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; case 9: - if(distance < seekerPingLevel2) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); + if (distance < seekerPingLevel2) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); break; } } - for(Player spectator : Board.getSpectators()){ + for(Player spectator : Board.getSpectators()) { spectator.setFlying(spectator.getAllowFlight()); } - if(tick%20 == 0) { - if(gameLength > 0) { + if (tick%20 == 0) { + if (gameLength > 0) { Board.reloadGameBoards(); timeLeft--; } - if(worldborderEnabled) worldBorder.update(); - if(tauntEnabled) taunt.update(); + if (worldborderEnabled) worldBorder.update(); + if (tauntEnabled) taunt.update(); if (glowEnabled) glow.update(); } checkWinConditions(); } - public static void resetWorldBorder(String worldName){ + public static void resetWorldBorder(String worldName) { worldBorder = new Border(); worldBorder.resetWorldborder(worldName); } @@ -398,18 +398,18 @@ public class Game { } public static boolean isNotSetup() { - if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; - if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; - if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; - if(mapSaveEnabled) { + if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; + if (lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; + if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; + if (mapSaveEnabled) { File destination = new File(Main.root + File.separator + getGameWorld()); if (!destination.exists()) return true; } return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; } - public static String getGameWorld(){ - if(mapSaveEnabled) return "hideandseek_"+spawnWorld; + public static String getGameWorld() { + if (mapSaveEnabled) return "hideandseek_"+spawnWorld; else return spawnWorld; } @@ -419,35 +419,35 @@ public class Game { player.removePotionEffect(effect.getType()); } if (Board.isSeeker(player)) { - if(pvpEnabled) + if (pvpEnabled) for(ItemStack item : Items.SEEKER_ITEMS) player.getInventory().addItem(item); for(PotionEffect effect : Items.SEEKER_EFFECTS) player.addPotionEffect(effect); } else if (Board.isHider(player)) { - if(pvpEnabled) + if (pvpEnabled) for(ItemStack item : Items.HIDER_ITEMS) player.getInventory().addItem(item); for(PotionEffect effect : Items.HIDER_EFFECTS) player.addPotionEffect(effect); - if(glowEnabled) { + if (glowEnabled) { player.getInventory().addItem(glowPowerupItem); } } } - public static void removeItems(Player player){ + public static void removeItems(Player player) { for(ItemStack si : Items.SEEKER_ITEMS) for(ItemStack i : player.getInventory().getContents()) - if(si.isSimilar(i)) player.getInventory().remove(i); + if (si.isSimilar(i)) player.getInventory().remove(i); for(ItemStack hi : Items.HIDER_ITEMS) for(ItemStack i : player.getInventory().getContents()) - if(hi.isSimilar(i)) player.getInventory().remove(i); + if (hi.isSimilar(i)) player.getInventory().remove(i); } - private static void checkWinConditions(){ - if(Board.sizeHider() < 1) { - if(hiderLeave){ + private static void checkWinConditions() { + if (Board.sizeHider() < 1) { + if (hiderLeave) { if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); stop(WinType.NONE); @@ -456,12 +456,12 @@ public class Game { else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); stop(WinType.SEEKER_WIN); } - } else if(Board.sizeSeeker() < 1) { - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); + } else if (Board.sizeSeeker() < 1) { + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); stop(WinType.NONE); - } else if(timeLeft < 1) { - if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); + } else if (timeLeft < 1) { + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); stop(WinType.HIDER_WIN); } @@ -470,14 +470,14 @@ public class Game { private static void sendHideCountdownMessage(String message, int gameId, int delay) { Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> { - if(gameId == Game.gameId){ - for(Player player : Board.getPlayers()){ - if(countdownDisplay == CountdownDisplay.CHAT){ + if (gameId == Game.gameId) { + for(Player player : Board.getPlayers()) { + if (countdownDisplay == CountdownDisplay.CHAT) { player.sendMessage(message); - } else if(countdownDisplay == CountdownDisplay.ACTIONBAR){ + } else if (countdownDisplay == CountdownDisplay.ACTIONBAR) { ActionBar.clearActionBar(player); ActionBar.sendActionBar(player,message); - } else if(countdownDisplay == CountdownDisplay.TITLE){ + } else if (countdownDisplay == CountdownDisplay.TITLE) { Titles.clearTitle(player); Titles.sendTitle(player, 10, 40, 10, " ", message); } @@ -499,9 +499,9 @@ class Taunt { } protected void update() { - if(delay == 0) { - if(running) launchTaunt(); - else if(tauntLast || Board.sizeHider() > 1) executeTaunt(); + if (delay == 0) { + if (running) launchTaunt(); + else if (tauntLast || Board.sizeHider() > 1) executeTaunt(); } else { delay--; delay = Math.max(delay, 0); @@ -510,7 +510,7 @@ class Taunt { private void executeTaunt() { Optional rand = Board.getHiders().stream().skip(new Random().nextInt(Board.size())).findFirst(); - if(!rand.isPresent()){ + if (!rand.isPresent()) { Main.plugin.getLogger().warning("Failed to select random seeker."); return; } @@ -522,10 +522,10 @@ class Taunt { delay = 30; } - private void launchTaunt(){ + private void launchTaunt() { Player taunted = Board.getPlayer(tauntPlayer); - if(taunted != null) { - if(!Board.isHider(taunted)){ + if (taunted != null) { + if (!Board.isHider(taunted)) { Main.plugin.getLogger().info("Taunted played died and is now seeker. Skipping taunt."); tauntPlayer = null; running = false; @@ -533,7 +533,7 @@ class Taunt { return; } World world = taunted.getLocation().getWorld(); - if(world == null){ + if (world == null) { Main.plugin.getLogger().severe("Game world is null while trying to launch taunt."); tauntPlayer = null; running = false; @@ -561,7 +561,7 @@ class Taunt { delay = tauntDelay; } - public int getDelay(){ + public int getDelay() { return delay; } @@ -580,11 +580,11 @@ class Border { delay = 60 * worldborderDelay; } - void update(){ - if(delay == 30 && !running){ + void update() { + if (delay == 30 && !running) { broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN")); - } else if(delay == 0){ - if(running){ + } else if (delay == 0) { + if (running) { delay = 60 * worldborderDelay; running = false; } @@ -594,9 +594,9 @@ class Border { } private void decreaceWorldborder() { - if(currentWorldborderSize == 100) return; + if (currentWorldborderSize == 100) return; int change = worldborderChange; - if(currentWorldborderSize-worldborderChange < 100){ + if (currentWorldborderSize-worldborderChange < 100) { change = currentWorldborderSize-100; } running = true; @@ -613,7 +613,7 @@ class Border { World world = Bukkit.getWorld(worldName); assert world != null; org.bukkit.WorldBorder border = world.getWorldBorder(); - if(worldborderEnabled) { + if (worldborderEnabled) { border.setSize(worldborderSize); border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ()); currentWorldborderSize = worldborderSize; @@ -623,7 +623,7 @@ class Border { } } - public int getDelay(){ + public int getDelay() { return delay; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java index c91ae41..a805fa5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java @@ -21,12 +21,12 @@ public class BlockedCommandHandler implements Listener { String message = event.getMessage(); String[] array = message.split(" "); String[] temp = array[0].split(":"); - for(String handle : blockedCommands){ + for(String handle : blockedCommands) { if ( array[0].substring(1).equalsIgnoreCase(handle) && Board.contains(player) || temp[temp.length-1].equalsIgnoreCase(handle) && Board.contains(player) ) { - if(Game.status == Status.STANDBY) return; + if (Game.status == Status.STANDBY) return; player.sendMessage(errorPrefix + message("BLOCKED_COMMAND")); event.setCancelled(true); break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java index f0c0ac6..523b3ee 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java @@ -10,7 +10,7 @@ import org.bukkit.event.player.AsyncPlayerChatEvent; public class ChatHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) - public void onChat(AsyncPlayerChatEvent event){ + public void onChat(AsyncPlayerChatEvent event) { if (event.getMessage().equals("fly")) { event.getPlayer().setAllowFlight(true); event.getPlayer().setFlying(true); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index f247cd3..5bbfa8c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -25,50 +25,50 @@ public class DamageHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { // If you are not a player, get out of here - if(!(event.getEntity() instanceof Player)) return; + if (!(event.getEntity() instanceof Player)) return; // Define variables Player player = (Player) event.getEntity(); Player attacker = null; // If player pvp is enabled, and player doesn't die, we do not care - if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5){ return; } + if (pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5) { return; } // If no spawn position, we won't be able to manage their death :o - if(spawnPosition == null){ return; } + if (spawnPosition == null) { return; } // If there is an attacker, find them if (event instanceof EntityDamageByEntityEvent) { - if(((EntityDamageByEntityEvent) event).getDamager() instanceof Player) + if (((EntityDamageByEntityEvent) event).getDamager() instanceof Player) attacker = (Player) ((EntityDamageByEntityEvent) event).getDamager(); - else if(((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile) - if(((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player) + else if (((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile) + if (((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player) attacker = (Player) ((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter(); } // Makes sure that if there was an attacking player, that the event is allowed for the game - if(attacker != null){ + if (attacker != null) { // Cancel if one player is in the game but other isn't - if((Board.contains(player) && !Board.contains(attacker)) || (!Board.contains(player) && Board.contains(attacker))){ + if ((Board.contains(player) && !Board.contains(attacker)) || (!Board.contains(player) && Board.contains(attacker))) { event.setCancelled(true); return; // Ignore event if neither player are in the game - } else if(!Board.contains(player) && !Board.contains(attacker)){ + } else if (!Board.contains(player) && !Board.contains(attacker)) { return; // Ignore event if players are on the same team, or one of them is a spectator - } else if(Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)){ + } else if (Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)) { event.setCancelled(true); return; // Ignore the event if pvp is disabled, and a hider is trying to attack a seeker - } else if(!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)){ + } else if (!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)) { event.setCancelled(true); return; } // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. - } else if(!pvpEnabled && !allowNaturalCauses){ + } else if (!pvpEnabled && !allowNaturalCauses) { event.setCancelled(true); return; // Spectators cannot take damage - } else if(Board.isSpectator(player)){ + } else if (Board.isSpectator(player)) { event.setCancelled(true); - if(Version.atLeast("1.18") && player.getLocation().getY() < -64){ + if (Version.atLeast("1.18") && player.getLocation().getY() < -64) { player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - } else if(player.getLocation().getY() < 0){ + } else if (player.getLocation().getY() < 0) { player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); } return; @@ -76,7 +76,7 @@ public class DamageHandler implements Listener { // Handle death event event.setCancelled(true); // Reset health and play death effect - if(Version.atLeast("1.9")) { + if (Version.atLeast("1.9")) { AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); if (attribute != null) player.setHealth(attribute.getValue()); XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); @@ -89,7 +89,7 @@ public class DamageHandler implements Listener { // Broadcast player death message if (Board.isSeeker(player)) { Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); - if(Board.getFirstSeeker().getName().equals(player.getName())){ + if (Board.getFirstSeeker().getName().equals(player.getName())) { Board.addDeath(player.getUniqueId()); } } else if (Board.isHider(player)) { @@ -102,7 +102,7 @@ public class DamageHandler implements Listener { Board.addSeeker(player); } // Add leaderboard kills if attacker - if(attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) + if (attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) Board.addKill(attacker.getUniqueId()); Game.resetPlayer(player); Board.reloadBoardTeams(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java index 5390c77..7aa976a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -20,20 +20,20 @@ public class InteractHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { - if(!Board.contains(event.getPlayer())) return; - if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())){ + if (!Board.contains(event.getPlayer())) return; + if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())) { event.setCancelled(true); return; } ItemStack temp = event.getItem(); - if(temp == null) return; - if(Game.status == Status.STANDBY) + if (temp == null) return; + if (Game.status == Status.STANDBY) onPlayerInteractLobby(temp, event); - if(Game.status == Status.PLAYING) + if (Game.status == Status.PLAYING) onPlayerInteractGame(temp, event); } - private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event){ + private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { event.setCancelled(true); Game.leave(event.getPlayer()); @@ -57,11 +57,11 @@ public class InteractHandler implements Listener { } } - private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event){ + private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { - if(!glowEnabled) return; + if (!glowEnabled) return; Player player = event.getPlayer(); - if(Board.isHider(player)) { + if (Board.isHider(player)) { Game.glow.onProjectile(); player.getInventory().remove(glowPowerupItem); assert XMaterial.SNOWBALL.parseMaterial() != null; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java index 221e880..6e42f57 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java @@ -25,16 +25,16 @@ public class JoinLeaveHandler implements Listener { Board.remove(event.getPlayer()); Game.removeItems(event.getPlayer()); if (Game.isNotSetup()) return; - if (autoJoin){ + if (autoJoin) { Game.join(event.getPlayer()); - } else if(teleportToExit) { + } else if (teleportToExit) { if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().setGameMode(GameMode.ADVENTURE); } } else { if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { - if(Game.status != Status.STANDBY && Game.status != Status.ENDING){ + if (Game.status != Status.STANDBY && Game.status != Status.ENDING) { Game.join(event.getPlayer()); } else { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); @@ -56,12 +56,12 @@ public class JoinLeaveHandler implements Listener { private void handleLeave(Player player) { Board.remove(player); - if(Game.status == Status.STANDBY) { + if (Game.status == Status.STANDBY) { Board.reloadLobbyBoards(); } else { Board.reloadGameBoards(); } - for(PotionEffect effect : player.getActivePotionEffects()){ + for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } Game.removeItems(player); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java index 73793a9..31aedb0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java @@ -16,17 +16,17 @@ public class PlayerHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onFoodLevelChange(FoodLevelChangeEvent event) { - if(event.getEntity() instanceof Player) { - if(!Board.contains((Player) event.getEntity())) return; + if (event.getEntity() instanceof Player) { + if (!Board.contains((Player) event.getEntity())) return; event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerRegainHealth(EntityRegainHealthEvent event) { - if(event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) { - if(event.getEntity() instanceof Player) { - if(!Board.contains((Player) event.getEntity())) return; + if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) { + if (event.getEntity() instanceof Player) { + if (!Board.contains((Player) event.getEntity())) return; event.setCancelled(true); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java index 1c19906..aeda227 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java @@ -21,7 +21,7 @@ public class RespawnHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); - if(!Board.contains(player)) return; + if (!Board.contains(player)) return; event.setKeepInventory(true); event.setDeathMessage(""); temp_loc.put(player.getUniqueId(), player.getLocation()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 2c33059..4af5ff9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -36,49 +36,49 @@ public class PAPIExpansion extends PlaceholderExpansion { @Override public String onRequest(OfflinePlayer player, @NotNull String params) { String[] args = params.split("_"); - if(args.length < 1) return null; - if(args[0].equals("stats") && args.length == 2){ + if (args.length < 1) return null; + if (args[0].equals("stats") && args.length == 2) { PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); return getValue(info, args[1]); - } else if(args[0].equals("stats") && args.length == 3){ + } else if (args[0].equals("stats") && args.length == 3) { UUID uuid; try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfo(uuid); return getValue(info, args[1]); - } else if((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3){ + } else if ((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3) { int place; try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } - if(place < 1) { return placeholderError; } - if(getRanking(args[1]) == null) { return placeholderError; } + if (place < 1) { return placeholderError; } + if (getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfoRanking(getRanking(args[1]), place); - if(info == null) return placeholderNoData; - if(args[0].equals("rank-score")){ + if (info == null) return placeholderNoData; + if (args[0].equals("rank-score")) { return getValue(info, args[1]); } else { return UUIDFetcher.getPlayer(info.uuid).getName(); } - } else if(args[0].equals("rank-place") && args.length == 2){ - if(getRanking(args[1]) == null) { return placeholderError; } + } else if (args[0].equals("rank-place") && args.length == 2) { + if (getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); - if(getValue(info, args[1]).equals("0")) { return "-"; } + if (getValue(info, args[1]).equals("0")) { return "-"; } Integer count = Database.playerInfo.getRanking(getRanking(args[1]), player.getUniqueId()); - if(count == null) { return placeholderNoData; } + if (count == null) { return placeholderNoData; } return count.toString(); - } else if(args[0].equals("rank-place") && args.length == 3){ + } else if (args[0].equals("rank-place") && args.length == 3) { UUID uuid; try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } - if(getRanking(args[1]) == null) { return placeholderError; } + if (getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); - if(getValue(info, args[1]).equals("0")) { return "-"; } + if (getValue(info, args[1]).equals("0")) { return "-"; } Integer count = Database.playerInfo.getRanking(getRanking(args[1]), uuid); - if(count == null) { return placeholderNoData; } + if (count == null) { return placeholderNoData; } return count.toString(); } return null; } - private String getValue(PlayerInfo info, String query){ - if(query == null) return null; + private String getValue(PlayerInfo info, String query) { + if (query == null) return null; switch (query) { case "total-wins": return String.valueOf(info.hider_wins + info.seeker_wins); @@ -109,8 +109,8 @@ public class PAPIExpansion extends PlaceholderExpansion { } } - private String getRanking(String query){ - if(query == null) return null; + private String getRanking(String query) { + if (query == null) return null; switch (query) { case "total-wins": return "(hider_wins + seeker_wins)"; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java b/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java index 086fd86..bb7219f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java @@ -40,7 +40,7 @@ public class Packet { WrappedDataWatcher watcher = new WrappedDataWatcher(); Serializer serializer = Registry.get(Byte.class); watcher.setEntity(target); - if(glowing) { + if (glowing) { watcher.setObject(0, serializer, (byte) (0x40)); } else { watcher.setObject(0, serializer, (byte) (0x0)); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java b/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java index e1ffa22..0ffba00 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java @@ -20,8 +20,7 @@ package net.tylermurphy.hideAndSeek.util; public enum Status { - STANDBY, - STARTING, - PLAYING, - ENDING + + STANDBY, STARTING, PLAYING, ENDING + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java index ccc20d0..85b10ee 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java @@ -27,22 +27,22 @@ import java.util.List; import java.util.Locale; import java.util.stream.Collectors; -public class TabCompleter{ +public class TabCompleter { public static List handleTabComplete(CommandSender sender, String[] args) { - if(args.length == 1) { + if (args.length == 1) { return new ArrayList<>(CommandHandler.COMMAND_REGISTER.keySet()) .stream() .filter(handle -> sender.hasPermission("hideandseek."+handle.toLowerCase()) && handle.toLowerCase().startsWith(args[0].toLowerCase(Locale.ROOT))) .collect(Collectors.toList()); - } else if(args.length > 1) { - if(!CommandHandler.COMMAND_REGISTER.containsKey(args[0].toLowerCase())) { + } else if (args.length > 1) { + if (!CommandHandler.COMMAND_REGISTER.containsKey(args[0].toLowerCase())) { return null; } else { String[] usage = CommandHandler.COMMAND_REGISTER.get(args[0].toLowerCase()).getUsage().split(" "); - if(args.length - 2 < usage.length) { + if (args.length - 2 < usage.length) { String parameter = usage[args.length-2]; - if(parameter.equals("")) { + if (parameter.equals("")) { return null; } else { List temp = new ArrayList<>(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java index 1f99e38..abc3400 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java @@ -40,20 +40,20 @@ public final class UUIDFetcher { private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/"; private static int cacheTask; - public static void init(){ + public static void init() { cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, () -> { CACHE.clear(); PLAYER_CACHE.clear(); }, 600 * 20, 600 * 20); } - public static void cleanup(){ + public static void cleanup() { Main.plugin.getServer().getScheduler().cancelTask(cacheTask); } public static UUID getUUID(String playername) { - if(CACHE.containsKey(playername)) return CACHE.get(playername); + if (CACHE.containsKey(playername)) return CACHE.get(playername); String output = callURL(UUID_URL + playername); StringBuilder result = new StringBuilder(); @@ -72,8 +72,8 @@ public final class UUIDFetcher { return UUID.fromString(uuid.toString()); } - public static OfflinePlayer getPlayer(UUID uuid){ - if(PLAYER_CACHE.containsKey(uuid)) return PLAYER_CACHE.get(uuid); + public static OfflinePlayer getPlayer(UUID uuid) { + if (PLAYER_CACHE.containsKey(uuid)) return PLAYER_CACHE.get(uuid); OfflinePlayer temp = Bukkit.getOfflinePlayer(uuid); PLAYER_CACHE.put(uuid, temp); return temp; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java b/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java index 96854db..fa66fe2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java @@ -9,20 +9,20 @@ public class Version { private static final Map CACHE = new HashMap<>(); - public static boolean atLeast(String testVersion){ + public static boolean atLeast(String testVersion) { - if(CACHE.containsKey(testVersion)) return CACHE.get(testVersion); + if (CACHE.containsKey(testVersion)) return CACHE.get(testVersion); String[] serverCheckTemp = Bukkit.getBukkitVersion().substring(2,Bukkit.getBukkitVersion().indexOf('-')).split("\\."); int[] serverCheck = new int[serverCheckTemp.length]; - for(int i=0; i serverCheck[0]) return false; - else if(customCheck[0] < serverCheck[0]) return true; + private static boolean getResult(int[] customCheck, int[] serverCheck) { + if (customCheck[0] > serverCheck[0]) return false; + else if (customCheck[0] < serverCheck[0]) return true; else { if (customCheck.length == 1 && serverCheck.length == 1) return true; - else if(customCheck.length == 2 && serverCheck.length == 2){ + else if (customCheck.length == 2 && serverCheck.length == 2) { return customCheck[1] <= serverCheck[1]; } else return serverCheck.length == 2; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java b/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java index 3c555cc..1f6ccd8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.util; public enum WinType { - HIDER_WIN, - SEEKER_WIN, - NONE + + HIDER_WIN, SEEKER_WIN, NONE + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index e4d8b1a..20d8ee5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -25,71 +25,72 @@ import org.bukkit.World; import org.bukkit.WorldCreator; import java.io.*; +import java.nio.file.Files; import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class WorldLoader { - final String mapname; - final String savename; + final String mapName; + final String saveName; - public WorldLoader(String mapname) { - this.mapname = mapname; - this.savename = "hideandseek_"+mapname; + public WorldLoader(String mapName) { + this.mapName = mapName; + this.saveName = "hideandseek_"+ mapName; } - public World getWorld(){ - return Bukkit.getServer().getWorld(savename); + public World getWorld() { + return Bukkit.getServer().getWorld(saveName); } - public void unloadMap(){ - World world = Bukkit.getServer().getWorld(savename); - if(world == null){ - Main.plugin.getLogger().warning(savename + " already unloaded."); + public void unloadMap() { + World world = Bukkit.getServer().getWorld(saveName); + if (world == null) { + Main.plugin.getLogger().warning(saveName + " already unloaded."); return; } - if(Bukkit.getServer().unloadWorld(world, false)){ - Main.plugin.getLogger().info("Successfully unloaded " + savename); + if (Bukkit.getServer().unloadWorld(world, false)) { + Main.plugin.getLogger().info("Successfully unloaded " + saveName); }else{ - Main.plugin.getLogger().severe("COULD NOT UNLOAD " + savename); + Main.plugin.getLogger().severe("COULD NOT UNLOAD " + saveName); } } - public void loadMap(){ - Bukkit.getServer().createWorld(new WorldCreator(savename).generator(new VoidGenerator())); - World world = Bukkit.getServer().getWorld(savename); - if(world == null){ - Main.plugin.getLogger().severe("COULD NOT LOAD " + savename); + public void loadMap() { + Bukkit.getServer().createWorld(new WorldCreator(saveName).generator(new VoidGenerator())); + World world = Bukkit.getServer().getWorld(saveName); + if (world == null) { + Main.plugin.getLogger().severe("COULD NOT LOAD " + saveName); return; } world.setAutoSave(false); } - public void rollback(){ + public void rollback() { unloadMap(); loadMap(); } public String save() { - File current = new File(Main.root+File.separator+mapname); - if(current.exists()) { + File current = new File(Main.root+File.separator+ mapName); + if (current.exists()) { try { - File destenation = new File(Main.root+File.separator+savename); - File temp_destenation = new File(Main.root+File.separator+"temp_"+savename); + File destenation = new File(Main.root+File.separator+ saveName); + File temp_destenation = new File(Main.root+File.separator+"temp_"+ saveName); copyFileFolder("region",true); copyFileFolder("entities",true); copyFileFolder("datapacks",false); File srcFile = new File(current, "level.dat"); File destFile = new File(temp_destenation, "level.dat"); copyFile(srcFile,destFile); - if(destenation.exists()) { + if (destenation.exists()) { deleteDirectory(destenation); - if(!destenation.mkdir()){ + if (!destenation.mkdir()) { throw new RuntimeException("Failed to create directory: "+destenation.getPath()); } } - if(!temp_destenation.renameTo(destenation)){ + if (!temp_destenation.renameTo(destenation)) { throw new RuntimeException("Failed to rename directory: "+temp_destenation.getPath()); } } catch(IOException e) { @@ -103,38 +104,38 @@ public class WorldLoader { } private void copyFileFolder(String name, Boolean isMca) throws IOException { - File region = new File(Main.root+File.separator+mapname+File.separator+name); - File temp = new File(Main.root+File.separator+"temp_"+savename+File.separator+name); + File region = new File(Main.root+File.separator+ mapName +File.separator+name); + File temp = new File(Main.root+File.separator+"temp_"+ saveName +File.separator+name); System.out.println(region.getAbsolutePath()); System.out.println(temp.getAbsolutePath()); - if(region.exists() && region.isDirectory()) { + if (region.exists() && region.isDirectory()) { System.out.println("passed"); - if(!temp.exists()) - if(!temp.mkdirs()) + if (!temp.exists()) + if (!temp.mkdirs()) throw new IOException("Couldn't create region directory!"); String[] files = region.list(); - if(files == null){ + if (files == null) { Main.plugin.getLogger().severe("Region directory is null or cannot be accessed"); return; } for (String file : files) { System.out.println("Testing file "+ file); - if(isMca) { + if (isMca) { int minX = (int)Math.floor(saveMinX / 512.0); int minZ = (int)Math.floor(saveMinZ / 512.0); int maxX = (int)Math.floor(saveMaxX / 512.0); int maxZ = (int)Math.floor(saveMaxZ / 512.0); String[] parts = file.split("\\."); - if(parts.length > 1) { + if (parts.length > 1) { Main.plugin.getLogger().info(file); - if( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ ) + if ( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ ) continue; } } File srcFile = new File(region, file); - if(srcFile.isDirectory()) { + if (srcFile.isDirectory()) { copyFileFolder(name+File.separator+file, false); } else { File destFile = new File(temp, file); @@ -145,8 +146,8 @@ public class WorldLoader { } private void copyFile(File source, File target) throws IOException { - InputStream in = new FileInputStream(source); - OutputStream out = new FileOutputStream(target); + InputStream in = Files.newInputStream(source.toPath()); + OutputStream out = Files.newOutputStream(target.toPath()); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) @@ -162,7 +163,7 @@ public class WorldLoader { deleteDirectory(file); } } - if(!directoryToBeDeleted.delete()){ + if (!directoryToBeDeleted.delete()) { throw new RuntimeException("Failed to delete directory: "+directoryToBeDeleted.getPath()); } } From 1be91d9860abea449fa2abf51ee52cd0b973e703 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Fri, 13 May 2022 12:13:07 -0500 Subject: [PATCH 43/68] typos: fix typos in CONTRIBUTING.md --- CONTRIBUTING.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c9abacf..1e992d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,13 +2,13 @@ ## Contributing Guidelines - Do not send any pull requests to the master branch - Any pull requests sent to master will be closed - - Send pull requets to the current beta branch (usually named as an unreleased version) -- Please tell us why you think this change is nessessary - - We dont want to spend lots of time browsing through your code changes + - Send pull requests to the current beta branch (usually named as an unreleased version) +- Please tell us why you think this change is necessary + - We don't want to spend lots of time browsing through your code changes - Describe your changes -- Do not repoen a pull request if we closed it for not being a nessary feature +- Do not reopen a pull request if we closed it for not being a necessary feature - Do not change credits in any of the files -- If making a new language file, follow the local naming convencion - - localization-[LANGUAGE](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes#)_[TERROTORY](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).yml. You can find the 2 letter codes in the links. +- If making a new language file, follow the local naming convention + - localization-[LANGUAGE](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes#)_[TERRITORY](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).yml. You can find the 2-letter codes in the links. - Common sense, please... - File subject to change in the future From ea8f76493141717296e1f59fbdab21c39f1937be Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 13 May 2022 21:17:46 -0400 Subject: [PATCH 44/68] refactor and encapsulate classes --- .../net/tylermurphy/hideAndSeek/Main.java | 66 +- .../tylermurphy/hideAndSeek/command/Help.java | 2 +- .../tylermurphy/hideAndSeek/command/Join.java | 9 +- .../hideAndSeek/command/Leave.java | 9 +- .../hideAndSeek/command/Reload.java | 6 +- .../hideAndSeek/command/SaveMap.java | 9 +- .../hideAndSeek/command/SetBorder.java | 10 +- .../hideAndSeek/command/SetBounds.java | 6 +- .../hideAndSeek/command/SetExitLocation.java | 74 -- .../hideAndSeek/command/SetLobbyLocation.java | 74 -- .../hideAndSeek/command/SetSpawnLocation.java | 83 --- .../hideAndSeek/command/Setup.java | 3 +- .../hideAndSeek/command/Start.java | 20 +- .../tylermurphy/hideAndSeek/command/Stop.java | 12 +- .../tylermurphy/hideAndSeek/command/Top.java | 5 +- .../tylermurphy/hideAndSeek/command/Wins.java | 10 +- .../command/location/SetExitLocation.java | 53 ++ .../command/location/SetLobbyLocation.java | 54 ++ .../command/location/SetSpawnLocation.java | 66 ++ .../command/location/util/LocationUtils.java | 57 ++ .../command/location/util/Locations.java | 27 + .../hideAndSeek/configuration/Config.java | 6 +- .../configuration/ConfigManager.java | 10 +- .../hideAndSeek/configuration/Items.java | 2 +- .../hideAndSeek/database/Database.java | 84 ++- .../hideAndSeek/database/PlayerInfoTable.java | 95 +-- .../tylermurphy/hideAndSeek/game/Board.java | 128 ++-- .../tylermurphy/hideAndSeek/game/Game.java | 639 +++++------------- .../hideAndSeek/game/events/Border.java | 71 ++ .../hideAndSeek/game/{ => events}/Glow.java | 15 +- .../hideAndSeek/game/events/Taunt.java | 101 +++ .../game/listener/BlockedCommandHandler.java | 11 +- .../game/listener/ChatHandler.java | 6 +- .../game/listener/DamageHandler.java | 66 +- .../game/listener/InteractHandler.java | 25 +- .../game/listener/JoinLeaveHandler.java | 42 +- .../game/listener/MovementHandler.java | 9 +- .../game/listener/PlayerHandler.java | 12 +- .../game/listener/RespawnHandler.java | 7 +- .../{ => game}/util/CountdownDisplay.java | 2 +- .../hideAndSeek/{ => game}/util/Packet.java | 2 +- .../hideAndSeek/game/util/PlayerUtil.java | 120 ++++ .../hideAndSeek/{ => game}/util/Status.java | 4 +- .../hideAndSeek/{ => game}/util/Version.java | 2 +- .../hideAndSeek/{ => game}/util/WinType.java | 2 +- .../{game => util}/CommandHandler.java | 5 +- .../hideAndSeek/util/PAPIExpansion.java | 22 +- .../hideAndSeek/util/TabCompleter.java | 1 - .../hideAndSeek/util/UUIDFetcher.java | 119 ---- .../hideAndSeek/world/WorldLoader.java | 35 +- 50 files changed, 1130 insertions(+), 1168 deletions(-) delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java rename src/main/java/net/tylermurphy/hideAndSeek/game/{ => events}/Glow.java (67%) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/events/Taunt.java rename src/main/java/net/tylermurphy/hideAndSeek/{ => game}/util/CountdownDisplay.java (94%) rename src/main/java/net/tylermurphy/hideAndSeek/{ => game}/util/Packet.java (97%) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java rename src/main/java/net/tylermurphy/hideAndSeek/{ => game}/util/Status.java (88%) rename src/main/java/net/tylermurphy/hideAndSeek/{ => game}/util/Version.java (97%) rename src/main/java/net/tylermurphy/hideAndSeek/{ => game}/util/WinType.java (94%) rename src/main/java/net/tylermurphy/hideAndSeek/{game => util}/CommandHandler.java (92%) delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index d061977..fc4b2cc 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -24,12 +24,12 @@ import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.CommandHandler; +import net.tylermurphy.hideAndSeek.game.util.Status; +import net.tylermurphy.hideAndSeek.util.CommandHandler; import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.listener.*; import net.tylermurphy.hideAndSeek.util.PAPIExpansion; import net.tylermurphy.hideAndSeek.util.TabCompleter; -import net.tylermurphy.hideAndSeek.util.UUIDFetcher; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -42,14 +42,15 @@ import java.util.List; public class Main extends JavaPlugin implements Listener { - public static Main plugin; - public static File root, data; - private int onTickTask; + private static Main instance; + + private Database database; + private Board board; + private Game game; public void onEnable() { - plugin = this; - root = this.getServer().getWorldContainer(); - data = this.getDataFolder(); + + instance = this; this.registerListeners(); @@ -58,30 +59,29 @@ public class Main extends JavaPlugin implements Listener { Items.loadItems(); CommandHandler.registerCommands(); - Board.reload(); - Database.init(); - UUIDFetcher.init(); - onTickTask = Bukkit.getServer().getScheduler().runTaskTimer(this, () -> { - try{ - Game.onTick(); - } catch (Exception e) { - e.printStackTrace(); - } - },0,1).getTaskId(); + board = new Board(); + database = new Database(); + + game = new Game(board); + + getServer().getScheduler().runTaskTimer(this, this::onTick,0,1).getTaskId(); Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new PAPIExpansion().register(); } } - + public void onDisable() { - Main.plugin.getServer().getScheduler().cancelTask(onTickTask); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this); - UUIDFetcher.cleanup(); - Board.cleanup(); + board.cleanup(); + } + + private void onTick() { + if(game.getStatus() == Status.ENDED) game = new Game(board); + game.onTick(); } private void registerListeners() { @@ -102,5 +102,25 @@ public class Main extends JavaPlugin implements Listener { public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { return TabCompleter.handleTabComplete(sender, args); } + + public static Main getInstance() { + return instance; + } + + public File getWorldContainer() { + return this.getServer().getWorldContainer(); + } + + public Database getDatabase() { + return database; + } + + public Board getBoard(){ + return board; + } + + public Game getGame(){ + return game; + } } \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java index d773e60..11b0b0a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.md_5.bungee.api.ChatColor; -import net.tylermurphy.hideAndSeek.game.CommandHandler; +import net.tylermurphy.hideAndSeek.util.CommandHandler; import org.bukkit.command.CommandSender; public class Help implements ICommand { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java index 446fb2d..eb8fd82 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java @@ -19,8 +19,7 @@ package net.tylermurphy.hideAndSeek.command; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -31,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Join implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.isNotSetup()) { + if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } @@ -40,12 +39,12 @@ public class Join implements ICommand { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if (Board.contains(player)) { + if (Main.getInstance().getBoard().contains(player)) { sender.sendMessage(errorPrefix + message("GAME_INGAME")); return; } - Game.join(player); + Main.getInstance().getGame().join(player); } public String getLabel() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java index f508498..0b895b4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java @@ -19,8 +19,7 @@ package net.tylermurphy.hideAndSeek.command; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -31,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Leave implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.isNotSetup()) { + if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } @@ -40,11 +39,11 @@ public class Leave implements ICommand { sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); return; } - if (!Board.contains(player)) { + if (!Main.getInstance().getBoard().contains(player)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } - Game.leave(player); + Main.getInstance().getGame().leave(player); } public String getLabel() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java index d2ed069..0f959f2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java @@ -19,11 +19,11 @@ package net.tylermurphy.hideAndSeek.command; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.command.CommandSender; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; @@ -34,7 +34,7 @@ public class Reload implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java index 83f2580..e69c882 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java @@ -20,8 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.CommandSender; @@ -39,7 +38,7 @@ public class SaveMap implements ICommand { sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED")); return; } - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } @@ -57,12 +56,12 @@ public class SaveMap implements ICommand { BukkitRunnable runnable = new BukkitRunnable() { public void run() { sender.sendMessage( - Game.worldLoader.save() + Main.getInstance().getGame().getWorldLoader().save() ); runningBackup = false; } }; - runnable.runTaskAsynchronously(Main.plugin); + runnable.runTaskAsynchronously(Main.getInstance()); runningBackup = true; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index e049a8e..8114838 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -19,8 +19,8 @@ package net.tylermurphy.hideAndSeek.command; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; @@ -31,7 +31,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBorder implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } @@ -44,7 +44,7 @@ public class SetBorder implements ICommand { addToConfig("worldBorder.enabled",false); saveConfig(); sender.sendMessage(messagePrefix + message("WORLDBORDER_DISABLE")); - Game.resetWorldBorder(spawnWorld); + Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld); return; } int num,delay,change; @@ -90,7 +90,7 @@ public class SetBorder implements ICommand { addToConfig("worldBorder.move", worldborderChange); sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay)); saveConfig(); - Game.resetWorldBorder(spawnWorld); + Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld); } public String getLabel() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java index 719d675..7d2da96 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java @@ -19,8 +19,8 @@ package net.tylermurphy.hideAndSeek.command; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -30,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBounds implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java deleted file mode 100644 index de33b93..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetExitLocation.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.command; - -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -public class SetExitLocation implements ICommand { - - public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { - sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); - return; - } - Vector newExitPosition = new Vector(); - Player player = (Player) sender; - if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { - sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); - return; - } - newExitPosition.setX(player.getLocation().getBlockX()); - newExitPosition.setY(player.getLocation().getBlockY()); - newExitPosition.setZ(player.getLocation().getBlockZ()); - World world = player.getLocation().getWorld(); - if (world == null) { - throw new RuntimeException("Unable to get world: " + spawnWorld); - } - exitWorld = world.getName(); - exitPosition = newExitPosition; - sender.sendMessage(messagePrefix + message("EXIT_SPAWN")); - addToConfig("spawns.exit.x", exitPosition.getX()); - addToConfig("spawns.exit.y", exitPosition.getY()); - addToConfig("spawns.exit.z", exitPosition.getZ()); - addToConfig("spawns.exit.world", player.getLocation().getWorld().getName()); - saveConfig(); - } - - public String getLabel() { - return "setexit"; - } - - public String getUsage() { - return ""; - } - - public String getDescription() { - return "Sets hide and seeks exit location to current position and world"; - } - -} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java deleted file mode 100644 index a9351fd..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetLobbyLocation.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.command; - -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -public class SetLobbyLocation implements ICommand { - - public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { - sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); - return; - } - Vector newLobbyPosition = new Vector(); - Player player = (Player) sender; - if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { - sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); - return; - } - newLobbyPosition.setX(player.getLocation().getBlockX()); - newLobbyPosition.setY(player.getLocation().getBlockY()); - newLobbyPosition.setZ(player.getLocation().getBlockZ()); - World world = player.getLocation().getWorld(); - if (world == null) { - throw new RuntimeException("Unable to get world: " + spawnWorld); - } - lobbyWorld = world.getName(); - lobbyPosition = newLobbyPosition; - sender.sendMessage(messagePrefix + message("LOBBY_SPAWN")); - addToConfig("spawns.lobby.x", lobbyPosition.getX()); - addToConfig("spawns.lobby.y", lobbyPosition.getY()); - addToConfig("spawns.lobby.z", lobbyPosition.getZ()); - addToConfig("spawns.lobby.world", player.getLocation().getWorld().getName()); - saveConfig(); - } - - public String getLabel() { - return "setlobby"; - } - - public String getUsage() { - return ""; - } - - public String getDescription() { - return "Sets hide and seeks lobby location to current position"; - } - -} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java deleted file mode 100644 index 6a9b572..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetSpawnLocation.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.command; - -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; -import net.tylermurphy.hideAndSeek.world.WorldLoader; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import static net.tylermurphy.hideAndSeek.configuration.Config.*; -import static net.tylermurphy.hideAndSeek.configuration.Localization.message; - -public class SetSpawnLocation implements ICommand { - - public void execute(CommandSender sender, String[] args) { - if (Game.status != Status.STANDBY) { - sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); - return; - } - Vector newSpawnPosition = new Vector(); - Player player = (Player) sender; - if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) { - sender.sendMessage(errorPrefix + message("NOT_AT_ZERO")); - return; - } - newSpawnPosition.setX(player.getLocation().getBlockX()); - newSpawnPosition.setY(player.getLocation().getBlockY()); - newSpawnPosition.setZ(player.getLocation().getBlockZ()); - if (worldborderEnabled && newSpawnPosition.distance(worldborderPosition) > 100) { - sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); - return; - } - World world = player.getLocation().getWorld(); - if (world == null) { - throw new RuntimeException("Unable to get world: " + spawnWorld); - } - if (mapSaveEnabled && !world.getName().equals(spawnWorld)) { - Game.worldLoader.unloadMap(); - Game.worldLoader = new WorldLoader(world.getName()); - } - spawnWorld = world.getName(); - spawnPosition = newSpawnPosition; - sender.sendMessage(messagePrefix + message("GAME_SPAWN")); - addToConfig("spawns.game.x", spawnPosition.getX()); - addToConfig("spawns.game.y", spawnPosition.getY()); - addToConfig("spawns.game.z", spawnPosition.getZ()); - addToConfig("spawns.game.world", player.getLocation().getWorld().getName()); - saveConfig(); - } - - public String getLabel() { - return "setspawn"; - } - - public String getUsage() { - return ""; - } - - public String getDescription() { - return "Sets hide and seeks spawn location to current position"; - } - -} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java index ec932d8..0bedcb5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java @@ -20,7 +20,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Game; import org.bukkit.command.CommandSender; import java.io.File; @@ -52,7 +51,7 @@ public class Setup implements ICommand { count++; } if (mapSaveEnabled) { - File destenation = new File(Main.root + File.separator + Game.getGameWorld()); + File destenation = new File(Main.getInstance().getWorldContainer() + File.separator + Main.getInstance().getGame().getGameWorld()); if (!destenation.exists()) { msg = msg + "\n" + message("SETUP_SAVEMAP"); count++; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java index 78f9a64..b1e5895 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java @@ -20,9 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -37,27 +35,27 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Start implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.isNotSetup()) { + if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; } - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if (!Board.contains(sender)) { + if (!Main.getInstance().getBoard().contains(sender)) { sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); return; } - if (Board.size() < minPlayers) { + if (Main.getInstance().getBoard().size() < minPlayers) { sender.sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); return; } String seekerName; if (args.length < 1) { - Optional rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); + Optional rand = Main.getInstance().getBoard().getPlayers().stream().skip(new Random().nextInt(Main.getInstance().getBoard().size())).findFirst(); if (!rand.isPresent()) { - Main.plugin.getLogger().warning("Failed to select random seeker."); + Main.getInstance().getLogger().warning("Failed to select random seeker."); return; } seekerName = rand.get().getName(); @@ -69,12 +67,12 @@ public class Start implements ICommand { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); return; } - Player seeker = Board.getPlayer(temp.getUniqueId()); + Player seeker = Main.getInstance().getBoard().getPlayer(temp.getUniqueId()); if (seeker == null) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); return; } - Game.start(seeker); + Main.getInstance().getGame().start(seeker); } public String getLabel() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index 2a310e8..b5f0c17 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -19,8 +19,8 @@ package net.tylermurphy.hideAndSeek.command; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.command.CommandSender; import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix; @@ -30,13 +30,13 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Stop implements ICommand { public void execute(CommandSender sender, String[] args) { - if (Game.isNotSetup()) { + if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do"); return; } - if (Game.status == Status.STARTING || Game.status == Status.PLAYING) { - Game.broadcastMessage(abortPrefix + message("STOP")); - Game.end(); + if (Main.getInstance().getGame().getStatus() == Status.STARTING || Main.getInstance().getGame().getStatus() == Status.PLAYING) { + Main.getInstance().getGame().broadcastMessage(abortPrefix + message("STOP")); + Main.getInstance().getGame().end(); } else { sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS")); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 916656d..31f814c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -20,7 +20,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.PlayerInfo; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -48,14 +47,14 @@ public class Top implements ICommand { StringBuilder message = new StringBuilder(String.format( "%s------- %sLEADERBOARD %s(Page %s) %s-------\n", ChatColor.WHITE, ChatColor.BOLD, ChatColor.GRAY, page, ChatColor.WHITE)); - List infos = Database.playerInfo.getInfoPage(page); + List infos = Main.getInstance().getDatabase().getGameData().getInfoPage(page); int i = 1 + (page-1)*10; if (infos == null) { sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); return; } for(PlayerInfo info : infos) { - String name = Main.plugin.getServer().getOfflinePlayer(info.uuid).getName(); + String name = Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName(); ChatColor color; switch (i) { case 1: color = ChatColor.YELLOW; break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index 1366f07..0c0f5eb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -20,9 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.PlayerInfo; -import net.tylermurphy.hideAndSeek.util.UUIDFetcher; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -35,12 +33,12 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Wins implements ICommand { public void execute(CommandSender sender, String[] args) { - Main.plugin.getServer().getScheduler().runTaskAsynchronously(Main.plugin, () -> { + Main.getInstance().getServer().getScheduler().runTaskAsynchronously(Main.getInstance(), () -> { UUID uuid; String name; if (args.length == 0) { - Player player = Main.plugin.getServer().getPlayer(sender.getName()); + Player player = Main.getInstance().getServer().getPlayer(sender.getName()); if (player == null) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName())); return; @@ -51,13 +49,13 @@ public class Wins implements ICommand { else { try { name = args[0]; - uuid = UUIDFetcher.getUUID(args[0]); + uuid = Main.getInstance().getServer().getOfflinePlayer(args[0]).getUniqueId(); } catch (Exception e) { sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); return; } } - PlayerInfo info = Database.playerInfo.getInfo(uuid); + PlayerInfo info = Main.getInstance().getDatabase().getGameData().getInfo(uuid); if (info == null) { sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java new file mode 100644 index 0000000..abe6f69 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java @@ -0,0 +1,53 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2021 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.command.location; + +import net.tylermurphy.hideAndSeek.command.ICommand; +import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; +import net.tylermurphy.hideAndSeek.command.location.util.Locations; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; + +public class SetExitLocation implements ICommand { + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof Player)) return; + Player player = (Player) sender; + + LocationUtils.setLocation(player, Locations.EXIT, vector -> { + exitWorld = player.getLocation().getWorld().getName(); + exitPosition = vector; + }); + } + + public String getLabel() { + return "setexit"; + } + + public String getUsage() { + return ""; + } + + public String getDescription() { + return "Sets hide and seeks exit location to current position and world"; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java new file mode 100644 index 0000000..fab7076 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java @@ -0,0 +1,54 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2021 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.command.location; + +import net.tylermurphy.hideAndSeek.command.ICommand; +import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; +import net.tylermurphy.hideAndSeek.command.location.util.Locations; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; + +public class SetLobbyLocation implements ICommand { + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof Player)) return; + Player player = (Player) sender; + + LocationUtils.setLocation(player, Locations.LOBBY, vector -> { + lobbyWorld = player.getLocation().getWorld().getName(); + lobbyPosition = vector; + }); + } + + public String getLabel() { + return "setlobby"; + } + + public String getUsage() { + return ""; + } + + public String getDescription() { + return "Sets hide and seeks lobby location to current position"; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java new file mode 100644 index 0000000..d96252d --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java @@ -0,0 +1,66 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2021 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.command.location; + +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.command.ICommand; +import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; +import net.tylermurphy.hideAndSeek.command.location.util.Locations; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class SetSpawnLocation implements ICommand { + + public void execute(CommandSender sender, String[] args) { + if (!(sender instanceof Player)) return; + Player player = (Player) sender; + + LocationUtils.setLocation(player, Locations.GAME, vector -> { + if (worldborderEnabled && vector.distance(worldborderPosition) > 100) { + sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); + throw new RuntimeException("World border not enabled or not in valid position!"); + } + + if (!player.getLocation().getWorld().getName().equals(spawnWorld)) { + Main.getInstance().getGame().getWorldLoader().unloadMap(); + Main.getInstance().getGame().getWorldLoader().setNewMap(player.getLocation().getWorld().getName()); + } + + spawnWorld = player.getLocation().getWorld().getName(); + spawnPosition = vector; + }); + } + + public String getLabel() { + return "setspawn"; + } + + public String getUsage() { + return ""; + } + + public String getDescription() { + return "Sets hide and seeks spawn location to current position"; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java new file mode 100644 index 0000000..e0fc033 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java @@ -0,0 +1,57 @@ +package net.tylermurphy.hideAndSeek.command.location.util; + +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.game.util.Status; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class LocationUtils { + + /** + * Provides a vector for a player + * @param player the player to create the vector for + * @return the vector + */ + private static @Nullable Vector vector(Player player) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { + player.sendMessage(errorPrefix + message("GAME_INPROGRESS")); + return null; + } + + if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0){ + player.sendMessage(errorPrefix + message("NOT_AT_ZERO")); + return null; + } + + Location loc = player.getLocation(); + return new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + + public static void setLocation(Player player, Locations place, @Nullable Consumer consumer) { + Vector vec = vector(player); + + World world = player.getLocation().getWorld(); + if(world == null) { + throw new RuntimeException("Unable to get world: " + spawnWorld); + } + + consumer.accept(vec); + + player.sendMessage(messagePrefix + message(place.message())); + addToConfig(place.path("x"), vec.getX()); + addToConfig(place.path("y"), vec.getY()); + addToConfig(place.path("z"), vec.getZ()); + addToConfig(place.path("world"), player.getLocation().getWorld().getName()); + saveConfig(); + } + +} \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java new file mode 100644 index 0000000..bde5456 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java @@ -0,0 +1,27 @@ +package net.tylermurphy.hideAndSeek.command.location.util; + +public enum Locations { + + GAME("spawns.game", "GAME_SPAWN"), + LOBBY("spawns.lobby", "LOBBY_SPAWN"), + EXIT("spawns.exit", "EXIT_SPAWN"); + + private final String path, message; + Locations(String path, String message) { + this.path = path; + this.message = message; + } + + public String message() { + return message; + } + + public String path() { + return path; + } + + public String path(String additive) { + return path + "." + additive; + } + +} \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 793e773..afd1729 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -23,8 +23,8 @@ import com.cryptomorin.xseries.XItemStack; import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.util.CountdownDisplay; -import net.tylermurphy.hideAndSeek.util.Version; +import net.tylermurphy.hideAndSeek.game.util.CountdownDisplay; +import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -266,7 +266,7 @@ public class Config { countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay")); } catch (IllegalArgumentException e) { countdownDisplay = CountdownDisplay.CHAT; - Main.plugin.getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!"); + Main.getInstance().getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!"); } blockedInteracts = new ArrayList<>(); List tempInteracts = config.getStringList("blockedInteracts"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 5954d05..3a95fe9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -47,9 +47,9 @@ public class ConfigManager { private ConfigManager(String filename, String defaultFilename) { this.defaultFilename = defaultFilename; - this.file = new File(Main.data, filename); + this.file = new File(Main.getInstance().getDataFolder(), filename); - File folder = Main.data; + File folder = Main.getInstance().getDataFolder(); if (!folder.exists()) { if (!folder.mkdirs()) { throw new RuntimeException("Failed to make directory: " + file.getPath()); @@ -58,7 +58,7 @@ public class ConfigManager { if (!file.exists()) { try{ - InputStream input = Main.plugin.getResource(defaultFilename); + InputStream input = Main.getInstance().getResource(defaultFilename); if (input == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } @@ -181,7 +181,7 @@ public class ConfigManager { public void resetFile(String newDefaultFilename) { this.defaultFilename = newDefaultFilename; - InputStream input = Main.plugin.getResource(defaultFilename); + InputStream input = Main.getInstance().getResource(defaultFilename); if (input == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } @@ -214,7 +214,7 @@ public class ConfigManager { public void saveConfig() { try { - InputStream is = Main.plugin.getResource(defaultFilename); + InputStream is = Main.getInstance().getResource(defaultFilename); if (is == null) { throw new RuntimeException("Could not create input stream for "+defaultFilename); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index c2d7bed..18a31b2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.configuration; import com.cryptomorin.xseries.XItemStack; -import net.tylermurphy.hideAndSeek.util.Version; +import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index 8f8286f..ce06244 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -23,6 +23,7 @@ import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; import org.sqlite.SQLiteConfig; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -34,38 +35,15 @@ import java.util.UUID; public class Database { - private static final File databaseFile = new File(Main.data, "database.db"); + private final File databaseFile = new File(Main.getInstance().getDataFolder(), "database.db"); + private final PlayerInfoTable playerInfo; + private final SQLiteConfig config; - public static PlayerInfoTable playerInfo; - private static SQLiteConfig config; - - protected static Connection connect() { - Connection conn = null; - try { - String url = "jdbc:sqlite:"+databaseFile; - conn = DriverManager.getConnection(url, config.toProperties()); - } catch (SQLException e) { - Main.plugin.getLogger().severe(e.getMessage()); - e.printStackTrace(); - } - return conn; - } - - protected static UUID convertBinaryStream(InputStream stream) { - ByteBuffer buffer = ByteBuffer.allocate(16); - try { - buffer.put(ByteStreams.toByteArray(stream)); - buffer.flip(); - return new UUID(buffer.getLong(), buffer.getLong()); - } catch (IOException ignored) {} - return null; - } - - public static void init() { + public Database(){ try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { - Main.plugin.getLogger().severe(e.getMessage()); + Main.getInstance().getLogger().severe(e.getMessage()); throw new RuntimeException(e.getMessage()); } @@ -73,7 +51,55 @@ public class Database { config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); config.setTempStore(SQLiteConfig.TempStore.MEMORY); - playerInfo = new PlayerInfoTable(); + playerInfo = new PlayerInfoTable(this); + } + + public PlayerInfoTable getGameData(){ + return playerInfo; + } + + protected Connection connect() { + Connection conn = null; + try { + String url = "jdbc:sqlite:"+databaseFile; + conn = DriverManager.getConnection(url, config.toProperties()); + } catch (SQLException e) { + Main.getInstance().getLogger().severe(e.getMessage()); + e.printStackTrace(); + } + return conn; + } + + protected byte[] encodeUUID(UUID uuid) { + try { + byte[] bytes = new byte[16]; + ByteBuffer.wrap(bytes) + .putLong(uuid.getMostSignificantBits()) + .putLong(uuid.getLeastSignificantBits()); + InputStream is = new ByteArrayInputStream(bytes); + byte[] result = new byte[is.available()]; + if (is.read(result) == -1) { + Main.getInstance().getLogger().severe("IO Error: Failed to read bytes from input stream"); + return new byte[0]; + } + return result; + } catch (IOException e) { + Main.getInstance().getLogger().severe("IO Error: " + e.getMessage()); + return new byte[0]; + } + } + + protected UUID decodeUUID(byte[] bytes) { + InputStream is = new ByteArrayInputStream(bytes); + ByteBuffer buffer = ByteBuffer.allocate(16); + try { + buffer.put(ByteStreams.toByteArray(is)); + buffer.flip(); + return new UUID(buffer.getLong(), buffer.getLong()); + } catch (IOException e) { + Main.getInstance().getLogger().severe("IO Error: " + e.getMessage()); + } + return null; } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index 9ad8adf..f20180b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -19,25 +19,20 @@ package net.tylermurphy.hideAndSeek.database; -import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.util.WinType; -import org.jetbrains.annotations.NotNull; +import net.tylermurphy.hideAndSeek.game.util.WinType; import org.jetbrains.annotations.Nullable; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; import java.sql.*; import java.util.*; public class PlayerInfoTable { - private static final Map CACHE = new HashMap<>(); + private final Map CACHE = new HashMap<>(); + private final Database database; - protected PlayerInfoTable() { + protected PlayerInfoTable(Database database) { String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n" + " uuid BINARY(16) PRIMARY KEY,\n" @@ -51,51 +46,22 @@ public class PlayerInfoTable { + " seeker_deaths int NOT NULL\n" + ");"; - try(Connection connection = Database.connect(); Statement statement = connection.createStatement()) { + try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { statement.executeUpdate(sql); } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } + + this.database = database; } - private byte[] encodeUUID(UUID uuid) { - try { - byte[] bytes = new byte[16]; - ByteBuffer.wrap(bytes) - .putLong(uuid.getMostSignificantBits()) - .putLong(uuid.getLeastSignificantBits()); - InputStream is = new ByteArrayInputStream(bytes); - byte[] result = new byte[is.available()]; - if (is.read(result) == -1) { - Main.plugin.getLogger().severe("IO Error: Failed to read bytes from input stream"); - return new byte[0]; - } - return result; - } catch (IOException e) { - Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); - return new byte[0]; - } - } - - private UUID decodeUUID(byte[] bytes) { - InputStream is = new ByteArrayInputStream(bytes); - ByteBuffer buffer = ByteBuffer.allocate(16); - try { - buffer.put(ByteStreams.toByteArray(is)); - buffer.flip(); - return new UUID(buffer.getLong(), buffer.getLong()); - } catch (IOException e) { - Main.plugin.getLogger().severe("IO Error: " + e.getMessage()); - } - return null; - } - - @NotNull + @Nullable public PlayerInfo getInfo(UUID uuid) { + if(CACHE.containsKey(uuid)) return CACHE.get(uuid); String sql = "SELECT * FROM hs_data WHERE uuid = ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { - statement.setBytes(1, encodeUUID(uuid)); + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, database.encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); if (rs.next()) { PlayerInfo info = new PlayerInfo( @@ -116,20 +82,20 @@ public class PlayerInfoTable { } rs.close(); } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } - return new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); + return null; } @Nullable public PlayerInfo getInfoRanking(String order, int place) { String sql = "SELECT * FROM hs_data ORDER BY "+order+" DESC LIMIT 1 OFFSET ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, place-1); ResultSet rs = statement.executeQuery(); if (rs.next()) { - UUID uuid = decodeUUID(rs.getBytes("uuid")); + UUID uuid = database.decodeUUID(rs.getBytes("uuid")); PlayerInfo info = new PlayerInfo( uuid, rs.getInt("hider_wins"), @@ -148,7 +114,7 @@ public class PlayerInfoTable { } rs.close(); } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } return null; @@ -157,13 +123,13 @@ public class PlayerInfoTable { @Nullable public List getInfoPage(int page) { String sql = "SELECT * FROM hs_data ORDER BY (hider_wins + seeker_wins) DESC LIMIT 10 OFFSET ?;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, (page-1)*10); ResultSet rs = statement.executeQuery(); List infoList = new ArrayList<>(); while(rs.next()) { PlayerInfo info = new PlayerInfo( - decodeUUID(rs.getBytes("uuid")), + database.decodeUUID(rs.getBytes("uuid")), rs.getInt("hider_wins"), rs.getInt("seeker_wins"), rs.getInt("hider_games"), @@ -179,7 +145,7 @@ public class PlayerInfoTable { connection.close(); return infoList; } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } return null; @@ -188,37 +154,40 @@ public class PlayerInfoTable { @Nullable public Integer getRanking(String order, UUID uuid) { String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND "+order+" > 0;"; - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { - statement.setBytes(1, encodeUUID(uuid)); + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, database.encodeUUID(uuid)); ResultSet rs = statement.executeQuery(); if (rs.next()) { return rs.getInt("total"); } rs.close(); } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } return null; } - public void addWins(List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type) { + public void addWins(Board board, List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type) { for(UUID uuid : uuids) { String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; PlayerInfo info = getInfo(uuid); - try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { - statement.setBytes(1, encodeUUID(uuid)); + if(info == null){ + info = new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); + } + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, database.encodeUUID(uuid)); statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); - statement.setInt(4, info.hider_games + (Board.isHider(uuid) || (Board.isSeeker(uuid) && !Board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); - statement.setInt(5, info.seeker_games + (Board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); + statement.setInt(4, info.hider_games + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); + statement.setInt(5, info.seeker_games + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); statement.setInt(6, info.hider_kills + hider_kills.getOrDefault(uuid.toString(), 0)); statement.setInt(7, info.seeker_kills + seeker_kills.getOrDefault(uuid.toString(), 0)); statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0)); statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0)); statement.execute(); } catch (SQLException e) { - Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); return; } finally { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 75d2a7d..41950a1 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -19,8 +19,12 @@ package net.tylermurphy.hideAndSeek.game; -import net.tylermurphy.hideAndSeek.util.Status; -import net.tylermurphy.hideAndSeek.util.Version; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.events.Border; +import net.tylermurphy.hideAndSeek.game.events.Glow; +import net.tylermurphy.hideAndSeek.game.events.Taunt; +import net.tylermurphy.hideAndSeek.game.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; @@ -35,110 +39,110 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Board { - private static final List Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); - private static final Map playerList = new HashMap<>(); - private static final Map customBoards = new HashMap<>(); - private static final Map hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>(); + private final List Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); + private final Map playerList = new HashMap<>(); + private final Map customBoards = new HashMap<>(); + private final Map hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>(); - public static boolean contains(Player player) { + public boolean contains(Player player) { return playerList.containsKey(player.getUniqueId().toString()); } - public static boolean contains(CommandSender sender) { + public boolean contains(CommandSender sender) { return contains((Player) sender); } - public static boolean isHider(Player player) { + public boolean isHider(Player player) { return Hider.contains(player.getUniqueId().toString()); } - public static boolean isHider(UUID uuid) { + public boolean isHider(UUID uuid) { return Hider.contains(uuid.toString()); } - public static boolean isSeeker(Player player) { + public boolean isSeeker(Player player) { return Seeker.contains(player.getUniqueId().toString()); } - public static boolean isSeeker(UUID uuid) { + public boolean isSeeker(UUID uuid) { return Seeker.contains(uuid.toString()); } - public static boolean isSpectator(Player player) { + public boolean isSpectator(Player player) { return Spectator.contains(player.getUniqueId().toString()); } - public static int sizeHider() { + public int sizeHider() { return Hider.size(); } - public static int sizeSeeker() { + public int sizeSeeker() { return Seeker.size(); } - public static int size() { + public int size() { return playerList.values().size(); } - public static List getHiders() { + public List getHiders() { return Hider.stream().map(playerList::get).collect(Collectors.toList()); } - public static List getSeekers() { + public List getSeekers() { return Seeker.stream().map(playerList::get).collect(Collectors.toList()); } - public static Player getFirstSeeker() { + public Player getFirstSeeker() { return playerList.get(Seeker.get(0)); } - public static List getSpectators() { + public List getSpectators() { return Spectator.stream().map(playerList::get).collect(Collectors.toList()); } - public static List getPlayers() { + public List getPlayers() { return new ArrayList<>(playerList.values()); } - public static Player getPlayer(UUID uuid) { + public Player getPlayer(UUID uuid) { return playerList.get(uuid.toString()); } - public static void addHider(Player player) { + public void addHider(Player player) { Hider.add(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString()); playerList.put(player.getUniqueId().toString(), player); } - public static void addSeeker(Player player) { + public void addSeeker(Player player) { Hider.remove(player.getUniqueId().toString()); Seeker.add(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString()); playerList.put(player.getUniqueId().toString(), player); } - public static void addSpectator(Player player) { + public void addSpectator(Player player) { Hider.remove(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString()); Spectator.add(player.getUniqueId().toString()); playerList.put(player.getUniqueId().toString(), player); } - public static void remove(Player player) { + public void remove(Player player) { Hider.remove(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString()); playerList.remove(player.getUniqueId().toString()); } - public static boolean onSameTeam(Player player1, Player player2) { + public boolean onSameTeam(Player player1, Player player2) { if (Hider.contains(player1.getUniqueId().toString()) && Hider.contains(player2.getUniqueId().toString())) return true; else if (Seeker.contains(player1.getUniqueId().toString()) && Seeker.contains(player2.getUniqueId().toString())) return true; else return Spectator.contains(player1.getUniqueId().toString()) && Spectator.contains(player2.getUniqueId().toString()); } - public static void reload() { + public void reload() { Hider.clear(); Seeker.clear(); Spectator.clear(); @@ -148,7 +152,7 @@ public class Board { seeker_deaths.clear(); } - public static void addKill(UUID uuid) { + public void addKill(UUID uuid) { if (Hider.contains(uuid.toString())) { if (hider_kills.containsKey(uuid.toString())) { hider_kills.put(uuid.toString(), hider_kills.get(uuid.toString())+1); @@ -164,7 +168,7 @@ public class Board { } } - public static void addDeath(UUID uuid) { + public void addDeath(UUID uuid) { if (Hider.contains(uuid.toString())) { if (hider_deaths.containsKey(uuid.toString())) { hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1); @@ -180,24 +184,24 @@ public class Board { } } - public static Map getHiderKills() { + public Map getHiderKills() { return new HashMap<>(hider_kills); } - public static Map getSeekerKills() { + public Map getSeekerKills() { return new HashMap<>(seeker_kills); } - public static Map getHiderDeaths() { + public Map getHiderDeaths() { return new HashMap<>(hider_deaths); } - public static Map getSeekerDeaths() { + public Map getSeekerDeaths() { return new HashMap<>(seeker_deaths); } - public static void createLobbyBoard(Player player) { + public void createLobbyBoard(Player player) { createLobbyBoard(player, true); } - private static void createLobbyBoard(Player player, boolean recreate) { + private void createLobbyBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); if (recreate) { board = new CustomBoard(player, LOBBY_TITLE); @@ -210,10 +214,10 @@ public class Board { } else if (line.contains("{COUNTDOWN}")) { if (!lobbyCountdownEnabled) { board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_ADMINSTART)); - } else if (Game.countdownTime == -1) { + } else if (Main.getInstance().getGame().getLobbyTime() == -1) { board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_WAITING)); } else { - board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_COUNTING.replace("{AMOUNT}",Game.countdownTime+""))); + board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_COUNTING.replace("{AMOUNT}",Main.getInstance().getGame().getLobbyTime()+""))); } } else if (line.contains("{COUNT}")) { board.setLine(String.valueOf(i), line.replace("{COUNT}", getPlayers().size()+"")); @@ -230,51 +234,59 @@ public class Board { customBoards.put(player.getUniqueId().toString(), board); } - public static void createGameBoard(Player player) { + public void createGameBoard(Player player) { createGameBoard(player, true); } - private static void createGameBoard(Player player, boolean recreate) { + private void createGameBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); if (recreate) { board = new CustomBoard(player, GAME_TITLE); board.updateTeams(); } + + int timeLeft = Main.getInstance().getGame().getTimeLeft(); + Status status = Main.getInstance().getGame().getStatus(); + + Taunt taunt = Main.getInstance().getGame().getTaunt(); + Border worldBorder = Main.getInstance().getGame().getBorder(); + Glow glow = Main.getInstance().getGame().getGlow(); + int i = 0; for(String line : GAME_CONTENTS) { if (line.equalsIgnoreCase("")) { board.addBlank(); } else { if (line.contains("{TIME}")) { - String value = Game.timeLeft/60 + "m" + Game.timeLeft%60 + "s"; + String value = timeLeft/60 + "m" + timeLeft%60 + "s"; board.setLine(String.valueOf(i), line.replace("{TIME}", value)); } else if (line.contains("{TEAM}")) { String value = getTeam(player); board.setLine(String.valueOf(i), line.replace("{TEAM}", value)); } else if (line.contains("{BORDER}")) { if (!worldborderEnabled) continue; - if (Game.worldBorder == null || Game.status == Status.STARTING) { + if (worldBorder == null || status == Status.STARTING) { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replace("{AMOUNT}", "0"))); - } else if (!Game.worldBorder.isRunning()) { - board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()/60+"").replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()%60+""))); + } else if (!worldBorder.isRunning()) { + board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replaceFirst("\\{AMOUNT}", worldBorder.getDelay()/60+"").replaceFirst("\\{AMOUNT}", worldBorder.getDelay()%60+""))); } else { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_DECREASING)); } } else if (line.contains("{TAUNT}")) { if (!tauntEnabled) continue; - if (Game.taunt == null || Game.status == Status.STARTING) { + if (taunt == null || status == Status.STARTING) { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replace("{AMOUNT}", "0"))); } else if (!tauntLast && Hider.size() == 1) { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_EXPIRED)); - } else if (!Game.taunt.isRunning()) { - board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() / 60 + "").replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() % 60 + ""))); + } else if (!taunt.isRunning()) { + board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replaceFirst("\\{AMOUNT}", taunt.getDelay() / 60 + "").replaceFirst("\\{AMOUNT}", taunt.getDelay() % 60 + ""))); } else { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_ACTIVE)); } } else if (line.contains("{GLOW}")) { if (!glowEnabled) return; - if (Game.glow == null || Game.status == Status.STARTING || !Game.glow.isRunning()) { + if (glow == null || status == Status.STARTING || !glow.isRunning()) { board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_INACTIVE)); } else { board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_ACTIVE)); @@ -293,50 +305,50 @@ public class Board { customBoards.put(player.getUniqueId().toString(), board); } - public static void removeBoard(Player player) { + public void removeBoard(Player player) { ScoreboardManager manager = Bukkit.getScoreboardManager(); assert manager != null; player.setScoreboard(manager.getMainScoreboard()); customBoards.remove(player.getUniqueId().toString()); } - public static void reloadLobbyBoards() { + public void reloadLobbyBoards() { for(Player player : playerList.values()) createLobbyBoard(player, false); } - public static void reloadGameBoards() { + public void reloadGameBoards() { for(Player player : playerList.values()) createGameBoard(player, false); } - public static void reloadBoardTeams() { + public void reloadBoardTeams() { for(CustomBoard board : customBoards.values()) board.updateTeams(); } - private static String getSeekerPercent() { + private String getSeekerPercent() { if (playerList.values().size() < 2) return " --"; else return " "+(int)(100*(1.0/playerList.size())); } - private static String getHiderPercent() { + private String getHiderPercent() { if (playerList.size() < 2) return " --"; else return " "+(int)(100-100*(1.0/playerList.size())); } - private static String getTeam(Player player) { + private String getTeam(Player player) { if (isHider(player)) return message("HIDER_TEAM_NAME").toString(); else if (isSeeker(player)) return message("SEEKER_TEAM_NAME").toString(); else if (isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString(); else return ChatColor.WHITE + "UNKNOWN"; } - public static void cleanup() { + public void cleanup() { playerList.clear(); Hider.clear(); Seeker.clear(); @@ -380,13 +392,13 @@ class CustomBoard { assert hiderTeam != null; for(String entry : hiderTeam.getEntries()) hiderTeam.removeEntry(entry); - for(Player player : Board.getHiders()) + for(Player player : Main.getInstance().getBoard().getHiders()) hiderTeam.addEntry(player.getName()); Team seekerTeam = board.getTeam("Seeker"); assert seekerTeam != null; for(String entry : seekerTeam.getEntries()) seekerTeam.removeEntry(entry); - for(Player player : Board.getSeekers()) + for(Player player : Main.getInstance().getBoard().getSeekers()) seekerTeam.addEntry(player.getName()); if (Version.atLeast("1.9")) { if (nametagsVisible) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 83b304d..e33e503 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -23,24 +23,16 @@ import com.cryptomorin.xseries.messages.ActionBar; import com.cryptomorin.xseries.messages.Titles; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; -import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.configuration.Items; -import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.game.events.Border; +import net.tylermurphy.hideAndSeek.game.events.Glow; +import net.tylermurphy.hideAndSeek.game.events.Taunt; import net.tylermurphy.hideAndSeek.game.listener.RespawnHandler; -import net.tylermurphy.hideAndSeek.util.*; +import net.tylermurphy.hideAndSeek.game.util.*; import net.tylermurphy.hideAndSeek.world.WorldLoader; import org.bukkit.*; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Firework; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; import java.io.File; import java.util.*; @@ -48,303 +40,239 @@ import java.util.stream.Collectors; import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Localization.message; -import static net.tylermurphy.hideAndSeek.game.Game.broadcastMessage; public class Game { - public static Taunt taunt; - public static Glow glow; - public static Border worldBorder; - public static WorldLoader worldLoader; - public static int tick = 0; - public static int countdownTime = -1; - public static int gameId = 0; - public static int timeLeft = 0; - public static Status status = Status.STANDBY; + private final Taunt taunt; + private final Glow glow; + private final Border worldBorder; + private final WorldLoader worldLoader; - private static boolean hiderLeave = false; + private final Board board; - static { - worldLoader = new WorldLoader(spawnWorld); + private Status status; + + private int gameTick; + private int lobbyTimer; + private int startingTimer; + private int gameTimer; + private boolean hiderLeft; + + public Game(Board board){ + this.taunt = new Taunt(); + this.glow = new Glow(); + this.worldBorder = new Border(); + this.worldLoader = new WorldLoader(spawnWorld); + + this.status = Status.STANDBY; + + this.board = board; + + this.gameTick = 0; + this.lobbyTimer = -1; + this.startingTimer = -1; + this.gameTimer = 0; + this.hiderLeft = false; } - public static void start() { - Optional rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); - if (!rand.isPresent()) { - Main.plugin.getLogger().warning("Failed to select random seeker."); - return; - } - String seekerName = rand.get().getName(); - Player temp = Bukkit.getPlayer(seekerName); - if (temp == null) { - Main.plugin.getLogger().warning("Failed to select random seeker."); - return; - } - Player seeker = Board.getPlayer(temp.getUniqueId()); - if (seeker == null) { - Main.plugin.getLogger().warning("Failed to select random seeker."); - return; - } - start(seeker); + public Status getStatus(){ + return status; } - public static void start(Player seeker) { - if (status == Status.STARTING || status == Status.PLAYING) return; - if (mapSaveEnabled && worldLoader.getWorld() != null) { - worldLoader.rollback(); - } else if (mapSaveEnabled) { - worldLoader.loadMap(); + public int getTimeLeft(){ + return gameTimer; + } + + public int getLobbyTime(){ + return lobbyTimer; + } + + public Glow getGlow(){ + return glow; + } + + public Border getBorder(){ + return worldBorder; + } + + public Taunt getTaunt(){ + return taunt; + } + + public WorldLoader getWorldLoader(){ + return worldLoader; + } + + public void start() { + try { + Optional rand = board.getPlayers().stream().skip(new Random().nextInt(board.size())).findFirst(); + String seekerName = rand.get().getName(); + Player temp = Bukkit.getPlayer(seekerName); + Player seeker = board.getPlayer(temp.getUniqueId()); + start(seeker); + } catch (Exception e){ + Main.getInstance().getLogger().warning("Failed to select random seeker."); } - Board.reload(); - for(Player temp : Board.getPlayers()) { - if (temp.getName().equals(seeker.getName())) - continue; - Board.addHider(temp); - } - Board.addSeeker(seeker); - currentWorldborderSize = worldborderSize; - for(Player player : Board.getPlayers()) { - player.getInventory().clear(); - player.setGameMode(GameMode.ADVENTURE); - player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - } - for(Player player : Board.getSeekers()) { - player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS,1000000,127,false,false)); - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW,1000000,127,false,false)); - player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,1000000,128,false,false)); - Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("SEEKER_TEAM_NAME"), ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString()); - } - for(Player player : Board.getHiders()) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false)); - Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString()); - } - if (tauntEnabled) - taunt = new Taunt(); - if (glowEnabled) - glow = new Glow(); - worldBorder = new Border(); - worldBorder.resetWorldborder(getGameWorld()); - if (gameLength > 0) - timeLeft = gameLength; - for(Player player : Board.getPlayers()) - Board.createGameBoard(player); - Board.reloadGameBoards(); + } + + public void start(Player seeker) { + if (mapSaveEnabled) worldLoader.rollback(); + board.reload(); + board.addSeeker(seeker); + PlayerUtil.loadSeeker(seeker, getGameWorld()); + board.getPlayers().forEach(player -> { + board.createGameBoard(player); + if(board.isSeeker(player)) return; + board.addHider(player); + PlayerUtil.loadHider(player, getGameWorld()); + }); + worldBorder.resetWorldBorder(getGameWorld()); + if (gameLength > 0) gameTimer = gameLength; status = Status.STARTING; - int temp = gameId; - if (countdownDisplay != CountdownDisplay.TITLE) { - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30), gameId, 0); - } - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10); - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20); - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25); - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27); - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28); - sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29); - Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> { - if (temp != gameId) return; - sendHideCountdownMessage(messagePrefix + message("START"), gameId, 0); - for(Player player : Board.getPlayers()) resetPlayer(player); - status = Status.PLAYING; - }, 20 * 30); + startingTimer = 30; } - public static void stop(WinType type) { - if (status == Status.STANDBY || status == Status.ENDING) return; + private void stop(WinType type) { status = Status.ENDING; - for(Player player : Board.getPlayers()) { - player.getInventory().clear(); - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); - if (Version.atLeast("1.9")) { - for(Player temp : Board.getPlayers()) { - Packet.setGlow(player, temp, false); - } - } - } - List players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); + List players = board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList()); if (type == WinType.HIDER_WIN) { - List winners = Board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); - Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); + List winners = board.getHiders().stream().map(Entity::getUniqueId).collect(Collectors.toList()); + Main.getInstance().getDatabase().getGameData().addWins(board, players, winners, board.getHiderKills(), board.getHiderDeaths(), board.getSeekerKills(), board.getSeekerDeaths(), type); } else if (type == WinType.SEEKER_WIN) { List winners = new ArrayList<>(); - winners.add(Board.getFirstSeeker().getUniqueId()); - Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); + winners.add(board.getFirstSeeker().getUniqueId()); + Main.getInstance().getDatabase().getGameData().addWins(board, players, winners, board.getHiderKills(), board.getHiderDeaths(), board.getSeekerKills(), board.getSeekerDeaths(), type); } - Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::end, 5*20); + Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), this::end, 5*20); } - public static void end() { - if (status == Status.STANDBY) return; - tick = 0; - countdownTime = -1; - status = Status.STANDBY; - gameId++; - timeLeft = 0; - worldBorder.resetWorldborder(getGameWorld()); - for(Player player : Board.getPlayers()) { - for(Player player2 : Board.getPlayers()) { - player.showPlayer(player2); - } - player.setAllowFlight(false); - player.setFlying(false); - if (Version.atLeast("1.9")) { - for(Player temp : Board.getPlayers()) { - Packet.setGlow(player, temp, false); - } - } - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); + public void end() { + board.getPlayers().forEach(PlayerUtil::unloadPlayer); + worldBorder.resetWorldBorder(getGameWorld()); + board.getPlayers().forEach(player -> { if (leaveOnEnd) { - Board.removeBoard(player); - Board.remove(player); - player.getInventory().clear(); + board.removeBoard(player); + board.remove(player); handleBungeeLeave(player); } else { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); - Board.createLobbyBoard(player); - player.setGameMode(GameMode.ADVENTURE); - Board.addHider(player); - player.getInventory().clear(); - if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp())) - player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); - if (lobbyLeaveItem != null) - player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100)); + board.createLobbyBoard(player); + board.addHider(player); + PlayerUtil.joinPlayer(player); } - } + }); RespawnHandler.temp_loc.clear(); if (mapSaveEnabled) worldLoader.unloadMap(); - Board.reloadLobbyBoards(); + board.reloadLobbyBoards(); + status = Status.ENDED; } - public static void join(Player player) { - if (Game.status == Status.STANDBY || Game.status == Status.ENDING) { - player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); - player.getInventory().clear(); - if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) - player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); - if (lobbyLeaveItem != null) - player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); - Board.addHider(player); + public void join(Player player) { + if (status != Status.STARTING && status != Status.PLAYING) { + PlayerUtil.joinPlayer(player); + board.addHider(player); + board.createLobbyBoard(player); + board.reloadLobbyBoards(); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); - else Game.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.setGameMode(GameMode.ADVENTURE); - Board.createLobbyBoard(player); - Board.reloadLobbyBoards(); + else broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); } else { - Board.addSpectator(player); + PlayerUtil.loadSpectator(player, getGameWorld()); + board.addSpectator(player); + board.createGameBoard(player); player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); - player.setGameMode(GameMode.ADVENTURE); - for(Player player2 : Board.getPlayers()) { - player2.hidePlayer(player); - } - Board.createGameBoard(player); - player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); - player.setAllowFlight(true); - player.setFlying(true); - player.setFallDistance(0.0F); - Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); - } - - player.setFoodLevel(20); - if (Version.atLeast("1.9")) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute != null) player.setHealth(attribute.getValue()); - } else { - player.setHealth(player.getMaxHealth()); } } - public static void leave(Player player) { - player.setFlying(false); - player.setAllowFlight(false); - player.setFallDistance(0.0F); - for(Player player2 : Board.getPlayers()) { - player2.showPlayer(player); - player.showPlayer(player2); - } + public void leave(Player player) { + PlayerUtil.unloadPlayer(player); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); - else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); - if (Board.isHider(player) && status != Status.ENDING && status != Status.STANDBY) { - hiderLeave = true; + else broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); + if (board.isHider(player) && status != Status.ENDING && status != Status.STANDBY) { + hiderLeft = true; } - Board.removeBoard(player); - Board.remove(player); - player.getInventory().clear(); - if (Game.status == Status.STANDBY) { - Board.reloadLobbyBoards(); + board.removeBoard(player); + board.remove(player); + if (status == Status.STANDBY) { + board.reloadLobbyBoards(); } else { - Board.reloadGameBoards(); - Board.reloadBoardTeams(); - } - for(PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); + board.reloadGameBoards(); + board.reloadBoardTeams(); } handleBungeeLeave(player); } - private static void handleBungeeLeave(Player player) { + private void handleBungeeLeave(Player player) { if (bungeeLeave) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); out.writeUTF("Connect"); out.writeUTF(leaveServer); - player.sendPluginMessage(Main.plugin, "BungeeCord", out.toByteArray()); + player.sendPluginMessage(Main.getInstance(), "BungeeCord", out.toByteArray()); } else { player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); } } - public static void onTick() { + public void onTick() { if (isNotSetup()) return; if (status == Status.STANDBY) whileWaiting(); else if (status == Status.STARTING) whileStarting(); else if (status == Status.PLAYING) whilePlaying(); - tick++; + gameTick++; } - private static void whileWaiting() { + private void whileWaiting() { if (!lobbyCountdownEnabled) return; - if (lobbyMin <= Board.size()) { - if (countdownTime == -1) - countdownTime = countdown; - if (Board.size() >= changeCountdown) - countdownTime = Math.min(countdownTime, 10); - if (tick % 20 == 0) { - countdownTime--; - Board.reloadLobbyBoards(); + if (lobbyMin <= board.size()) { + if (gameTimer == -1) + lobbyTimer = countdown; + if (board.size() >= changeCountdown) + lobbyTimer = Math.min(lobbyTimer, 10); + if (gameTick % 20 == 0) { + lobbyTimer--; + board.reloadLobbyBoards(); } - if (countdownTime == 0) { + if (lobbyTimer == 0) { start(); } } else { - countdownTime = -1; + lobbyTimer = -1; } } - private static void whileStarting() { - for(Player spectator : Board.getSpectators()) { - spectator.setFlying(spectator.getAllowFlight()); + private void whileStarting() { + + if(gameTick % 20 == 0) { + if (startingTimer % 5 == 0 || startingTimer < 4) { + String message; + if (startingTimer == 0) { + message = message("START").toString(); + status = Status.PLAYING; + board.getPlayers().forEach(player -> PlayerUtil.resetPlayer(player, board)); + } else { + message = message("START_COUNTDOWN").addAmount(startingTimer).toString(); + } + board.getPlayers().forEach(player -> { + if (countdownDisplay == CountdownDisplay.CHAT) { + player.sendMessage(messagePrefix + message); + } else if (countdownDisplay == CountdownDisplay.ACTIONBAR) { + ActionBar.clearActionBar(player); + ActionBar.sendActionBar(player, messagePrefix + message); + } else if (countdownDisplay == CountdownDisplay.TITLE) { + Titles.clearTitle(player); + Titles.sendTitle(player, 10, 40, 10, " ", message); + } + }); + } + startingTimer--; } + checkWinConditions(); } - private static void whilePlaying() { - for(Player hider : Board.getHiders()) { + private void whilePlaying() { + for(Player hider : board.getHiders()) { int distance = 100, temp = 100; - for(Player seeker : Board.getSeekers()) { + for(Player seeker : board.getSeekers()) { try { temp = (int) hider.getLocation().distance(seeker.getLocation()); } catch (Exception e) { @@ -354,7 +282,7 @@ public class Game { distance = temp; } } - if (seekerPing) switch(tick%10) { + if (seekerPing) switch(gameTick %10) { case 0: if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch); if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); @@ -371,13 +299,10 @@ public class Game { break; } } - for(Player spectator : Board.getSpectators()) { - spectator.setFlying(spectator.getAllowFlight()); - } - if (tick%20 == 0) { + if (gameTick %20 == 0) { if (gameLength > 0) { - Board.reloadGameBoards(); - timeLeft--; + board.reloadGameBoards(); + gameTimer--; } if (worldborderEnabled) worldBorder.update(); if (tauntEnabled) taunt.update(); @@ -386,68 +311,31 @@ public class Game { checkWinConditions(); } - public static void resetWorldBorder(String worldName) { - worldBorder = new Border(); - worldBorder.resetWorldborder(worldName); - } - - public static void broadcastMessage(String message) { - for(Player player : Board.getPlayers()) { + public void broadcastMessage(String message) { + for(Player player : board.getPlayers()) { player.sendMessage(message); } } - public static boolean isNotSetup() { + public boolean isNotSetup() { if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; if (lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true; if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; if (mapSaveEnabled) { - File destination = new File(Main.root + File.separator + getGameWorld()); + File destination = new File(Main.getInstance().getWorldContainer() + File.separator + getGameWorld()); if (!destination.exists()) return true; } return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; } - public static String getGameWorld() { + public String getGameWorld() { if (mapSaveEnabled) return "hideandseek_"+spawnWorld; else return spawnWorld; } - public static void resetPlayer(Player player) { - player.getInventory().clear(); - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - if (Board.isSeeker(player)) { - if (pvpEnabled) - for(ItemStack item : Items.SEEKER_ITEMS) - player.getInventory().addItem(item); - for(PotionEffect effect : Items.SEEKER_EFFECTS) - player.addPotionEffect(effect); - } else if (Board.isHider(player)) { - if (pvpEnabled) - for(ItemStack item : Items.HIDER_ITEMS) - player.getInventory().addItem(item); - for(PotionEffect effect : Items.HIDER_EFFECTS) - player.addPotionEffect(effect); - if (glowEnabled) { - player.getInventory().addItem(glowPowerupItem); - } - } - } - - public static void removeItems(Player player) { - for(ItemStack si : Items.SEEKER_ITEMS) - for(ItemStack i : player.getInventory().getContents()) - if (si.isSimilar(i)) player.getInventory().remove(i); - for(ItemStack hi : Items.HIDER_ITEMS) - for(ItemStack i : player.getInventory().getContents()) - if (hi.isSimilar(i)) player.getInventory().remove(i); - } - - private static void checkWinConditions() { - if (Board.sizeHider() < 1) { - if (hiderLeave) { + private void checkWinConditions() { + if (board.sizeHider() < 1) { + if (hiderLeft) { if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); stop(WinType.NONE); @@ -456,179 +344,16 @@ public class Game { else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); stop(WinType.SEEKER_WIN); } - } else if (Board.sizeSeeker() < 1) { + } else if (board.sizeSeeker() < 1) { if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); stop(WinType.NONE); - } else if (timeLeft < 1) { + } else if (gameTimer < 1) { if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); stop(WinType.HIDER_WIN); } - hiderLeave = false; - } - - private static void sendHideCountdownMessage(String message, int gameId, int delay) { - Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> { - if (gameId == Game.gameId) { - for(Player player : Board.getPlayers()) { - if (countdownDisplay == CountdownDisplay.CHAT) { - player.sendMessage(message); - } else if (countdownDisplay == CountdownDisplay.ACTIONBAR) { - ActionBar.clearActionBar(player); - ActionBar.sendActionBar(player,message); - } else if (countdownDisplay == CountdownDisplay.TITLE) { - Titles.clearTitle(player); - Titles.sendTitle(player, 10, 40, 10, " ", message); - } - } - } - }, delay); - } - -} - -class Taunt { - - private UUID tauntPlayer; - private int delay; - private boolean running; - - public Taunt() { - this.delay = tauntDelay; - } - - protected void update() { - if (delay == 0) { - if (running) launchTaunt(); - else if (tauntLast || Board.sizeHider() > 1) executeTaunt(); - } else { - delay--; - delay = Math.max(delay, 0); - } - } - - private void executeTaunt() { - Optional rand = Board.getHiders().stream().skip(new Random().nextInt(Board.size())).findFirst(); - if (!rand.isPresent()) { - Main.plugin.getLogger().warning("Failed to select random seeker."); - return; - } - Player taunted = rand.get(); - taunted.sendMessage(message("TAUNTED").toString()); - broadcastMessage(tauntPrefix + message("TAUNT")); - tauntPlayer = taunted.getUniqueId(); - running = true; - delay = 30; - } - - private void launchTaunt() { - Player taunted = Board.getPlayer(tauntPlayer); - if (taunted != null) { - if (!Board.isHider(taunted)) { - Main.plugin.getLogger().info("Taunted played died and is now seeker. Skipping taunt."); - tauntPlayer = null; - running = false; - delay = tauntDelay; - return; - } - World world = taunted.getLocation().getWorld(); - if (world == null) { - Main.plugin.getLogger().severe("Game world is null while trying to launch taunt."); - tauntPlayer = null; - running = false; - delay = tauntDelay; - return; - } - Firework fw = (Firework) world.spawnEntity(taunted.getLocation(), EntityType.FIREWORK); - FireworkMeta fwm = fw.getFireworkMeta(); - fwm.setPower(4); - fwm.addEffect(FireworkEffect.builder() - .withColor(Color.BLUE) - .withColor(Color.RED) - .withColor(Color.YELLOW) - .with(FireworkEffect.Type.STAR) - .with(FireworkEffect.Type.BALL) - .with(FireworkEffect.Type.BALL_LARGE) - .flicker(true) - .withTrail() - .build()); - fw.setFireworkMeta(fwm); - broadcastMessage(tauntPrefix + message("TAUNT_ACTIVATE")); - } - tauntPlayer = null; - running = false; - delay = tauntDelay; - } - - public int getDelay() { - return delay; - } - - public boolean isRunning() { - return running; - } - -} - -class Border { - - private int delay; - private boolean running; - - public Border() { - delay = 60 * worldborderDelay; - } - - void update() { - if (delay == 30 && !running) { - broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN")); - } else if (delay == 0) { - if (running) { - delay = 60 * worldborderDelay; - running = false; - } - else decreaceWorldborder(); - } - delay--; - } - - private void decreaceWorldborder() { - if (currentWorldborderSize == 100) return; - int change = worldborderChange; - if (currentWorldborderSize-worldborderChange < 100) { - change = currentWorldborderSize-100; - } - running = true; - broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change)); - currentWorldborderSize -= worldborderChange; - World world = Bukkit.getWorld(Game.getGameWorld()); - assert world != null; - org.bukkit.WorldBorder border = world.getWorldBorder(); - border.setSize(border.getSize()-change,30); - delay = 30; - } - - public void resetWorldborder(String worldName) { - World world = Bukkit.getWorld(worldName); - assert world != null; - org.bukkit.WorldBorder border = world.getWorldBorder(); - if (worldborderEnabled) { - border.setSize(worldborderSize); - border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ()); - currentWorldborderSize = worldborderSize; - } else { - border.setSize(30000000); - border.setCenter(0, 0); - } - } - - public int getDelay() { - return delay; - } - - public boolean isRunning() { - return running; + hiderLeft = false; } } \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java new file mode 100644 index 0000000..aa6beca --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java @@ -0,0 +1,71 @@ +package net.tylermurphy.hideAndSeek.game.events; + +import net.tylermurphy.hideAndSeek.Main; +import org.bukkit.Bukkit; +import org.bukkit.World; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class Border { + + private int delay; + private boolean running; + + public Border() { + delay = 60 * worldborderDelay; + } + + public void update() { + if (delay == 30 && !running) { + Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN")); + } else if (delay == 0) { + if (running) { + delay = 60 * worldborderDelay; + running = false; + } + else decreaceWorldborder(); + } + delay--; + } + + private void decreaceWorldborder() { + if (currentWorldborderSize == 100) return; + int change = worldborderChange; + if (currentWorldborderSize-worldborderChange < 100) { + change = currentWorldborderSize-100; + } + running = true; + Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change)); + currentWorldborderSize -= worldborderChange; + World world = Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()); + assert world != null; + org.bukkit.WorldBorder border = world.getWorldBorder(); + border.setSize(border.getSize()-change,30); + delay = 30; + } + + public void resetWorldBorder(String worldName) { + World world = Bukkit.getWorld(worldName); + assert world != null; + org.bukkit.WorldBorder border = world.getWorldBorder(); + if (worldborderEnabled) { + border.setSize(worldborderSize); + border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ()); + currentWorldborderSize = worldborderSize; + } else { + border.setSize(30000000); + border.setCenter(0, 0); + } + delay = 60 * worldborderDelay; + } + + public int getDelay() { + return delay; + } + + public boolean isRunning() { + return running; + } + +} \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java similarity index 67% rename from src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java index 61cb784..a0031e5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Glow.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java @@ -1,6 +1,7 @@ -package net.tylermurphy.hideAndSeek.game; +package net.tylermurphy.hideAndSeek.game.events; -import net.tylermurphy.hideAndSeek.util.Packet; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Packet; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength; @@ -22,12 +23,12 @@ public class Glow { } private void sendPackets() { - for (Player hider : Board.getHiders()) - for (Player seeker : Board.getSeekers()) + for (Player hider : Main.getInstance().getBoard().getHiders()) + for (Player seeker : Main.getInstance().getBoard().getSeekers()) Packet.setGlow(hider, seeker, true); } - protected void update() { + public void update() { if (running) { sendPackets(); glowTime--; @@ -40,8 +41,8 @@ public class Glow { private void stopGlow() { running = false; - for (Player hider : Board.getHiders()) { - for (Player seeker : Board.getSeekers()) { + for (Player hider : Main.getInstance().getBoard().getHiders()) { + for (Player seeker : Main.getInstance().getBoard().getSeekers()) { Packet.setGlow(hider, seeker, false); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Taunt.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Taunt.java new file mode 100644 index 0000000..191b1e7 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Taunt.java @@ -0,0 +1,101 @@ +package net.tylermurphy.hideAndSeek.game.events; + +import net.tylermurphy.hideAndSeek.Main; +import org.bukkit.Color; +import org.bukkit.FireworkEffect; +import org.bukkit.World; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.FireworkMeta; + +import java.util.Optional; +import java.util.Random; +import java.util.UUID; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.tauntDelay; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class Taunt { + + private UUID tauntPlayer; + private int delay; + private boolean running; + + public Taunt() { + this.delay = tauntDelay; + } + + public void update() { + if (delay == 0) { + if (running) launchTaunt(); + else if (tauntLast || Main.getInstance().getBoard().sizeHider() > 1) executeTaunt(); + } else { + delay--; + delay = Math.max(delay, 0); + } + } + + private void executeTaunt() { + Optional rand = Main.getInstance().getBoard().getHiders().stream().skip(new Random().nextInt(Main.getInstance().getBoard().size())).findFirst(); + if (!rand.isPresent()) { + Main.getInstance().getLogger().warning("Failed to select random seeker."); + return; + } + Player taunted = rand.get(); + taunted.sendMessage(message("TAUNTED").toString()); + Main.getInstance().getGame().broadcastMessage(tauntPrefix + message("TAUNT")); + tauntPlayer = taunted.getUniqueId(); + running = true; + delay = 30; + } + + private void launchTaunt() { + Player taunted = Main.getInstance().getBoard().getPlayer(tauntPlayer); + if (taunted != null) { + if (!Main.getInstance().getBoard().isHider(taunted)) { + Main.getInstance().getLogger().info("Taunted played died and is now seeker. Skipping taunt."); + tauntPlayer = null; + running = false; + delay = tauntDelay; + return; + } + World world = taunted.getLocation().getWorld(); + if (world == null) { + Main.getInstance().getLogger().severe("Game world is null while trying to launch taunt."); + tauntPlayer = null; + running = false; + delay = tauntDelay; + return; + } + Firework fw = (Firework) world.spawnEntity(taunted.getLocation(), EntityType.FIREWORK); + FireworkMeta fwm = fw.getFireworkMeta(); + fwm.setPower(4); + fwm.addEffect(FireworkEffect.builder() + .withColor(Color.BLUE) + .withColor(Color.RED) + .withColor(Color.YELLOW) + .with(FireworkEffect.Type.STAR) + .with(FireworkEffect.Type.BALL) + .with(FireworkEffect.Type.BALL_LARGE) + .flicker(true) + .withTrail() + .build()); + fw.setFireworkMeta(fwm); + Main.getInstance().getGame().broadcastMessage(tauntPrefix + message("TAUNT_ACTIVATE")); + } + tauntPlayer = null; + running = false; + delay = tauntDelay; + } + + public int getDelay() { + return delay; + } + + public boolean isRunning() { + return running; + } + +} \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java index a805fa5..7cc6dc3 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/BlockedCommandHandler.java @@ -1,8 +1,7 @@ package net.tylermurphy.hideAndSeek.game.listener; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -23,10 +22,10 @@ public class BlockedCommandHandler implements Listener { String[] temp = array[0].split(":"); for(String handle : blockedCommands) { if ( - array[0].substring(1).equalsIgnoreCase(handle) && Board.contains(player) || - temp[temp.length-1].equalsIgnoreCase(handle) && Board.contains(player) + array[0].substring(1).equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player) || + temp[temp.length-1].equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player) ) { - if (Game.status == Status.STANDBY) return; + if (Main.getInstance().getGame().getStatus() == Status.STANDBY) return; player.sendMessage(errorPrefix + message("BLOCKED_COMMAND")); event.setCancelled(true); break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java index 523b3ee..07014b7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java @@ -1,6 +1,6 @@ package net.tylermurphy.hideAndSeek.game.listener; -import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -19,9 +19,9 @@ public class ChatHandler implements Listener { event.getPlayer().setAllowFlight(false); event.getPlayer().setFlying(false); } - if (Board.isSeeker(event.getPlayer())) { + if (Main.getInstance().getBoard().isSeeker(event.getPlayer())) { event.setCancelled(true); - Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); + Main.getInstance().getBoard().getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 5bbfa8c..aabbd92 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -1,13 +1,14 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.cryptomorin.xseries.XSound; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Version; +import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; +import net.tylermurphy.hideAndSeek.game.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Bukkit; import org.bukkit.Location; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; @@ -24,6 +25,10 @@ public class DamageHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamage(EntityDamageEvent event) { + + Board board = Main.getInstance().getBoard(); + Game game = Main.getInstance().getGame(); + // If you are not a player, get out of here if (!(event.getEntity() instanceof Player)) return; // Define variables @@ -44,18 +49,18 @@ public class DamageHandler implements Listener { // Makes sure that if there was an attacking player, that the event is allowed for the game if (attacker != null) { // Cancel if one player is in the game but other isn't - if ((Board.contains(player) && !Board.contains(attacker)) || (!Board.contains(player) && Board.contains(attacker))) { + if ((board.contains(player) && !board.contains(attacker)) || (!board.contains(player) && board.contains(attacker))) { event.setCancelled(true); return; // Ignore event if neither player are in the game - } else if (!Board.contains(player) && !Board.contains(attacker)) { + } else if (!board.contains(player) && !board.contains(attacker)) { return; // Ignore event if players are on the same team, or one of them is a spectator - } else if (Board.onSameTeam(player, attacker) || Board.isSpectator(player) || Board.isSpectator(attacker)) { + } else if (board.onSameTeam(player, attacker) || board.isSpectator(player) || board.isSpectator(attacker)) { event.setCancelled(true); return; // Ignore the event if pvp is disabled, and a hider is trying to attack a seeker - } else if (!pvpEnabled && Board.isHider(attacker) && Board.isSeeker(player)) { + } else if (!pvpEnabled && board.isHider(attacker) && board.isSeeker(player)) { event.setCancelled(true); return; } @@ -63,49 +68,52 @@ public class DamageHandler implements Listener { } else if (!pvpEnabled && !allowNaturalCauses) { event.setCancelled(true); return; - // Spectators cannot take damage - } else if (Board.isSpectator(player)) { + } + // Spectators cannot take damage + if (board.isSpectator(player)) { event.setCancelled(true); if (Version.atLeast("1.18") && player.getLocation().getY() < -64) { - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); } else if (player.getLocation().getY() < 0) { - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); } return; } + // Players cannot take damage while game is not in session + if (board.contains(player) && (game.getStatus() == Status.STANDBY || game.getStatus() == Status.STARTING)){ + event.setCancelled(true); + return; + } // Handle death event event.setCancelled(true); - // Reset health and play death effect + // Play death effect if (Version.atLeast("1.9")) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); - if (attribute != null) player.setHealth(attribute.getValue()); XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); } else { - player.setHealth(player.getMaxHealth()); XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); } // Teleport player to seeker spawn - player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); // Broadcast player death message - if (Board.isSeeker(player)) { - Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); - if (Board.getFirstSeeker().getName().equals(player.getName())) { - Board.addDeath(player.getUniqueId()); + if (board.isSeeker(player)) { + game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); + if (board.getFirstSeeker().getName().equals(player.getName())) { + board.addDeath(player.getUniqueId()); } - } else if (Board.isHider(player)) { + } else if (board.isHider(player)) { if (attacker == null) { - Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); + game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); } else { - Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); + game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); } - Board.addDeath(player.getUniqueId()); - Board.addSeeker(player); + board.addDeath(player.getUniqueId()); + board.addSeeker(player); } // Add leaderboard kills if attacker - if (attacker != null && ( Board.isHider(attacker) || Board.getFirstSeeker().getName().equals(attacker.getName()) ) ) - Board.addKill(attacker.getUniqueId()); - Game.resetPlayer(player); - Board.reloadBoardTeams(); + if (attacker != null && ( board.isHider(attacker) || board.getFirstSeeker().getName().equals(attacker.getName()) ) ) + board.addKill(attacker.getUniqueId()); + PlayerUtil.resetPlayer(player, board); + board.reloadBoardTeams(); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java index 7aa976a..bd2c7fe 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -1,9 +1,8 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.cryptomorin.xseries.XMaterial; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -20,40 +19,40 @@ public class InteractHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { - if (!Board.contains(event.getPlayer())) return; + if (!Main.getInstance().getBoard().contains(event.getPlayer())) return; if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())) { event.setCancelled(true); return; } ItemStack temp = event.getItem(); if (temp == null) return; - if (Game.status == Status.STANDBY) + if (Main.getInstance().getGame().getStatus() == Status.STANDBY) onPlayerInteractLobby(temp, event); - if (Game.status == Status.PLAYING) + if (Main.getInstance().getGame().getStatus() == Status.PLAYING) onPlayerInteractGame(temp, event); } private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { event.setCancelled(true); - Game.leave(event.getPlayer()); + Main.getInstance().getGame().leave(event.getPlayer()); } if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) { event.setCancelled(true); - if (Game.isNotSetup()) { + if (Main.getInstance().getGame().isNotSetup()) { event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP")); return; } - if (Game.status != Status.STANDBY) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; } - if (Board.size() < minPlayers) { + if (Main.getInstance().getBoard().size() < minPlayers) { event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); return; } - Game.start(); + Main.getInstance().getGame().start(); } } @@ -61,8 +60,8 @@ public class InteractHandler implements Listener { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { if (!glowEnabled) return; Player player = event.getPlayer(); - if (Board.isHider(player)) { - Game.glow.onProjectile(); + if (Main.getInstance().getBoard().isHider(player)) { + Main.getInstance().getGame().getGlow().onProjectile(); player.getInventory().remove(glowPowerupItem); assert XMaterial.SNOWBALL.parseMaterial() != null; player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java index 6e42f57..37865b0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java @@ -1,8 +1,8 @@ package net.tylermurphy.hideAndSeek.game.listener; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.configuration.Items; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -13,6 +13,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import static net.tylermurphy.hideAndSeek.configuration.Config.*; @@ -22,20 +23,20 @@ public class JoinLeaveHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent event) { - Board.remove(event.getPlayer()); - Game.removeItems(event.getPlayer()); - if (Game.isNotSetup()) return; + Main.getInstance().getBoard().remove(event.getPlayer()); + removeItems(event.getPlayer()); + if (Main.getInstance().getGame().isNotSetup()) return; if (autoJoin) { - Game.join(event.getPlayer()); + Main.getInstance().getGame().join(event.getPlayer()); } else if (teleportToExit) { - if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { + if (event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().setGameMode(GameMode.ADVENTURE); } } else { - if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { - if (Game.status != Status.STANDBY && Game.status != Status.ENDING) { - Game.join(event.getPlayer()); + if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) { + if (Main.getInstance().getGame().getStatus() != Status.STANDBY && Main.getInstance().getGame().getStatus() != Status.ENDING) { + Main.getInstance().getGame().join(event.getPlayer()); } else { event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().setGameMode(GameMode.ADVENTURE); @@ -55,16 +56,25 @@ public class JoinLeaveHandler implements Listener { } private void handleLeave(Player player) { - Board.remove(player); - if (Game.status == Status.STANDBY) { - Board.reloadLobbyBoards(); + Main.getInstance().getBoard().remove(player); + if (Main.getInstance().getGame().getStatus() == Status.STANDBY) { + Main.getInstance().getBoard().reloadLobbyBoards(); } else { - Board.reloadGameBoards(); + Main.getInstance().getBoard().reloadGameBoards(); } for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } - Game.removeItems(player); + removeItems(player); + } + + private void removeItems(Player player) { + for(ItemStack si : Items.SEEKER_ITEMS) + for(ItemStack i : player.getInventory().getContents()) + if (si.isSimilar(i)) player.getInventory().remove(i); + for(ItemStack hi : Items.HIDER_ITEMS) + for(ItemStack i : player.getInventory().getContents()) + if (hi.isSimilar(i)) player.getInventory().remove(i); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java index 21e02de..10872ad 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java @@ -1,7 +1,6 @@ package net.tylermurphy.hideAndSeek.game.listener; -import net.tylermurphy.hideAndSeek.game.Board; -import net.tylermurphy.hideAndSeek.game.Game; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -14,11 +13,11 @@ public class MovementHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onMove(PlayerMoveEvent event) { - if (!Board.contains(event.getPlayer())) return; - if (!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; + if (!Main.getInstance().getBoard().contains(event.getPlayer())) return; + if (!event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return; if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return; if (event.getTo() == null || event.getTo().getWorld() == null) return; - if (!event.getTo().getWorld().getName().equals(Game.getGameWorld())) return; + if (!event.getTo().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return; if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) { event.setCancelled(true); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java index 31aedb0..b63d982 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java @@ -1,8 +1,8 @@ package net.tylermurphy.hideAndSeek.game.listener; -import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -17,7 +17,7 @@ public class PlayerHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onFoodLevelChange(FoodLevelChangeEvent event) { if (event.getEntity() instanceof Player) { - if (!Board.contains((Player) event.getEntity())) return; + if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return; event.setCancelled(true); } } @@ -26,7 +26,7 @@ public class PlayerHandler implements Listener { public void onPlayerRegainHealth(EntityRegainHealthEvent event) { if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) { if (event.getEntity() instanceof Player) { - if (!Board.contains((Player) event.getEntity())) return; + if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return; event.setCancelled(true); } } @@ -36,7 +36,7 @@ public class PlayerHandler implements Listener { public void onInventoryClick(InventoryClickEvent event) { if (event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); - if (Board.contains(player) && Game.status == Status.STANDBY) { + if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { event.setCancelled(true); } } @@ -44,7 +44,7 @@ public class PlayerHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onItemDrop(PlayerDropItemEvent event) { - if (Board.contains(event.getPlayer())) { + if (Main.getInstance().getBoard().contains(event.getPlayer())) { event.setCancelled(true); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java index aeda227..951304a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/RespawnHandler.java @@ -1,7 +1,6 @@ package net.tylermurphy.hideAndSeek.game.listener; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Board; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -21,17 +20,17 @@ public class RespawnHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); - if (!Board.contains(player)) return; + if (!Main.getInstance().getBoard().contains(player)) return; event.setKeepInventory(true); event.setDeathMessage(""); temp_loc.put(player.getUniqueId(), player.getLocation()); - Main.plugin.getLogger().severe("Player " + player.getName() + " died when not supposed to. Attempting to roll back death."); + Main.getInstance().getLogger().severe("Player " + player.getName() + " died when not supposed to. Attempting to roll back death."); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); - if (!Board.contains(player)) return; + if (!Main.getInstance().getBoard().contains(player)) return; if (temp_loc.containsKey(player.getUniqueId())) { player.teleport(temp_loc.get(player.getUniqueId())); temp_loc.remove(player.getUniqueId()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/CountdownDisplay.java similarity index 94% rename from src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/util/CountdownDisplay.java index 477f7ca..e735af9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/CountdownDisplay.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/CountdownDisplay.java @@ -17,7 +17,7 @@ * */ -package net.tylermurphy.hideAndSeek.util; +package net.tylermurphy.hideAndSeek.game.util; public enum CountdownDisplay { CHAT, diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java similarity index 97% rename from src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java index bb7219f..0fad539 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Packet.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java @@ -17,7 +17,7 @@ * */ -package net.tylermurphy.hideAndSeek.util; +package net.tylermurphy.hideAndSeek.game.util; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java new file mode 100644 index 0000000..61d2b0e --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java @@ -0,0 +1,120 @@ +package net.tylermurphy.hideAndSeek.game.util; + +import com.cryptomorin.xseries.messages.Titles; +import net.md_5.bungee.api.ChatColor; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.configuration.Items; +import net.tylermurphy.hideAndSeek.game.Board; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.lobbyPosition; +import static net.tylermurphy.hideAndSeek.configuration.Localization.message; + +public class PlayerUtil { + + public static void loadHider(Player player, String gameWorld){ + player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + loadPlayer(player); + player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false)); + Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString()); + } + + public static void loadSeeker(Player player, String gameWorld){ + player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + loadPlayer(player); + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS,1000000,127,false,false)); + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW,1000000,127,false,false)); + player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,1000000,128,false,false)); + Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("SEEKER_TEAM_NAME"), ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString()); + } + + public static void loadSpectator(Player player, String gameWorld){ + player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); + loadPlayer(player); + player.setAllowFlight(true); + player.setFlying(true); + player.setFallDistance(0.0F); + Main.getInstance().getBoard().getPlayers().forEach(otherPlayer -> { + otherPlayer.hidePlayer(player); + }); + Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString()); + } + + public static void resetPlayer(Player player, Board board){ + loadPlayer(player); + if (board.isSeeker(player)) { + if (pvpEnabled) + for(ItemStack item : Items.SEEKER_ITEMS) + player.getInventory().addItem(item); + for(PotionEffect effect : Items.SEEKER_EFFECTS) + player.addPotionEffect(effect); + } else if (board.isHider(player)) { + if (pvpEnabled) + for(ItemStack item : Items.HIDER_ITEMS) + player.getInventory().addItem(item); + for(PotionEffect effect : Items.HIDER_EFFECTS) + player.addPotionEffect(effect); + if (glowEnabled) { + player.getInventory().addItem(glowPowerupItem); + } + } + } + + public static void unloadPlayer(Player player){ + player.setGameMode(GameMode.ADVENTURE); + player.getInventory().clear(); + for(PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + if (Version.atLeast("1.9")) { + AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + if (attribute != null) player.setHealth(attribute.getValue()); + for(Player temp : Main.getInstance().getBoard().getPlayers()) { + Packet.setGlow(player, temp, false); + } + } else { + player.setHealth(player.getMaxHealth()); + } + Main.getInstance().getBoard().getPlayers().forEach(temp -> { + player.showPlayer(temp); + temp.showPlayer(player); + }); + player.setAllowFlight(false); + player.setFlying(false); + player.setFallDistance(0.0F); + } + + public static void joinPlayer(Player player){ + player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); + loadPlayer(player); + if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) + player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); + if (lobbyLeaveItem != null) + player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem); + } + + private static void loadPlayer(Player player){ + player.setGameMode(GameMode.ADVENTURE); + player.getInventory().clear(); + for(PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + player.setFoodLevel(20); + if (Version.atLeast("1.9")) { + AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + if (attribute != null) player.setHealth(attribute.getValue()); + } else { + player.setHealth(player.getMaxHealth()); + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Status.java similarity index 88% rename from src/main/java/net/tylermurphy/hideAndSeek/util/Status.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/util/Status.java index 0ffba00..e630070 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Status.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Status.java @@ -17,10 +17,10 @@ * */ -package net.tylermurphy.hideAndSeek.util; +package net.tylermurphy.hideAndSeek.game.util; public enum Status { - STANDBY, STARTING, PLAYING, ENDING + STANDBY, STARTING, PLAYING, ENDING, ENDED } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java similarity index 97% rename from src/main/java/net/tylermurphy/hideAndSeek/util/Version.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java index fa66fe2..e2dcfdd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/Version.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java @@ -1,4 +1,4 @@ -package net.tylermurphy.hideAndSeek.util; +package net.tylermurphy.hideAndSeek.game.util; import org.bukkit.Bukkit; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/WinType.java similarity index 94% rename from src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/util/WinType.java index 1f6ccd8..f584d80 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/WinType.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/WinType.java @@ -17,7 +17,7 @@ * */ -package net.tylermurphy.hideAndSeek.util; +package net.tylermurphy.hideAndSeek.game.util; public enum WinType { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java similarity index 92% rename from src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java rename to src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java index b7b2dad..3a05ee5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java @@ -17,9 +17,12 @@ * */ -package net.tylermurphy.hideAndSeek.game; +package net.tylermurphy.hideAndSeek.util; import net.tylermurphy.hideAndSeek.command.*; +import net.tylermurphy.hideAndSeek.command.location.SetExitLocation; +import net.tylermurphy.hideAndSeek.command.location.SetLobbyLocation; +import net.tylermurphy.hideAndSeek.command.location.SetSpawnLocation; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 4af5ff9..b5e7e34 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -1,6 +1,7 @@ package net.tylermurphy.hideAndSeek.util; import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.PlayerInfo; import org.bukkit.OfflinePlayer; @@ -35,42 +36,43 @@ public class PAPIExpansion extends PlaceholderExpansion { @Override public String onRequest(OfflinePlayer player, @NotNull String params) { + Database database = Main.getInstance().getDatabase(); String[] args = params.split("_"); if (args.length < 1) return null; if (args[0].equals("stats") && args.length == 2) { - PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); return getValue(info, args[1]); } else if (args[0].equals("stats") && args.length == 3) { UUID uuid; - try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } - PlayerInfo info = Database.playerInfo.getInfo(uuid); + try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } + PlayerInfo info = database.getGameData().getInfo(uuid); return getValue(info, args[1]); } else if ((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3) { int place; try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } if (place < 1) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = Database.playerInfo.getInfoRanking(getRanking(args[1]), place); + PlayerInfo info = database.getGameData().getInfoRanking(getRanking(args[1]), place); if (info == null) return placeholderNoData; if (args[0].equals("rank-score")) { return getValue(info, args[1]); } else { - return UUIDFetcher.getPlayer(info.uuid).getName(); + return Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName(); } } else if (args[0].equals("rank-place") && args.length == 2) { if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); if (getValue(info, args[1]).equals("0")) { return "-"; } - Integer count = Database.playerInfo.getRanking(getRanking(args[1]), player.getUniqueId()); + Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); if (count == null) { return placeholderNoData; } return count.toString(); } else if (args[0].equals("rank-place") && args.length == 3) { UUID uuid; - try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } + try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); + PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); if (getValue(info, args[1]).equals("0")) { return "-"; } - Integer count = Database.playerInfo.getRanking(getRanking(args[1]), uuid); + Integer count = database.getGameData().getRanking(getRanking(args[1]), uuid); if (count == null) { return placeholderNoData; } return count.toString(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java index 85b10ee..2605e7b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/TabCompleter.java @@ -19,7 +19,6 @@ package net.tylermurphy.hideAndSeek.util; -import net.tylermurphy.hideAndSeek.game.CommandHandler; import org.bukkit.command.CommandSender; import java.util.ArrayList; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java b/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java deleted file mode 100644 index abc3400..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/UUIDFetcher.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.util; - -import net.tylermurphy.hideAndSeek.Main; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public final class UUIDFetcher { - - private static final Map CACHE = new HashMap<>(); - private static final Map PLAYER_CACHE = new HashMap<>(); - - private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/"; - private static int cacheTask; - - public static void init() { - cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, () -> { - CACHE.clear(); - PLAYER_CACHE.clear(); - }, 600 * 20, 600 * 20); - } - - public static void cleanup() { - Main.plugin.getServer().getScheduler().cancelTask(cacheTask); - } - - public static UUID getUUID(String playername) { - - if (CACHE.containsKey(playername)) return CACHE.get(playername); - - String output = callURL(UUID_URL + playername); - StringBuilder result = new StringBuilder(); - readData(output, result); - String u = result.toString(); - StringBuilder uuid = new StringBuilder(); - for (int i = 0; i <= 31; i++) { - uuid.append(u.charAt(i)); - if (i == 7 || i == 11 || i == 15 || i == 19) { - uuid.append('-'); - } - } - - CACHE.put(playername, UUID.fromString(uuid.toString())); - - return UUID.fromString(uuid.toString()); - } - - public static OfflinePlayer getPlayer(UUID uuid) { - if (PLAYER_CACHE.containsKey(uuid)) return PLAYER_CACHE.get(uuid); - OfflinePlayer temp = Bukkit.getOfflinePlayer(uuid); - PLAYER_CACHE.put(uuid, temp); - return temp; - } - - private static void readData(String toRead, StringBuilder result) { - for (int i = toRead.length() - 3; i >= 0; i--) { - if (toRead.charAt(i) != '"') { - result.insert(0, toRead.charAt(i)); - } else { - break; - } - } - } - - private static String callURL(String urlStr) { - StringBuilder sb = new StringBuilder(); - URLConnection urlConn; - InputStreamReader in; - try { - URL url = new URL(urlStr); - urlConn = url.openConnection(); - if (urlConn != null) { - urlConn.setReadTimeout(60 * 1000); - } - if (urlConn != null && urlConn.getInputStream() != null) { - in = new InputStreamReader(urlConn.getInputStream(), - Charset.defaultCharset()); - BufferedReader bufferedReader = new BufferedReader(in); - int cp; - while ((cp = bufferedReader.read()) != -1) { - sb.append((char) cp); - } - bufferedReader.close(); - in.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - return sb.toString(); - } - -} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index 20d8ee5..193c34e 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -32,14 +32,19 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class WorldLoader { - final String mapName; - final String saveName; + private String mapName; + private String saveName; public WorldLoader(String mapName) { this.mapName = mapName; this.saveName = "hideandseek_"+ mapName; } + public void setNewMap(String mapName){ + this.mapName = mapName; + this.saveName = "hideandseek_"+ mapName; + } + public World getWorld() { return Bukkit.getServer().getWorld(saveName); } @@ -47,13 +52,13 @@ public class WorldLoader { public void unloadMap() { World world = Bukkit.getServer().getWorld(saveName); if (world == null) { - Main.plugin.getLogger().warning(saveName + " already unloaded."); + Main.getInstance().getLogger().warning(saveName + " already unloaded."); return; } if (Bukkit.getServer().unloadWorld(world, false)) { - Main.plugin.getLogger().info("Successfully unloaded " + saveName); + Main.getInstance().getLogger().info("Successfully unloaded " + saveName); }else{ - Main.plugin.getLogger().severe("COULD NOT UNLOAD " + saveName); + Main.getInstance().getLogger().severe("COULD NOT UNLOAD " + saveName); } } @@ -61,7 +66,7 @@ public class WorldLoader { Bukkit.getServer().createWorld(new WorldCreator(saveName).generator(new VoidGenerator())); World world = Bukkit.getServer().getWorld(saveName); if (world == null) { - Main.plugin.getLogger().severe("COULD NOT LOAD " + saveName); + Main.getInstance().getLogger().severe("COULD NOT LOAD " + saveName); return; } world.setAutoSave(false); @@ -73,11 +78,11 @@ public class WorldLoader { } public String save() { - File current = new File(Main.root+File.separator+ mapName); + File current = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName); if (current.exists()) { try { - File destenation = new File(Main.root+File.separator+ saveName); - File temp_destenation = new File(Main.root+File.separator+"temp_"+ saveName); + File destenation = new File(Main.getInstance().getWorldContainer()+File.separator+ saveName); + File temp_destenation = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName); copyFileFolder("region",true); copyFileFolder("entities",true); copyFileFolder("datapacks",false); @@ -104,22 +109,18 @@ public class WorldLoader { } private void copyFileFolder(String name, Boolean isMca) throws IOException { - File region = new File(Main.root+File.separator+ mapName +File.separator+name); - File temp = new File(Main.root+File.separator+"temp_"+ saveName +File.separator+name); - System.out.println(region.getAbsolutePath()); - System.out.println(temp.getAbsolutePath()); + File region = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName +File.separator+name); + File temp = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName +File.separator+name); if (region.exists() && region.isDirectory()) { - System.out.println("passed"); if (!temp.exists()) if (!temp.mkdirs()) throw new IOException("Couldn't create region directory!"); String[] files = region.list(); if (files == null) { - Main.plugin.getLogger().severe("Region directory is null or cannot be accessed"); + Main.getInstance().getLogger().severe("Region directory is null or cannot be accessed"); return; } for (String file : files) { - System.out.println("Testing file "+ file); if (isMca) { int minX = (int)Math.floor(saveMinX / 512.0); int minZ = (int)Math.floor(saveMinZ / 512.0); @@ -128,7 +129,7 @@ public class WorldLoader { String[] parts = file.split("\\."); if (parts.length > 1) { - Main.plugin.getLogger().info(file); + Main.getInstance().getLogger().info(file); if ( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ ) continue; } From 99c1ea8eb34093f27c37d315e2bc447f93998287 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 13 May 2022 23:11:35 -0400 Subject: [PATCH 45/68] better spectator flight and teleporting --- .../hideAndSeek/configuration/Config.java | 70 +++++++++--------- .../tylermurphy/hideAndSeek/game/Game.java | 2 +- .../game/listener/ChatHandler.java | 8 -- .../game/listener/DamageHandler.java | 4 +- .../game/listener/InteractHandler.java | 73 ++++++++++++++++++- .../game/listener/MovementHandler.java | 35 ++++++++- .../game/listener/PlayerHandler.java | 13 ---- .../hideAndSeek/game/util/PlayerUtil.java | 2 + src/main/resources/config.yml | 18 +++++ .../resources/lang/localization_de-DE.yml | 2 + .../resources/lang/localization_en-US.yml | 2 + 11 files changed, 164 insertions(+), 65 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index afd1729..9fdaaa6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -31,6 +31,7 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -105,7 +106,9 @@ public class Config { seekerPingLevel2, seekerPingLevel3, lobbyItemLeavePosition, - lobbyItemStartPosition; + lobbyItemStartPosition, + flightToggleItemPosition, + teleportItemPosition; public static float seekerPingLeadingVolume, @@ -137,7 +140,9 @@ public class Config { public static ItemStack lobbyLeaveItem, lobbyStartItem, - glowPowerupItem; + glowPowerupItem, + flightToggleItem, + teleportItem; public static XSound ringingSound, @@ -218,14 +223,7 @@ public class Config { glowStackable = config.getBoolean("glow.stackable"); glowEnabled = config.getBoolean("glow.enabled") && Version.atLeast("1.9"); if (glowEnabled) { - ConfigurationSection item = new YamlConfiguration().createSection("temp"); - item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("glow.name"))); - item.set("material", config.getString("glow.material")); - List lore = config.getStringList("glow.lore"); - if (lore != null && !lore.isEmpty()) item.set("lore", lore); - ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} - glowPowerupItem = temp; + glowPowerupItem = createItemStack("glow"); } //Lobby @@ -302,38 +300,21 @@ public class Config { //Lobby Items if (config.getBoolean("lobbyItems.leave.enabled")) { - ConfigurationSection item = new YamlConfiguration().createSection("temp"); - item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.leave.name"))); - item.set("material", config.getString("lobbyItems.leave.material")); - if (Version.atLeast("1.14")) { - if (config.contains("lobbyItems.leave.model-data") && config.getInt("lobbyItems.leave.model-data") != 0) { - item.set("model-data", config.getInt("lobbyItems.leave.model-data")); - } - } - List lore = config.getStringList("lobbyItems.leave.lore"); - if (lore != null && !lore.isEmpty()) item.set("lore", lore); - ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} - lobbyLeaveItem = temp; + lobbyLeaveItem = createItemStack("lobbyItems.leave"); lobbyItemLeavePosition = config.getInt("lobbyItems.leave.position"); } if (config.getBoolean("lobbyItems.start.enabled")) { - ConfigurationSection item = new YamlConfiguration().createSection("temp"); - item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.start.name"))); - item.set("material", config.getString("lobbyItems.start.material")); - List lore = config.getStringList("lobbyItems.start.lore"); - if (lore != null && !lore.isEmpty()) item.set("lore", lore); - ItemStack temp = null; - try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} - lobbyStartItem = temp; + lobbyStartItem = createItemStack("lobbyItems.start"); lobbyItemStartAdmin = config.getBoolean("lobbyItems.start.adminOnly"); lobbyItemStartPosition = config.getInt("lobbyItems.start.position"); - if (Version.atLeast("1.14")) { - if (config.contains("lobbyItems.start.model-data") && config.getInt("lobbyItems.start.model-data") != 0) { - item.set("model-data", config.getInt("lobbyItems.start.model-data")); - } - } } + + //Spectator Items + flightToggleItem = createItemStack("spectatorItems.flight"); + flightToggleItemPosition = config.getInt("spectatorItems.flight.position"); + + teleportItem = createItemStack("spectatorItems.teleport"); + teleportItemPosition = config.getInt("spectatorItems.teleport.position"); } public static void addToConfig(String path, Object value) { @@ -343,5 +324,22 @@ public class Config { public static void saveConfig() { config.saveConfig(); } + + @Nullable + private static ItemStack createItemStack(String path){ + ConfigurationSection item = new YamlConfiguration().createSection("temp"); + item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString(path+".name"))); + item.set("material", config.getString(path+".material")); + if (Version.atLeast("1.14")) { + if (config.contains(path+".model-data") && config.getInt(path+".model-data") != 0) { + item.set("model-data", config.getInt(path+".model-data")); + } + } + List lore = config.getStringList(path+".lore"); + if (lore != null && !lore.isEmpty()) item.set("lore", lore); + ItemStack temp = null; + try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {} + return temp; + } } \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index e33e503..15341c0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -265,7 +265,6 @@ public class Game { } startingTimer--; } - checkWinConditions(); } @@ -308,6 +307,7 @@ public class Game { if (tauntEnabled) taunt.update(); if (glowEnabled) glow.update(); } + board.getSpectators().forEach(spectator -> spectator.setFlying(spectator.getAllowFlight())); checkWinConditions(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java index 07014b7..27a6235 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/ChatHandler.java @@ -11,14 +11,6 @@ public class ChatHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onChat(AsyncPlayerChatEvent event) { - if (event.getMessage().equals("fly")) { - event.getPlayer().setAllowFlight(true); - event.getPlayer().setFlying(true); - } - if (event.getMessage().equals("no fly")) { - event.getPlayer().setAllowFlight(false); - event.getPlayer().setFlying(false); - } if (Main.getInstance().getBoard().isSeeker(event.getPlayer())) { event.setCancelled(true); Main.getInstance().getBoard().getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index aabbd92..ee63cc2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -34,8 +34,6 @@ public class DamageHandler implements Listener { // Define variables Player player = (Player) event.getEntity(); Player attacker = null; - // If player pvp is enabled, and player doesn't die, we do not care - if (pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5) { return; } // If no spawn position, we won't be able to manage their death :o if (spawnPosition == null) { return; } // If there is an attacker, find them @@ -84,6 +82,8 @@ public class DamageHandler implements Listener { event.setCancelled(true); return; } + // Check if player dies (pvp mode) + if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5) return; // Handle death event event.setCancelled(true); // Play death effect diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java index bd2c7fe..7fe924f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -1,15 +1,23 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.cryptomorin.xseries.XMaterial; +import com.cryptomorin.xseries.messages.ActionBar; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; +import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; +import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.List; import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Config.glowPowerupItem; @@ -30,15 +38,17 @@ public class InteractHandler implements Listener { onPlayerInteractLobby(temp, event); if (Main.getInstance().getGame().getStatus() == Status.PLAYING) onPlayerInteractGame(temp, event); + if (Main.getInstance().getBoard().isSpectator(event.getPlayer())) + onSpectatorInteract(temp, event); } private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event) { - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) { + if (temp.isSimilar(lobbyLeaveItem)) { event.setCancelled(true); Main.getInstance().getGame().leave(event.getPlayer()); } - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) { + if (temp.isSimilar(lobbyStartItem) && event.getPlayer().hasPermission("hideandseek.start")) { event.setCancelled(true); if (Main.getInstance().getGame().isNotSetup()) { event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP")); @@ -57,7 +67,7 @@ public class InteractHandler implements Listener { } private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event) { - if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { + if (temp.isSimilar(glowPowerupItem)) { if (!glowEnabled) return; Player player = event.getPlayer(); if (Main.getInstance().getBoard().isHider(player)) { @@ -70,4 +80,61 @@ public class InteractHandler implements Listener { } } + private void onSpectatorInteract(ItemStack temp, PlayerInteractEvent event){ + if(temp.isSimilar(flightToggleItem)){ + boolean isFlying = event.getPlayer().getAllowFlight(); + event.getPlayer().setAllowFlight(!isFlying); + event.getPlayer().setFlying(!isFlying); + ActionBar.clearActionBar(event.getPlayer()); + if(!isFlying){ + ActionBar.sendActionBar(event.getPlayer(), message("FLYING_ENABLED").toString()); + } else { + ActionBar.sendActionBar(event.getPlayer(), message("FLYING_DISABLED").toString()); + } + return; + } + if(temp.isSimilar(teleportItem)){ + int amount = Main.getInstance().getBoard().getHiders().size() + Main.getInstance().getBoard().getSeekers().size(); + Inventory teleportMenu = Main.getInstance().getServer().createInventory(null, 9*(((amount-1)/9)+1), ChatColor.stripColor(teleportItem.getItemMeta().getDisplayName())); + List hider_lore = new ArrayList<>(); hider_lore.add(message("HIDER_TEAM_NAME").toString()); + Main.getInstance().getBoard().getHiders().forEach(hider -> { + teleportMenu.addItem(getSkull(hider, hider_lore)); + }); + List seeker_lore = new ArrayList<>(); seeker_lore.add(message("SEEKER_TEAM_NAME").toString()); + Main.getInstance().getBoard().getSeekers().forEach(seeker -> { + teleportMenu.addItem(getSkull(seeker, seeker_lore)); + }); + event.getPlayer().openInventory(teleportMenu); + } + } + + private ItemStack getSkull(Player player, List lore){ + assert XMaterial.PLAYER_HEAD.parseMaterial() != null; + ItemStack playerhead = new ItemStack(XMaterial.PLAYER_HEAD.parseMaterial(), 1); + SkullMeta playerheadmeta = (SkullMeta) playerhead.getItemMeta(); + playerheadmeta.setOwner(player.getName()); + playerheadmeta.setDisplayName(player.getName()); + playerheadmeta.setLore(lore); + playerhead.setItemMeta(playerheadmeta); + return playerhead; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(InventoryClickEvent event) { + if (event.getWhoClicked() instanceof Player) { + Player player = (Player) event.getWhoClicked(); + if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { + event.setCancelled(true); + } + if (Main.getInstance().getBoard().isSpectator(player) && event.getCurrentItem().getType() == XMaterial.PLAYER_HEAD.parseMaterial()) { + event.setCancelled(true); + player.closeInventory(); + String name = event.getCurrentItem().getItemMeta().getDisplayName(); + Player clicked = Main.getInstance().getServer().getPlayer(name); + if(clicked == null) return; + player.teleport(clicked); + } + } + } + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java index 10872ad..aafc529 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java @@ -1,23 +1,54 @@ package net.tylermurphy.hideAndSeek.game.listener; +import com.comphenix.protocol.PacketType; +import com.google.common.collect.Sets; import net.tylermurphy.hideAndSeek.Main; +import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; +import java.util.Set; +import java.util.UUID; + import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Config.saveMaxZ; public class MovementHandler implements Listener { + private final Set prevPlayersOnGround = Sets.newHashSet(); + @EventHandler(priority = EventPriority.HIGHEST) public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null || event.getTo().getWorld() == null) return; + + checkJumping(event); + checkBounds(event); + } + + private void checkJumping(PlayerMoveEvent event){ + if (!Main.getInstance().getBoard().isSpectator(event.getPlayer())) return; + if (event.getPlayer().getVelocity().getY() > 0) { + if (event.getPlayer().getLocation().getBlock().getType() != Material.LADDER && prevPlayersOnGround.contains(event.getPlayer().getUniqueId())) { + if (!event.getPlayer().isOnGround()) { + // JUMPING :o + if(event.getPlayer().getAllowFlight()) event.getPlayer().setFlying(true); + } + } + } + if (event.getPlayer().isOnGround()) { + prevPlayersOnGround.add(event.getPlayer().getUniqueId()); + } else { + prevPlayersOnGround.remove(event.getPlayer().getUniqueId()); + } + } + + private void checkBounds(PlayerMoveEvent event){ if (!Main.getInstance().getBoard().contains(event.getPlayer())) return; if (!event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return; - if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return; - if (event.getTo() == null || event.getTo().getWorld() == null) return; if (!event.getTo().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return; + if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return; if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) { event.setCancelled(true); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java index b63d982..d8790fd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/PlayerHandler.java @@ -1,15 +1,12 @@ package net.tylermurphy.hideAndSeek.game.listener; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerDropItemEvent; public class PlayerHandler implements Listener { @@ -32,16 +29,6 @@ public class PlayerHandler implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(InventoryClickEvent event) { - if (event.getWhoClicked() instanceof Player) { - Player player = (Player) event.getWhoClicked(); - if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { - event.setCancelled(true); - } - } - } - @EventHandler(priority = EventPriority.HIGHEST) public void onItemDrop(PlayerDropItemEvent event) { if (Main.getInstance().getBoard().contains(event.getPlayer())) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java index 61d2b0e..59c7b73 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java @@ -43,6 +43,8 @@ public class PlayerUtil { player.setAllowFlight(true); player.setFlying(true); player.setFallDistance(0.0F); + player.getInventory().setItem(flightToggleItemPosition, flightToggleItem); + player.getInventory().setItem(teleportItemPosition, teleportItem); Main.getInstance().getBoard().getPlayers().forEach(otherPlayer -> { otherPlayer.hidePlayer(player); }); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 75658b6..c509200 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -130,6 +130,7 @@ glow: name: "Glow Powerup" lore: [ "Throw to make all seekers glow", "Last 30s, all hiders can see it", "Time stacks on multi use" ] material: SNOWBALL + model-data: 0 # The message prefixes displayed before messages. The message contents themselves # can be changed in localization.yml. @@ -182,6 +183,23 @@ lobbyItems: enabled: true adminOnly: true +# Below are the two items given to you when you join the game as a spectator. One toggles flight mode, and the other +# opens a gui to teleport to other players! Just like the lobby items, you can customize the material, name, lore, +# and position of the item. You can also change the model data if your server is running 1.14 or above. +spectatorItems: + flight: + material: FEATHER + name: "&bToggle Flight" + lore: [ "Turns flying on and off" ] + position: 3 + model-data: 0 + teleport: + material: COMPASS + name: "&bTeleport to Others" + lore: [ "Allows you to teleport to all other players in game" ] + position: 5 + model-data: 0 + # As a hider, the closer a seeker gets to you, the louder and faster a pining noise will play. # There are 3 separate distances (in blocks) you can set to the 3 different levels for the noise. # The higher the level, the closer the seeker. diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index fec12ba..84ada18 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -70,6 +70,8 @@ Localization: NO_GAME_INFO: "Keine Informationen zum Gameplay für diesen Spieler vorhanden." INFORMATION_FOR: "Gewinninformationen für {PLAYER}:" BLOCKED_COMMAND: "Command blocked by Kenshin's Hide And Seek" + FLYING_ENABLED: "Fliegen aktiviert" + FLYING_DISABLED: "Fliegen deaktiviert" # DO NOT EDIT IT OR IT MAY BREAK OR RESET FILE version: 3 diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index 1115fc4..07d547b 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -71,6 +71,8 @@ Localization: NO_GAME_INFO: "Player has no gameplay information." INFORMATION_FOR: "Win information for {PLAYER}:" BLOCKED_COMMAND: "Command blocked by Hide And Seek plugin." + FLYING_ENABLED: "&l&bFlying Enabled" + FLYING_DISABLED: "&l&bFlying Disabled" # DO NOT EDIT IT OR IT MAY BREAK OR RESET FILE version: 3 From e45099a5f415292b914d05b521336822d490a984 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Sat, 14 May 2022 08:36:25 -0500 Subject: [PATCH 46/68] refactor: reorganize PlayerInfo without static variables --- .../tylermurphy/hideAndSeek/command/Top.java | 4 +- .../tylermurphy/hideAndSeek/command/Wins.java | 4 +- .../hideAndSeek/database/PlayerInfo.java | 75 ++++++++++++++----- .../hideAndSeek/database/PlayerInfoTable.java | 16 ++-- .../hideAndSeek/util/PAPIExpansion.java | 26 +++---- 5 files changed, 81 insertions(+), 44 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 31f814c..4f2c628 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -54,7 +54,7 @@ public class Top implements ICommand { return; } for(PlayerInfo info : infos) { - String name = Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName(); + String name = Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); ChatColor color; switch (i) { case 1: color = ChatColor.YELLOW; break; @@ -63,7 +63,7 @@ public class Top implements ICommand { default: color = ChatColor.WHITE; break; } message.append(String.format("%s%s. %s%s %s%s\n", - color, i, ChatColor.RED, info.seeker_wins+info.hider_wins, ChatColor.WHITE, name)); + color, i, ChatColor.RED, info.getSeekerWins() +info.getHiderWins(), ChatColor.WHITE, name)); i++; } sender.sendMessage(message.toString()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index 0c0f5eb..e12e094 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -64,8 +64,8 @@ public class Wins implements ICommand { message = message + message("INFORMATION_FOR").addPlayer(name) + "\n"; message = message + "==============================\n"; message = message + String.format("%sTOTAL WINS: %s%s\n%sHIDER WINS: %s%s\n%sSEEKER WINS: %s%s\n%sGAMES PLAYED: %s", - ChatColor.YELLOW, ChatColor.WHITE, info.seeker_wins+info.hider_wins, ChatColor.GOLD, ChatColor.WHITE, info.hider_wins, - ChatColor.RED, ChatColor.WHITE, info.seeker_wins, ChatColor.WHITE, info.seeker_games+info.hider_games); + ChatColor.YELLOW, ChatColor.WHITE, info.getSeekerWins() +info.getHiderWins(), ChatColor.GOLD, ChatColor.WHITE, info.getHiderWins(), + ChatColor.RED, ChatColor.WHITE, info.getSeekerWins(), ChatColor.WHITE, info.getSeekerGames() +info.getHiderGames()); message = message + ChatColor.WHITE + "" + ChatColor.BOLD + "\n=============================="; sender.sendMessage(message); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java index 0070446..5c74e76 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java @@ -23,25 +23,62 @@ import java.util.UUID; public class PlayerInfo { - public final UUID uuid; - public final int hider_wins; - public final int seeker_wins; - public final int hider_games; - public final int seeker_games; - public final int hider_kills; - public final int seeker_kills; - public final int hider_deaths; - public final int seeker_deaths; + private final UUID uniqueId; + private final int hiderWins; + private final int seekerWins; + private final int hiderGames; + private final int seekerGames; + private final int hiderKills; + private final int seekerKills; + private final int hiderDeaths; + private final int seekerDeaths; - public PlayerInfo(UUID uuid, int hider_wins, int seeker_wins, int hider_games, int seeker_games, int hider_kills, int seeker_kills, int hider_deaths, int seeker_deaths) { - this.uuid = uuid; - this.hider_wins = hider_wins; - this.seeker_wins = seeker_wins; - this.hider_games = hider_games; - this.seeker_games = seeker_games; - this.hider_kills = hider_kills; - this.seeker_kills = seeker_kills; - this.hider_deaths = hider_deaths; - this.seeker_deaths = seeker_deaths; + public PlayerInfo(UUID uniqueId, int hiderWins, int seekerWins, int hiderGames, int seekerGames, int hiderKills, int seekerKills, int hiderDeaths, int seekerDeaths) { + this.uniqueId = uniqueId; + this.hiderWins = hiderWins; + this.seekerWins = seekerWins; + this.hiderGames = hiderGames; + this.seekerGames = seekerGames; + this.hiderKills = hiderKills; + this.seekerKills = seekerKills; + this.hiderDeaths = hiderDeaths; + this.seekerDeaths = seekerDeaths; } + + public UUID getUniqueId() { + return uniqueId; + } + + public int getHiderWins() { + return hiderWins; + } + + public int getSeekerWins() { + return seekerWins; + } + + public int getHiderGames() { + return hiderGames; + } + + public int getSeekerGames() { + return seekerGames; + } + + public int getHiderKills() { + return hiderKills; + } + + public int getSeekerKills() { + return seekerKills; + } + + public int getHiderDeaths() { + return hiderDeaths; + } + + public int getSeekerDeaths() { + return seekerDeaths; + } + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java index f20180b..500cdc0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java @@ -177,14 +177,14 @@ public class PlayerInfoTable { } try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { statement.setBytes(1, database.encodeUUID(uuid)); - statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); - statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); - statement.setInt(4, info.hider_games + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); - statement.setInt(5, info.seeker_games + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); - statement.setInt(6, info.hider_kills + hider_kills.getOrDefault(uuid.toString(), 0)); - statement.setInt(7, info.seeker_kills + seeker_kills.getOrDefault(uuid.toString(), 0)); - statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0)); - statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0)); + statement.setInt(2, info.getHiderWins() + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); + statement.setInt(3, info.getSeekerWins() + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); + statement.setInt(4, info.getHiderGames() + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); + statement.setInt(5, info.getSeekerGames() + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); + statement.setInt(6, info.getHiderKills() + hider_kills.getOrDefault(uuid.toString(), 0)); + statement.setInt(7, info.getSeekerKills() + seeker_kills.getOrDefault(uuid.toString(), 0)); + statement.setInt(8, info.getHiderDeaths() + hider_deaths.getOrDefault(uuid.toString(), 0)); + statement.setInt(9, info.getSeekerDeaths() + seeker_deaths.getOrDefault(uuid.toString(), 0)); statement.execute(); } catch (SQLException e) { Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index b5e7e34..896fa61 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -57,7 +57,7 @@ public class PAPIExpansion extends PlaceholderExpansion { if (args[0].equals("rank-score")) { return getValue(info, args[1]); } else { - return Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName(); + return Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); } } else if (args[0].equals("rank-place") && args.length == 2) { if (getRanking(args[1]) == null) { return placeholderError; } @@ -83,29 +83,29 @@ public class PAPIExpansion extends PlaceholderExpansion { if (query == null) return null; switch (query) { case "total-wins": - return String.valueOf(info.hider_wins + info.seeker_wins); + return String.valueOf(info.getHiderWins() + info.getSeekerWins()); case "hider-wins": - return String.valueOf(info.hider_wins); + return String.valueOf(info.getHiderWins()); case "seeker-wins": - return String.valueOf(info.seeker_wins); + return String.valueOf(info.getSeekerWins()); case "total-games": - return String.valueOf(info.hider_games + info.seeker_games); + return String.valueOf(info.getHiderGames() + info.getSeekerGames()); case "hider-games": - return String.valueOf(info.hider_games); + return String.valueOf(info.getHiderGames()); case "seeker-games": - return String.valueOf(info.seeker_games); + return String.valueOf(info.getSeekerGames()); case "total-kills": - return String.valueOf(info.hider_kills + info.seeker_kills); + return String.valueOf(info.getHiderKills() + info.getSeekerKills()); case "hider-kills": - return String.valueOf(info.hider_kills); + return String.valueOf(info.getHiderKills()); case "seeker-kills": - return String.valueOf(info.seeker_kills); + return String.valueOf(info.getSeekerKills()); case "total-deaths": - return String.valueOf(info.hider_deaths + info.seeker_deaths); + return String.valueOf(info.getHiderDeaths() + info.getSeekerDeaths()); case "hider-deaths": - return String.valueOf(info.hider_deaths); + return String.valueOf(info.getHiderDeaths()); case "seeker-deaths": - return String.valueOf(info.seeker_deaths); + return String.valueOf(info.getSeekerDeaths()); default: return null; } From 99d31ff71cecb0de3eac175384d9b55312a8a619 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Sat, 14 May 2022 08:47:54 -0500 Subject: [PATCH 47/68] refactor: clean up typos, improperly named variables --- .github/workflows/beta.yml | 2 +- .../hideAndSeek/command/SetBorder.java | 32 ++++++++--------- .../command/location/SetSpawnLocation.java | 2 +- .../hideAndSeek/configuration/Config.java | 34 +++++++++---------- .../tylermurphy/hideAndSeek/game/Board.java | 6 ++-- .../tylermurphy/hideAndSeek/game/Game.java | 14 ++++---- .../hideAndSeek/game/events/Border.java | 28 +++++++-------- .../hideAndSeek/util/CommandHandler.java | 2 +- src/main/resources/config.yml | 4 +-- src/main/resources/plugin.yml | 2 +- 10 files changed, 63 insertions(+), 63 deletions(-) diff --git a/.github/workflows/beta.yml b/.github/workflows/beta.yml index 5cf7218..80db5b7 100644 --- a/.github/workflows/beta.yml +++ b/.github/workflows/beta.yml @@ -30,7 +30,7 @@ jobs: key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - - name: Upload artificats + - name: Upload artifacts uses: actions/upload-artifact@v2 with: name: artifacts-beta diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index 8114838..3286c74 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -40,7 +40,7 @@ public class SetBorder implements ICommand { return; } if (args.length < 3) { - worldborderEnabled = false; + worldBorderEnabled = false; addToConfig("worldBorder.enabled",false); saveConfig(); sender.sendMessage(messagePrefix + message("WORLDBORDER_DISABLE")); @@ -68,26 +68,26 @@ public class SetBorder implements ICommand { sender.sendMessage(errorPrefix + message("WORLDBORDER_CHANGE_SIZE")); return; } - Vector newWorldborderPosition = new Vector(); + Vector vec = new Vector(); Player player = (Player) sender; - newWorldborderPosition.setX(player.getLocation().getBlockX()); - newWorldborderPosition.setY(0); - newWorldborderPosition.setZ(player.getLocation().getBlockZ()); - if (spawnPosition.distance(newWorldborderPosition) > 100) { + vec.setX(player.getLocation().getBlockX()); + vec.setY(0); + vec.setZ(player.getLocation().getBlockZ()); + if (spawnPosition.distance(vec) > 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); return; } - worldborderPosition = newWorldborderPosition; - worldborderSize = num; - worldborderDelay = delay; - worldborderChange = change; - worldborderEnabled = true; - addToConfig("worldBorder.x", worldborderPosition.getBlockX()); - addToConfig("worldBorder.z", worldborderPosition.getBlockZ()); - addToConfig("worldBorder.delay", worldborderDelay); - addToConfig("worldBorder.size", worldborderSize); + worldBorderPosition = vec; + worldBorderSize = num; + worldBorderDelay = delay; + worldBorderChange = change; + worldBorderEnabled = true; + addToConfig("worldBorder.x", worldBorderPosition.getBlockX()); + addToConfig("worldBorder.z", worldBorderPosition.getBlockZ()); + addToConfig("worldBorder.delay", worldBorderDelay); + addToConfig("worldBorder.size", worldBorderSize); addToConfig("worldBorder.enabled", true); - addToConfig("worldBorder.move", worldborderChange); + addToConfig("worldBorder.move", worldBorderChange); sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay)); saveConfig(); Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java index d96252d..1f454d6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java @@ -36,7 +36,7 @@ public class SetSpawnLocation implements ICommand { Player player = (Player) sender; LocationUtils.setLocation(player, Locations.GAME, vector -> { - if (worldborderEnabled && vector.distance(worldborderPosition) > 100) { + if (worldBorderEnabled && vector.distance(worldBorderPosition) > 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); throw new RuntimeException("World border not enabled or not in valid position!"); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 9fdaaa6..7ed8454 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -46,9 +46,9 @@ public class Config { messagePrefix, errorPrefix, tauntPrefix, - worldborderPrefix, + worldBorderPrefix, abortPrefix, - gameoverPrefix, + gameOverPrefix, warningPrefix, spawnWorld, exitWorld, @@ -62,13 +62,13 @@ public class Config { spawnPosition, lobbyPosition, exitPosition, - worldborderPosition; + worldBorderPosition; - public static boolean - nametagsVisible, + public static boolean + nameTagsVisible, permissionsRequired, announceMessagesToNonPlayers, - worldborderEnabled, + worldBorderEnabled, tauntEnabled, tauntCountdown, tauntLast, @@ -87,10 +87,10 @@ public class Config { public static int minPlayers, - worldborderSize, - worldborderDelay, + worldBorderSize, + worldBorderDelay, currentWorldborderSize, - worldborderChange, + worldBorderChange, gameLength, saveMinX, saveMinZ, @@ -183,15 +183,15 @@ public class Config { exitWorld = config.getString("spawns.exit.world"); //World border - worldborderPosition = new Vector( + worldBorderPosition = new Vector( config.getInt("worldBorder.x"), 0, config.getInt("worldBorder.z") ); - worldborderSize = Math.max(100, config.getInt("worldBorder.size")); - worldborderDelay = Math.max(1, config.getInt("worldBorder.delay")); - worldborderEnabled = config.getBoolean("worldBorder.enabled"); - worldborderChange = config.getInt("worldBorder.moveAmount"); + worldBorderSize = Math.max(100, config.getInt("worldBorder.size")); + worldBorderDelay = Math.max(1, config.getInt("worldBorder.delay")); + worldBorderEnabled = config.getBoolean("worldBorder.enabled"); + worldBorderChange = config.getInt("worldBorder.moveAmount"); //Prefix char SYMBOLE = '\u00A7'; @@ -200,9 +200,9 @@ public class Config { messagePrefix = config.getString("prefix.default").replace("&", SYMBOLE_STRING); errorPrefix = config.getString("prefix.error").replace("&", SYMBOLE_STRING); tauntPrefix = config.getString("prefix.taunt").replace("&", SYMBOLE_STRING); - worldborderPrefix = config.getString("prefix.border").replace("&", SYMBOLE_STRING); + worldBorderPrefix = config.getString("prefix.border").replace("&", SYMBOLE_STRING); abortPrefix = config.getString("prefix.abort").replace("&", SYMBOLE_STRING); - gameoverPrefix = config.getString("prefix.gameover").replace("&", SYMBOLE_STRING); + gameOverPrefix = config.getString("prefix.gameover").replace("&", SYMBOLE_STRING); warningPrefix = config.getString("prefix.warning").replace("&", SYMBOLE_STRING); //Map Bounds @@ -248,7 +248,7 @@ public class Config { ringingSound = ringingOptional.orElse(XSound.BLOCK_NOTE_BLOCK_PLING); //Other - nametagsVisible = config.getBoolean("nametagsVisible"); + nameTagsVisible = config.getBoolean("nametagsVisible"); permissionsRequired = config.getBoolean("permissionsRequired"); gameLength = config.getInt("gameLength"); pvpEnabled = config.getBoolean("pvp"); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 41950a1..876cb42 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -265,7 +265,7 @@ public class Board { String value = getTeam(player); board.setLine(String.valueOf(i), line.replace("{TEAM}", value)); } else if (line.contains("{BORDER}")) { - if (!worldborderEnabled) continue; + if (!worldBorderEnabled) continue; if (worldBorder == null || status == Status.STARTING) { board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replace("{AMOUNT}", "0"))); } else if (!worldBorder.isRunning()) { @@ -401,7 +401,7 @@ class CustomBoard { for(Player player : Main.getInstance().getBoard().getSeekers()) seekerTeam.addEntry(player.getName()); if (Version.atLeast("1.9")) { - if (nametagsVisible) { + if (nameTagsVisible) { hiderTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OWN_TEAM); seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OTHER_TEAMS); } else { @@ -409,7 +409,7 @@ class CustomBoard { seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER); } } else { - if (nametagsVisible) { + if (nameTagsVisible) { hiderTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OTHER_TEAMS); seekerTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OWN_TEAM); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 15341c0..e81d0e5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -303,7 +303,7 @@ public class Game { board.reloadGameBoards(); gameTimer--; } - if (worldborderEnabled) worldBorder.update(); + if (worldBorderEnabled) worldBorder.update(); if (tauntEnabled) taunt.update(); if (glowEnabled) glow.update(); } @@ -336,12 +336,12 @@ public class Game { private void checkWinConditions() { if (board.sizeHider() < 1) { if (hiderLeft) { - if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); - else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); + else broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); stop(WinType.NONE); } else { - if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); - else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); + else broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); stop(WinType.SEEKER_WIN); } } else if (board.sizeSeeker() < 1) { @@ -349,8 +349,8 @@ public class Game { else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); stop(WinType.NONE); } else if (gameTimer < 1) { - if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); - else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); + if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_TIME")); + else broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_TIME")); stop(WinType.HIDER_WIN); } hiderLeft = false; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java index aa6beca..647c4b6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Border.java @@ -13,31 +13,31 @@ public class Border { private boolean running; public Border() { - delay = 60 * worldborderDelay; + delay = 60 * worldBorderDelay; } public void update() { if (delay == 30 && !running) { - Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN")); + Main.getInstance().getGame().broadcastMessage(worldBorderPrefix + message("WORLDBORDER_WARN")); } else if (delay == 0) { if (running) { - delay = 60 * worldborderDelay; + delay = 60 * worldBorderDelay; running = false; } - else decreaceWorldborder(); + else decreaseWorldBorder(); } delay--; } - private void decreaceWorldborder() { + private void decreaseWorldBorder() { if (currentWorldborderSize == 100) return; - int change = worldborderChange; - if (currentWorldborderSize-worldborderChange < 100) { + int change = worldBorderChange; + if (currentWorldborderSize-worldBorderChange < 100) { change = currentWorldborderSize-100; } running = true; - Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change)); - currentWorldborderSize -= worldborderChange; + Main.getInstance().getGame().broadcastMessage(worldBorderPrefix + message("WORLDBORDER_DECREASING").addAmount(change)); + currentWorldborderSize -= worldBorderChange; World world = Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()); assert world != null; org.bukkit.WorldBorder border = world.getWorldBorder(); @@ -49,15 +49,15 @@ public class Border { World world = Bukkit.getWorld(worldName); assert world != null; org.bukkit.WorldBorder border = world.getWorldBorder(); - if (worldborderEnabled) { - border.setSize(worldborderSize); - border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ()); - currentWorldborderSize = worldborderSize; + if (worldBorderEnabled) { + border.setSize(worldBorderSize); + border.setCenter(worldBorderPosition.getX(), worldBorderPosition.getZ()); + currentWorldborderSize = worldBorderSize; } else { border.setSize(30000000); border.setCenter(0, 0); } - delay = 60 * worldborderDelay; + delay = 60 * worldBorderDelay; } public int getDelay() { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java index 3a05ee5..6034607 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java @@ -82,7 +82,7 @@ public class CommandHandler { try { COMMAND_REGISTER.get(args[0].toLowerCase()).execute(sender,Arrays.copyOfRange(args, 1, args.length)); } catch (Exception e) { - sender.sendMessage(errorPrefix + "An error has occured."); + sender.sendMessage(errorPrefix + "An error has occurred."); e.printStackTrace(); } } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index c509200..2d76b4a 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -94,8 +94,8 @@ leaveServer: hub # default: true mapSaveEnabled: true -# The worldborder closes every interval, which is evey [delay] in minutes. -# Thw worldborder starts at [size], and decreases 100 blocks every interval. +# The world border closes every interval, which is evey [delay] in minutes. +# Thw world border starts at [size], and decreases 100 blocks every interval. # x & z are the center location. [enabled] is whenever the border is enabled. # You can choose if Hiders are warned 30 seconds before the border moves. worldBorder: diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 93fec0d..b9ad408 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -42,7 +42,7 @@ permissions: description: Allows you to reload the config default: op hideandseek.setborder: - description: Allows you to set the game worldborder + description: Allows you to set the game world border default: op hideandseek.setspawn: description: Allows you to set the game spawn point From 90b99235257770e39a96f4d54293e4ebd7f6256c Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Sat, 14 May 2022 21:12:27 -0400 Subject: [PATCH 48/68] debug menu and 1.8/1.14 fixes --- .../hideAndSeek/command/About.java | 4 +- .../hideAndSeek/command/Debug.java | 111 ++++++++++++++++++ .../tylermurphy/hideAndSeek/command/Help.java | 4 +- .../hideAndSeek/command/ICommand.java | 4 +- .../tylermurphy/hideAndSeek/command/Join.java | 3 +- .../hideAndSeek/command/Leave.java | 3 +- .../hideAndSeek/command/Reload.java | 4 +- .../hideAndSeek/command/SaveMap.java | 4 +- .../hideAndSeek/command/SetBorder.java | 3 +- .../hideAndSeek/command/SetBounds.java | 3 +- .../hideAndSeek/command/Setup.java | 4 +- .../hideAndSeek/command/Start.java | 3 +- .../tylermurphy/hideAndSeek/command/Stop.java | 4 +- .../tylermurphy/hideAndSeek/command/Top.java | 4 +- .../tylermurphy/hideAndSeek/command/Wins.java | 3 +- .../command/location/SetExitLocation.java | 10 +- .../command/location/SetLobbyLocation.java | 10 +- .../command/location/SetSpawnLocation.java | 14 +-- .../command/location/util/LocationUtils.java | 4 +- .../command/location/util/Locations.java | 3 + .../tylermurphy/hideAndSeek/game/Board.java | 7 +- .../game/listener/InteractHandler.java | 21 +++- .../game/listener/MovementHandler.java | 1 - .../hideAndSeek/util/CommandHandler.java | 10 +- .../hideAndSeek/world/WorldLoader.java | 3 + src/main/resources/plugin.yml | 6 +- 26 files changed, 186 insertions(+), 64 deletions(-) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java index 046c2d8..f996519 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java @@ -20,11 +20,11 @@ package net.tylermurphy.hideAndSeek.command; import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; public class About implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { sender.sendMessage( String.format("%s%sHide and Seek %s(%s1.4.3%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) + String.format("%sAuthor: %s[KenshinEto]\n", ChatColor.GRAY, ChatColor.WHITE) + diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java new file mode 100644 index 0000000..a051d8e --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java @@ -0,0 +1,111 @@ +package net.tylermurphy.hideAndSeek.command; + +import com.cryptomorin.xseries.XMaterial; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; +import net.tylermurphy.hideAndSeek.game.util.Status; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +import static net.tylermurphy.hideAndSeek.configuration.Config.*; +import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition; + +public class Debug implements ICommand { + + private static final Map> debugMenuFunctions = new HashMap<>(); + private Inventory debugMenu; + + public void execute(Player sender, String[] args) { + if(debugMenu == null) createMenu(); + sender.openInventory(debugMenu); + } + + private void createMenu(){ + debugMenu = Main.getInstance().getServer().createInventory(null, 9, "Debug Menu"); + debugMenu.setItem(0, createOption(0, XMaterial.LEATHER_CHESTPLATE.parseMaterial(), "&6Become a &lHider", 1, player -> { + if(mapSaveEnabled) { + if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); + } + Main.getInstance().getBoard().addHider(player); + PlayerUtil.loadHider(player, Main.getInstance().getGame().getGameWorld()); + PlayerUtil.resetPlayer(player, Main.getInstance().getBoard()); + })); + debugMenu.setItem(1, createOption(1, XMaterial.GOLDEN_CHESTPLATE.parseMaterial(), "&cBecome a &lSeeker", 1, player -> { + if(mapSaveEnabled) { + if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); + } + Main.getInstance().getBoard().addSeeker(player); + PlayerUtil.loadSeeker(player, Main.getInstance().getGame().getGameWorld()); + PlayerUtil.resetPlayer(player, Main.getInstance().getBoard()); + })); + debugMenu.setItem(2, createOption(2, XMaterial.IRON_CHESTPLATE.parseMaterial(), "&8Become a &lSpectator", 1, player -> { + if(mapSaveEnabled) { + if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); + } + Main.getInstance().getBoard().addSpectator(player); + PlayerUtil.loadSpectator(player, Main.getInstance().getGame().getGameWorld()); + })); + debugMenu.setItem(3, createOption(3, XMaterial.BARRIER.parseMaterial(), "&cUnload from Game", 1, player -> { + Main.getInstance().getBoard().remove(player); + PlayerUtil.unloadPlayer(player); + player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + })); + debugMenu.setItem(4, createOption(4, XMaterial.BARRIER.parseMaterial(), "&cDie In Game", 2, player -> { + if((Main.getInstance().getBoard().isSeeker(player) || Main.getInstance().getBoard().isHider(player)) && Main.getInstance().getGame().getStatus() == Status.PLAYING){ + player.setHealth(0.1); + } + })); + debugMenu.setItem(6, createOption(6, Material.ENDER_PEARL, "&d&lTeleport: &fGame spawn", 1, player -> { + if(mapSaveEnabled) { + if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); + } + player.teleport(new Location(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + })); + debugMenu.setItem(7, createOption(7, Material.ENDER_PEARL, "&d&lTeleport: &fLobby", 2, player -> { + player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(), lobbyPosition.getY(), lobbyPosition.getZ())); + })); + debugMenu.setItem(8, createOption(8, Material.ENDER_PEARL, "&d&lTeleport: &fExit", 3, player -> { + player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + })); + } + + private ItemStack createOption(int slow, Material material, String name, int amount, Consumer callback){ + ItemStack temp = new ItemStack(material, amount); + ItemMeta meta = temp.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name)); + temp.setItemMeta(meta); + debugMenuFunctions.put(slow, callback); + return temp; + } + + public static void handleOption(Player player, int slotId){ + Main.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> { + Consumer callback = debugMenuFunctions.get(slotId); + if(callback != null) callback.accept(player); + }, 0); + } + + public String getLabel() { + return "debug"; + } + + public String getUsage() { + return ""; + } + + public String getDescription() { + return "Run debug commands"; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java index 11b0b0a..97224d7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Help.java @@ -21,11 +21,11 @@ package net.tylermurphy.hideAndSeek.command; import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.util.CommandHandler; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; public class Help implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { StringBuilder message = new StringBuilder(); for(ICommand command : CommandHandler.COMMAND_REGISTER.values()) { message.append(String.format("%s/hs %s%s %s%s\n %s%s%s", ChatColor.AQUA, ChatColor.WHITE, command.getLabel().toLowerCase(), ChatColor.BLUE, command.getUsage(), ChatColor.GRAY, ChatColor.ITALIC, command.getDescription() + "\n")); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/ICommand.java b/src/main/java/net/tylermurphy/hideAndSeek/command/ICommand.java index 6404c22..275d189 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/ICommand.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/ICommand.java @@ -19,11 +19,11 @@ package net.tylermurphy.hideAndSeek.command; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; public interface ICommand { - void execute(CommandSender sender, String[] args); + void execute(Player sender, String[] args); String getLabel(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java index eb8fd82..941cec0 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Join.java @@ -21,7 +21,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; @@ -29,7 +28,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Join implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java index 0b895b4..092ff50 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Leave.java @@ -21,7 +21,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; @@ -29,7 +28,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Leave implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java index 0f959f2..56f4517 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Reload.java @@ -24,7 +24,7 @@ import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.game.util.Status; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; import static net.tylermurphy.hideAndSeek.configuration.Config.messagePrefix; @@ -32,7 +32,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Reload implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java index e69c882..1e66395 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SaveMap.java @@ -23,7 +23,7 @@ import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; import org.bukkit.World; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import static net.tylermurphy.hideAndSeek.configuration.Config.*; @@ -33,7 +33,7 @@ public class SaveMap implements ICommand { public static boolean runningBackup = false; - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (!mapSaveEnabled) { sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java index 3286c74..45e66b9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBorder.java @@ -21,7 +21,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.Vector; @@ -30,7 +29,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBorder implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java index 7d2da96..90ecb28 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/SetBounds.java @@ -21,7 +21,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.*; @@ -29,7 +28,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetBounds implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) { sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java index 0bedcb5..7b29f79 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Setup.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.io.File; @@ -29,7 +29,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Setup implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { String msg = message("SETUP").toString(); int count = 0; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java index b1e5895..18bcbba 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Start.java @@ -22,7 +22,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Optional; @@ -34,7 +33,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Start implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + message("GAME_SETUP")); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java index b5f0c17..9280b53 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Stop.java @@ -21,7 +21,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.Status; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; @@ -29,7 +29,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Stop implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { if (Main.getInstance().getGame().isNotSetup()) { sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do"); return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 4f2c628..e0aa2fb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -22,7 +22,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.PlayerInfo; import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.util.List; @@ -31,7 +31,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Top implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { int page; if (args.length == 0) page = 1; else try{ diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index e12e094..bb69cd4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -22,7 +22,6 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.PlayerInfo; import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.UUID; @@ -32,7 +31,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class Wins implements ICommand { - public void execute(CommandSender sender, String[] args) { + public void execute(Player sender, String[] args) { Main.getInstance().getServer().getScheduler().runTaskAsynchronously(Main.getInstance(), () -> { UUID uuid; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java index abe6f69..93c0d8c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetExitLocation.java @@ -22,18 +22,14 @@ package net.tylermurphy.hideAndSeek.command.location; import net.tylermurphy.hideAndSeek.command.ICommand; import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; import net.tylermurphy.hideAndSeek.command.location.util.Locations; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.*; public class SetExitLocation implements ICommand { - public void execute(CommandSender sender, String[] args) { - if (!(sender instanceof Player)) return; - Player player = (Player) sender; - - LocationUtils.setLocation(player, Locations.EXIT, vector -> { - exitWorld = player.getLocation().getWorld().getName(); + public void execute(Player sender, String[] args) { + LocationUtils.setLocation(sender, Locations.EXIT, vector -> { + exitWorld = sender.getLocation().getWorld().getName(); exitPosition = vector; }); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java index fab7076..eb228f9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetLobbyLocation.java @@ -22,19 +22,15 @@ package net.tylermurphy.hideAndSeek.command.location; import net.tylermurphy.hideAndSeek.command.ICommand; import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; import net.tylermurphy.hideAndSeek.command.location.util.Locations; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.*; public class SetLobbyLocation implements ICommand { - public void execute(CommandSender sender, String[] args) { - if (!(sender instanceof Player)) return; - Player player = (Player) sender; - - LocationUtils.setLocation(player, Locations.LOBBY, vector -> { - lobbyWorld = player.getLocation().getWorld().getName(); + public void execute(Player sender, String[] args) { + LocationUtils.setLocation(sender, Locations.LOBBY, vector -> { + lobbyWorld = sender.getLocation().getWorld().getName(); lobbyPosition = vector; }); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java index 1f454d6..5ecfb8d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/SetSpawnLocation.java @@ -23,7 +23,6 @@ import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.command.ICommand; import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils; import net.tylermurphy.hideAndSeek.command.location.util.Locations; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import static net.tylermurphy.hideAndSeek.configuration.Config.*; @@ -31,22 +30,19 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message; public class SetSpawnLocation implements ICommand { - public void execute(CommandSender sender, String[] args) { - if (!(sender instanceof Player)) return; - Player player = (Player) sender; - - LocationUtils.setLocation(player, Locations.GAME, vector -> { + public void execute(Player sender, String[] args) { + LocationUtils.setLocation(sender, Locations.GAME, vector -> { if (worldBorderEnabled && vector.distance(worldBorderPosition) > 100) { sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION")); throw new RuntimeException("World border not enabled or not in valid position!"); } - if (!player.getLocation().getWorld().getName().equals(spawnWorld)) { + if (!sender.getLocation().getWorld().getName().equals(spawnWorld)) { Main.getInstance().getGame().getWorldLoader().unloadMap(); - Main.getInstance().getGame().getWorldLoader().setNewMap(player.getLocation().getWorld().getName()); + Main.getInstance().getGame().getWorldLoader().setNewMap(sender.getLocation().getWorld().getName()); } - spawnWorld = player.getLocation().getWorld().getName(); + spawnWorld = sender.getLocation().getWorld().getName(); spawnPosition = vector; }); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java index e0fc033..50d1776 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/LocationUtils.java @@ -1,7 +1,6 @@ package net.tylermurphy.hideAndSeek.command.location.util; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Location; import org.bukkit.World; @@ -14,6 +13,9 @@ import java.util.function.Consumer; import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Localization.message; +/** + * @author bobby29831 + */ public class LocationUtils { /** diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java index bde5456..59e1517 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java @@ -1,5 +1,8 @@ package net.tylermurphy.hideAndSeek.command.location.util; +/** + * @author bobby29831 + */ public enum Locations { GAME("spawns.game", "GAME_SPAWN"), diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 876cb42..f13942f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -27,7 +27,6 @@ import net.tylermurphy.hideAndSeek.game.util.Status; import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Bukkit; import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.scoreboard.*; @@ -48,10 +47,6 @@ public class Board { return playerList.containsKey(player.getUniqueId().toString()); } - public boolean contains(CommandSender sender) { - return contains((Player) sender); - } - public boolean isHider(Player player) { return Hider.contains(player.getUniqueId().toString()); } @@ -203,7 +198,7 @@ public class Board { private void createLobbyBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); - if (recreate) { + if (recreate || board == null) { board = new CustomBoard(player, LOBBY_TITLE); board.updateTeams(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java index 7fe924f..4e30a50 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -3,8 +3,13 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.messages.ActionBar; import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.command.Debug; +import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; import net.tylermurphy.hideAndSeek.game.util.Status; +import net.tylermurphy.hideAndSeek.game.util.Version; +import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -110,7 +115,7 @@ public class InteractHandler implements Listener { private ItemStack getSkull(Player player, List lore){ assert XMaterial.PLAYER_HEAD.parseMaterial() != null; - ItemStack playerhead = new ItemStack(XMaterial.PLAYER_HEAD.parseMaterial(), 1); + ItemStack playerhead = new ItemStack(XMaterial.PLAYER_HEAD.parseMaterial(), 1, (byte) 3); SkullMeta playerheadmeta = (SkullMeta) playerhead.getItemMeta(); playerheadmeta.setOwner(player.getName()); playerheadmeta.setDisplayName(player.getName()); @@ -123,9 +128,11 @@ public class InteractHandler implements Listener { public void onInventoryClick(InventoryClickEvent event) { if (event.getWhoClicked() instanceof Player) { Player player = (Player) event.getWhoClicked(); + // Block players from moving lobby items if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { event.setCancelled(true); } + // Spectator Teleport Menu if (Main.getInstance().getBoard().isSpectator(player) && event.getCurrentItem().getType() == XMaterial.PLAYER_HEAD.parseMaterial()) { event.setCancelled(true); player.closeInventory(); @@ -134,6 +141,18 @@ public class InteractHandler implements Listener { if(clicked == null) return; player.teleport(clicked); } + // Debug Menu + boolean debug = false; + if(Version.atLeast("1.14")){ + debug = event.getView().getTitle().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); + } else { + debug = event.getInventory().getName().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); + } + if (debug){ + event.setCancelled(true); + player.closeInventory(); + Debug.handleOption(player, event.getRawSlot()); + } } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java index aafc529..aba8275 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java @@ -22,7 +22,6 @@ public class MovementHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onMove(PlayerMoveEvent event) { if (event.getTo() == null || event.getTo().getWorld() == null) return; - checkJumping(event); checkBounds(event); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java index 6034607..1f0c8a3 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/CommandHandler.java @@ -62,16 +62,20 @@ public class CommandHandler { registerCommand(new Leave()); registerCommand(new Top()); registerCommand(new Wins()); + registerCommand(new Debug()); } public static boolean handleCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(errorPrefix + message("COMMAND_PLAYER_ONLY")); - } else if (args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) { + return true; + } + Player player = (Player) sender; + if (args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) { if (permissionsRequired && !sender.hasPermission("hideandseek.about")) { sender.sendMessage(errorPrefix + LOCAL.get("")); } else { - COMMAND_REGISTER.get("about").execute(sender, null); + COMMAND_REGISTER.get("about").execute(player, null); } } else { if (!args[0].equalsIgnoreCase("about") && !args[0].equalsIgnoreCase("help") && SaveMap.runningBackup) { @@ -80,7 +84,7 @@ public class CommandHandler { sender.sendMessage(errorPrefix + message("COMMAND_NOT_ALLOWED")); } else { try { - COMMAND_REGISTER.get(args[0].toLowerCase()).execute(sender,Arrays.copyOfRange(args, 1, args.length)); + COMMAND_REGISTER.get(args[0].toLowerCase()).execute(player,Arrays.copyOfRange(args, 1, args.length)); } catch (Exception e) { sender.sendMessage(errorPrefix + "An error has occurred."); e.printStackTrace(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index 193c34e..21b6a76 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -95,6 +95,9 @@ public class WorldLoader { throw new RuntimeException("Failed to create directory: "+destenation.getPath()); } } + if(!destenation.delete()){ + throw new RuntimeException("Unable to delete folder: "+destenation.getPath()); + } if (!temp_destenation.renameTo(destenation)) { throw new RuntimeException("Failed to rename directory: "+temp_destenation.getPath()); } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index b9ad408..74c4855 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -31,7 +31,8 @@ permissions: hideandseek.leave: true hideandseek.leavebounds: true hideandseek.wins: true - hideand.top: true + hideandseek.top: true + hideandseek.debug: true hideandseek.about: description: Allows you to run the about command default: true @@ -83,3 +84,6 @@ permissions: hideandseek.top: description: Allows players to see the global wins leaderboard default: true + hideandseek.debug: + description: Opens the debug menu + default: op From d6f1cce234aa2a0b1628e3fbebec8ec40b258e78 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Sat, 14 May 2022 22:25:24 -0500 Subject: [PATCH 49/68] refactor: simplify Locations.java class --- .../command/location/util/Locations.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java index bde5456..ff44546 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/location/util/Locations.java @@ -2,22 +2,17 @@ package net.tylermurphy.hideAndSeek.command.location.util; public enum Locations { - GAME("spawns.game", "GAME_SPAWN"), - LOBBY("spawns.lobby", "LOBBY_SPAWN"), - EXIT("spawns.exit", "EXIT_SPAWN"); + GAME("spawns.game"), + LOBBY("spawns.lobby"), + EXIT("spawns.exit"); - private final String path, message; - Locations(String path, String message) { + private final String path; + Locations(String path) { this.path = path; - this.message = message; } public String message() { - return message; - } - - public String path() { - return path; + return this + "_SPAWN"; } public String path(String additive) { From 416e459af261994ad702462812c29d55da8cb2d5 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Mon, 16 May 2022 13:56:52 -0400 Subject: [PATCH 50/68] refactor: Jump Event, InventoryHandler, Relocate One function Utility Classes, Config Manager Getters Use Contains() --- .../net/tylermurphy/hideAndSeek/Main.java | 15 ++++ .../hideAndSeek/command/Debug.java | 15 ++-- .../hideAndSeek/configuration/Config.java | 11 ++- .../configuration/ConfigManager.java | 15 ++-- .../hideAndSeek/configuration/Items.java | 9 +-- .../tylermurphy/hideAndSeek/game/Board.java | 7 +- .../tylermurphy/hideAndSeek/game/Game.java | 16 ++-- .../PlayerUtil.java => PlayerLoader.java} | 30 ++++++-- .../hideAndSeek/game/events/Glow.java | 33 +++++++- .../game/listener/DamageHandler.java | 9 +-- .../game/listener/InteractHandler.java | 39 ---------- .../game/listener/InventoryHandler.java | 77 +++++++++++++++++++ .../game/listener/MovementHandler.java | 12 ++- .../game/listener/events/PlayerJumpEvent.java | 49 ++++++++++++ .../hideAndSeek/game/util/Packet.java | 56 -------------- .../hideAndSeek/game/util/Version.java | 45 ----------- 16 files changed, 241 insertions(+), 197 deletions(-) rename src/main/java/net/tylermurphy/hideAndSeek/game/{util/PlayerUtil.java => PlayerLoader.java} (85%) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/InventoryHandler.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java delete mode 100644 src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index fc4b2cc..2737e81 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -39,10 +39,13 @@ import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class Main extends JavaPlugin implements Listener { private static Main instance; + private static int version; private Database database; private Board board; @@ -72,6 +75,13 @@ public class Main extends JavaPlugin implements Listener { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new PAPIExpansion().register(); } + + Matcher matcher = Pattern.compile("MC: \\d\\.(\\d+)").matcher(Bukkit.getVersion()); + if (matcher.find()) { + version = Integer.parseInt(matcher.group(1)); + } else { + throw new IllegalArgumentException("Failed to parse server version from: " + Bukkit.getVersion()); + } } public void onDisable() { @@ -89,6 +99,7 @@ public class Main extends JavaPlugin implements Listener { getServer().getPluginManager().registerEvents(new ChatHandler(), this); getServer().getPluginManager().registerEvents(new DamageHandler(), this); getServer().getPluginManager().registerEvents(new InteractHandler(), this); + getServer().getPluginManager().registerEvents(new InventoryHandler(), this); getServer().getPluginManager().registerEvents(new JoinLeaveHandler(), this); getServer().getPluginManager().registerEvents(new MovementHandler(), this); getServer().getPluginManager().registerEvents(new PlayerHandler(), this); @@ -122,5 +133,9 @@ public class Main extends JavaPlugin implements Listener { public Game getGame(){ return game; } + + public boolean supports(int v){ + return version >= v; + } } \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java index a051d8e..c1cec56 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java @@ -2,14 +2,13 @@ package net.tylermurphy.hideAndSeek.command; import com.cryptomorin.xseries.XMaterial; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; +import net.tylermurphy.hideAndSeek.game.PlayerLoader; import net.tylermurphy.hideAndSeek.game.util.Status; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -38,27 +37,27 @@ public class Debug implements ICommand { if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); } Main.getInstance().getBoard().addHider(player); - PlayerUtil.loadHider(player, Main.getInstance().getGame().getGameWorld()); - PlayerUtil.resetPlayer(player, Main.getInstance().getBoard()); + PlayerLoader.loadHider(player, Main.getInstance().getGame().getGameWorld()); + PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); })); debugMenu.setItem(1, createOption(1, XMaterial.GOLDEN_CHESTPLATE.parseMaterial(), "&cBecome a &lSeeker", 1, player -> { if(mapSaveEnabled) { if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); } Main.getInstance().getBoard().addSeeker(player); - PlayerUtil.loadSeeker(player, Main.getInstance().getGame().getGameWorld()); - PlayerUtil.resetPlayer(player, Main.getInstance().getBoard()); + PlayerLoader.loadSeeker(player, Main.getInstance().getGame().getGameWorld()); + PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); })); debugMenu.setItem(2, createOption(2, XMaterial.IRON_CHESTPLATE.parseMaterial(), "&8Become a &lSpectator", 1, player -> { if(mapSaveEnabled) { if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap(); } Main.getInstance().getBoard().addSpectator(player); - PlayerUtil.loadSpectator(player, Main.getInstance().getGame().getGameWorld()); + PlayerLoader.loadSpectator(player, Main.getInstance().getGame().getGameWorld()); })); debugMenu.setItem(3, createOption(3, XMaterial.BARRIER.parseMaterial(), "&cUnload from Game", 1, player -> { Main.getInstance().getBoard().remove(player); - PlayerUtil.unloadPlayer(player); + PlayerLoader.unloadPlayer(player); player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); })); debugMenu.setItem(4, createOption(4, XMaterial.BARRIER.parseMaterial(), "&cDie In Game", 2, player -> { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 7ed8454..03d7504 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -24,7 +24,6 @@ import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XSound; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.util.CountdownDisplay; -import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -160,7 +159,7 @@ public class Config { //Spawn spawnPosition = new Vector( config.getDouble("spawns.game.x"), - Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.game.y"))), + Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.game.y"))), config.getDouble("spawns.game.z") ); spawnWorld = config.getString("spawns.game.world"); @@ -168,7 +167,7 @@ public class Config { ///Lobby lobbyPosition = new Vector( config.getDouble("spawns.lobby.x"), - Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.lobby.y"))), + Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.lobby.y"))), config.getDouble("spawns.lobby.z") ); lobbyWorld = config.getString("spawns.lobby.world"); @@ -177,7 +176,7 @@ public class Config { exitPosition = new Vector( config.getDouble("spawns.exit.x"), - Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.exit.y"))), + Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.exit.y"))), config.getDouble("spawns.exit.z") ); exitWorld = config.getString("spawns.exit.world"); @@ -221,7 +220,7 @@ public class Config { //Glow glowLength = Math.max(1, config.getInt("glow.time")); glowStackable = config.getBoolean("glow.stackable"); - glowEnabled = config.getBoolean("glow.enabled") && Version.atLeast("1.9"); + glowEnabled = config.getBoolean("glow.enabled") && Main.getInstance().supports(9); if (glowEnabled) { glowPowerupItem = createItemStack("glow"); } @@ -330,7 +329,7 @@ public class Config { ConfigurationSection item = new YamlConfiguration().createSection("temp"); item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString(path+".name"))); item.set("material", config.getString(path+".material")); - if (Version.atLeast("1.14")) { + if (Main.getInstance().supports(14)) { if (config.contains(path+".model-data") && config.getInt(path+".model-data") != 0) { item.set("model-data", config.getInt(path+".model-data")); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 3a95fe9..f02eaba 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -112,20 +112,18 @@ public class ConfigManager { } public double getDouble(String path) { - double value = config.getDouble(path); - if (value == 0.0D) { + if (!config.contains(path)) { return defaultConfig.getDouble(path); } else { - return value; + return config.getDouble(path); } } public int getInt(String path) { - int value = config.getInt(path); - if (value == 0) { + if (!config.contains(path)) { return defaultConfig.getInt(path); } else { - return value; + return config.getInt(path); } } @@ -134,11 +132,10 @@ public class ConfigManager { } public float getFloat(String path) { - float value = (float) config.getDouble(path); - if (value == 0.0F) { + if (!config.contains(path)) { return (float) defaultConfig.getDouble(path); } else { - return value; + return (float) config.getDouble(path); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java index 18a31b2..dfdb197 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Items.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.configuration; import com.cryptomorin.xseries.XItemStack; -import net.tylermurphy.hideAndSeek.game.util.Version; +import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; @@ -30,7 +30,6 @@ import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.List; -import java.util.Objects; public class Items { @@ -90,7 +89,7 @@ public class Items { ConfigurationSection config = new YamlConfiguration().createSection("temp"); String material = item.getString("material").toUpperCase(); boolean splash = false; - if (!Version.atLeast("1.9")) { + if (!Main.getInstance().supports(9)) { if (material.contains("POTION")) { config.set("level", 1); } @@ -103,7 +102,7 @@ public class Items { config.set("material", material); config.set("enchants", item.getConfigurationSection("enchantments")); config.set("unbreakable", item.getBoolean("unbreakable")); - if (Version.atLeast("1.14")) { + if (Main.getInstance().supports(14)) { if (item.contains("model-data")) { config.set("model-data", item.getInt("model-data")); } @@ -123,7 +122,7 @@ public class Items { if (type == null) return null; if (PotionEffectType.getByName(type.toUpperCase()) == null) return null; return new PotionEffect( - Objects.requireNonNull(PotionEffectType.getByName(type.toUpperCase())), + PotionEffectType.getByName(type.toUpperCase()), item.getInt("duration"), item.getInt("amplifier"), item.getBoolean("ambient"), diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index f13942f..04b0d37 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -24,7 +24,6 @@ import net.tylermurphy.hideAndSeek.game.events.Border; import net.tylermurphy.hideAndSeek.game.events.Glow; import net.tylermurphy.hideAndSeek.game.events.Taunt; import net.tylermurphy.hideAndSeek.game.util.Status; -import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -368,7 +367,7 @@ class CustomBoard { this.board = manager.getNewScoreboard(); this.LINES = new HashMap<>(); this.player = player; - if (Version.atLeast("1.13")) { + if (Main.getInstance().supports(13)) { this.obj = board.registerNewObjective( "Scoreboard", "dummy", ChatColor.translateAlternateColorCodes('&', title)); } else { @@ -395,7 +394,7 @@ class CustomBoard { seekerTeam.removeEntry(entry); for(Player player : Main.getInstance().getBoard().getSeekers()) seekerTeam.addEntry(player.getName()); - if (Version.atLeast("1.9")) { + if (Main.getInstance().supports(9)) { if (nameTagsVisible) { hiderTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OWN_TEAM); seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OTHER_TEAMS); @@ -412,7 +411,7 @@ class CustomBoard { seekerTeam.setNameTagVisibility(NameTagVisibility.NEVER); } } - if (Version.atLeast("1.12")) { + if (Main.getInstance().supports(12)) { hiderTeam.setColor(ChatColor.GOLD); seekerTeam.setColor(ChatColor.RED); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index e81d0e5..c261b52 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -119,12 +119,12 @@ public class Game { if (mapSaveEnabled) worldLoader.rollback(); board.reload(); board.addSeeker(seeker); - PlayerUtil.loadSeeker(seeker, getGameWorld()); + PlayerLoader.loadSeeker(seeker, getGameWorld()); board.getPlayers().forEach(player -> { board.createGameBoard(player); if(board.isSeeker(player)) return; board.addHider(player); - PlayerUtil.loadHider(player, getGameWorld()); + PlayerLoader.loadHider(player, getGameWorld()); }); worldBorder.resetWorldBorder(getGameWorld()); if (gameLength > 0) gameTimer = gameLength; @@ -147,7 +147,7 @@ public class Game { } public void end() { - board.getPlayers().forEach(PlayerUtil::unloadPlayer); + board.getPlayers().forEach(PlayerLoader::unloadPlayer); worldBorder.resetWorldBorder(getGameWorld()); board.getPlayers().forEach(player -> { if (leaveOnEnd) { @@ -158,7 +158,7 @@ public class Game { player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); board.createLobbyBoard(player); board.addHider(player); - PlayerUtil.joinPlayer(player); + PlayerLoader.joinPlayer(player); } }); RespawnHandler.temp_loc.clear(); @@ -169,14 +169,14 @@ public class Game { public void join(Player player) { if (status != Status.STARTING && status != Status.PLAYING) { - PlayerUtil.joinPlayer(player); + PlayerLoader.joinPlayer(player); board.addHider(player); board.createLobbyBoard(player); board.reloadLobbyBoards(); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); else broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player)); } else { - PlayerUtil.loadSpectator(player, getGameWorld()); + PlayerLoader.loadSpectator(player, getGameWorld()); board.addSpectator(player); board.createGameBoard(player); player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); @@ -184,7 +184,7 @@ public class Game { } public void leave(Player player) { - PlayerUtil.unloadPlayer(player); + PlayerLoader.unloadPlayer(player); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); else broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player)); if (board.isHider(player) && status != Status.ENDING && status != Status.STANDBY) { @@ -247,7 +247,7 @@ public class Game { if (startingTimer == 0) { message = message("START").toString(); status = Status.PLAYING; - board.getPlayers().forEach(player -> PlayerUtil.resetPlayer(player, board)); + board.getPlayers().forEach(player -> PlayerLoader.resetPlayer(player, board)); } else { message = message("START_COUNTDOWN").addAmount(startingTimer).toString(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java similarity index 85% rename from src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java rename to src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java index 59c7b73..0ce7ac7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/util/PlayerUtil.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java @@ -1,10 +1,28 @@ -package net.tylermurphy.hideAndSeek.game.util; +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.game; import com.cryptomorin.xseries.messages.Titles; import net.md_5.bungee.api.ChatColor; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.configuration.Items; -import net.tylermurphy.hideAndSeek.game.Board; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -19,7 +37,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Config.lobbyPosition; import static net.tylermurphy.hideAndSeek.configuration.Localization.message; -public class PlayerUtil { +public class PlayerLoader { public static void loadHider(Player player, String gameWorld){ player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); @@ -77,11 +95,11 @@ public class PlayerUtil { for(PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } - if (Version.atLeast("1.9")) { + if (Main.getInstance().supports(9)) { AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); if (attribute != null) player.setHealth(attribute.getValue()); for(Player temp : Main.getInstance().getBoard().getPlayers()) { - Packet.setGlow(player, temp, false); + Main.getInstance().getGame().getGlow().setGlow(player, temp, false); } } else { player.setHealth(player.getMaxHealth()); @@ -111,7 +129,7 @@ public class PlayerUtil { player.removePotionEffect(effect.getType()); } player.setFoodLevel(20); - if (Version.atLeast("1.9")) { + if (Main.getInstance().supports(9)) { AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); if (attribute != null) player.setHealth(attribute.getValue()); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java index a0031e5..a1d7295 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java @@ -1,14 +1,22 @@ package net.tylermurphy.hideAndSeek.game.events; +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.game.util.Packet; import org.bukkit.entity.Player; +import java.lang.reflect.InvocationTargetException; + import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength; import static net.tylermurphy.hideAndSeek.configuration.Config.glowStackable; public class Glow { + private static final ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); + private int glowTime; private boolean running; @@ -25,7 +33,7 @@ public class Glow { private void sendPackets() { for (Player hider : Main.getInstance().getBoard().getHiders()) for (Player seeker : Main.getInstance().getBoard().getSeekers()) - Packet.setGlow(hider, seeker, true); + setGlow(hider, seeker, true); } public void update() { @@ -43,7 +51,7 @@ public class Glow { running = false; for (Player hider : Main.getInstance().getBoard().getHiders()) { for (Player seeker : Main.getInstance().getBoard().getSeekers()) { - Packet.setGlow(hider, seeker, false); + setGlow(hider, seeker, false); } } } @@ -52,4 +60,23 @@ public class Glow { return running; } + public void setGlow(Player player, Player target, boolean glowing) { + PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.ENTITY_METADATA); + packet.getIntegers().write(0, target.getEntityId()); + WrappedDataWatcher watcher = new WrappedDataWatcher(); + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); + watcher.setEntity(target); + if (glowing) { + watcher.setObject(0, serializer, (byte) (0x40)); + } else { + watcher.setObject(0, serializer, (byte) (0x0)); + } + packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); + try { + protocolManager.sendServerPacket(player, packet); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index ee63cc2..701f446 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -4,9 +4,8 @@ import com.cryptomorin.xseries.XSound; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Game; -import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; +import net.tylermurphy.hideAndSeek.game.PlayerLoader; import net.tylermurphy.hideAndSeek.game.util.Status; -import net.tylermurphy.hideAndSeek.game.util.Version; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -70,7 +69,7 @@ public class DamageHandler implements Listener { // Spectators cannot take damage if (board.isSpectator(player)) { event.setCancelled(true); - if (Version.atLeast("1.18") && player.getLocation().getY() < -64) { + if (Main.getInstance().supports(18) && player.getLocation().getY() < -64) { player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); } else if (player.getLocation().getY() < 0) { player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); @@ -87,7 +86,7 @@ public class DamageHandler implements Listener { // Handle death event event.setCancelled(true); // Play death effect - if (Version.atLeast("1.9")) { + if (Main.getInstance().supports(9)) { XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1); } else { XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); @@ -112,7 +111,7 @@ public class DamageHandler implements Listener { // Add leaderboard kills if attacker if (attacker != null && ( board.isHider(attacker) || board.getFirstSeeker().getName().equals(attacker.getName()) ) ) board.addKill(attacker.getUniqueId()); - PlayerUtil.resetPlayer(player, board); + PlayerLoader.resetPlayer(player, board); board.reloadBoardTeams(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java index 4e30a50..c8dd488 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InteractHandler.java @@ -3,19 +3,13 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.messages.ActionBar; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.command.Debug; -import net.tylermurphy.hideAndSeek.game.util.PlayerUtil; import net.tylermurphy.hideAndSeek.game.util.Status; -import net.tylermurphy.hideAndSeek.game.util.Version; -import org.bukkit.Bukkit; import org.bukkit.ChatColor; -import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; -import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; @@ -123,37 +117,4 @@ public class InteractHandler implements Listener { playerhead.setItemMeta(playerheadmeta); return playerhead; } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(InventoryClickEvent event) { - if (event.getWhoClicked() instanceof Player) { - Player player = (Player) event.getWhoClicked(); - // Block players from moving lobby items - if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { - event.setCancelled(true); - } - // Spectator Teleport Menu - if (Main.getInstance().getBoard().isSpectator(player) && event.getCurrentItem().getType() == XMaterial.PLAYER_HEAD.parseMaterial()) { - event.setCancelled(true); - player.closeInventory(); - String name = event.getCurrentItem().getItemMeta().getDisplayName(); - Player clicked = Main.getInstance().getServer().getPlayer(name); - if(clicked == null) return; - player.teleport(clicked); - } - // Debug Menu - boolean debug = false; - if(Version.atLeast("1.14")){ - debug = event.getView().getTitle().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); - } else { - debug = event.getInventory().getName().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); - } - if (debug){ - event.setCancelled(true); - player.closeInventory(); - Debug.handleOption(player, event.getRawSlot()); - } - } - } - } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InventoryHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InventoryHandler.java new file mode 100644 index 0000000..f0fb4f9 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/InventoryHandler.java @@ -0,0 +1,77 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.game.listener; + +import com.cryptomorin.xseries.XMaterial; +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.command.Debug; +import net.tylermurphy.hideAndSeek.game.util.Status; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; + +public class InventoryHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + + Player player = (Player) event.getWhoClicked(); + checkForInventoryMove(event); + checkForSpectatorTeleportMenu(event); + checkForDebugMenu(event); + } + + private void checkForInventoryMove(InventoryClickEvent event){ + if (Main.getInstance().getBoard().contains((Player) event.getWhoClicked()) && Main.getInstance().getGame().getStatus() == Status.STANDBY) { + event.setCancelled(true); + } + } + + private void checkForSpectatorTeleportMenu(InventoryClickEvent event){ + Player player = (Player) event.getWhoClicked(); + if (Main.getInstance().getBoard().isSpectator(player) && event.getCurrentItem().getType() == XMaterial.PLAYER_HEAD.parseMaterial()) { + event.setCancelled(true); + player.closeInventory(); + String name = event.getCurrentItem().getItemMeta().getDisplayName(); + Player clicked = Main.getInstance().getServer().getPlayer(name); + if(clicked == null) return; + player.teleport(clicked); + } + } + + private void checkForDebugMenu(InventoryClickEvent event){ + Player player = (Player) event.getWhoClicked(); + boolean debug; + if(Main.getInstance().supports(14)){ + debug = event.getView().getTitle().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); + } else { + debug = event.getInventory().getName().equals("Debug Menu") && player.hasPermission("hideandseek.debug"); + } + if (debug){ + event.setCancelled(true); + player.closeInventory(); + Debug.handleOption(player, event.getRawSlot()); + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java index aba8275..7a7e8ae 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/MovementHandler.java @@ -3,6 +3,7 @@ package net.tylermurphy.hideAndSeek.game.listener; import com.comphenix.protocol.PacketType; import com.google.common.collect.Sets; import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.game.listener.events.PlayerJumpEvent; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -26,13 +27,18 @@ public class MovementHandler implements Listener { checkBounds(event); } + @EventHandler(priority = EventPriority.HIGHEST) + public void onJump(PlayerJumpEvent event) { + if(Main.getInstance().getBoard().isSpectator(event.getPlayer()) && event.getPlayer().getAllowFlight()) { + event.getPlayer().setFlying(true); + } + } + private void checkJumping(PlayerMoveEvent event){ - if (!Main.getInstance().getBoard().isSpectator(event.getPlayer())) return; if (event.getPlayer().getVelocity().getY() > 0) { if (event.getPlayer().getLocation().getBlock().getType() != Material.LADDER && prevPlayersOnGround.contains(event.getPlayer().getUniqueId())) { if (!event.getPlayer().isOnGround()) { - // JUMPING :o - if(event.getPlayer().getAllowFlight()) event.getPlayer().setFlying(true); + Main.getInstance().getServer().getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer())); } } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java new file mode 100644 index 0000000..f42a33c --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java @@ -0,0 +1,49 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.game.listener.events; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class PlayerJumpEvent extends PlayerEvent implements Cancellable { + + private boolean cancel = false; + + public PlayerJumpEvent(Player player) { + super(player); + } + + @Override + public boolean isCancelled() { + return cancel; + } + + @Override + public void setCancelled(boolean b) { + this.cancel = !b; + } + + @Override + public HandlerList getHandlers() { + return null; + } +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java deleted file mode 100644 index 0fad539..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/util/Packet.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2021 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package net.tylermurphy.hideAndSeek.game.util; - -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedDataWatcher; -import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; -import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; - -public class Packet { - - private static final ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager(); - - public static void setGlow(Player player, Player target, boolean glowing) { - PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.ENTITY_METADATA); - packet.getIntegers().write(0, target.getEntityId()); - WrappedDataWatcher watcher = new WrappedDataWatcher(); - Serializer serializer = Registry.get(Byte.class); - watcher.setEntity(target); - if (glowing) { - watcher.setObject(0, serializer, (byte) (0x40)); - } else { - watcher.setObject(0, serializer, (byte) (0x0)); - } - packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); - try { - protocolManager.sendServerPacket(player, packet); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java b/src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java deleted file mode 100644 index e2dcfdd..0000000 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/util/Version.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.tylermurphy.hideAndSeek.game.util; - -import org.bukkit.Bukkit; - -import java.util.HashMap; -import java.util.Map; - -public class Version { - - private static final Map CACHE = new HashMap<>(); - - public static boolean atLeast(String testVersion) { - - - if (CACHE.containsKey(testVersion)) return CACHE.get(testVersion); - - String[] serverCheckTemp = Bukkit.getBukkitVersion().substring(2,Bukkit.getBukkitVersion().indexOf('-')).split("\\."); - int[] serverCheck = new int[serverCheckTemp.length]; - for(int i=0; i serverCheck[0]) return false; - else if (customCheck[0] < serverCheck[0]) return true; - else { - if (customCheck.length == 1 && serverCheck.length == 1) return true; - else if (customCheck.length == 2 && serverCheck.length == 2) { - return customCheck[1] <= serverCheck[1]; - } - else return serverCheck.length == 2; - } - } -} From 491e426ce919ada52adc2417efae58e5a7e91267 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Mon, 16 May 2022 18:06:45 -0400 Subject: [PATCH 51/68] mapsave bug fixes for windows servers --- .../game/listener/events/PlayerJumpEvent.java | 9 ++++++- .../hideAndSeek/util/PAPIExpansion.java | 3 +++ .../hideAndSeek/world/WorldLoader.java | 26 +++++++++---------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java index f42a33c..49920f2 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/events/PlayerJumpEvent.java @@ -26,6 +26,7 @@ import org.bukkit.event.player.PlayerEvent; public class PlayerJumpEvent extends PlayerEvent implements Cancellable { + private static final HandlerList handlers = new HandlerList(); private boolean cancel = false; public PlayerJumpEvent(Player player) { @@ -44,6 +45,12 @@ public class PlayerJumpEvent extends PlayerEvent implements Cancellable { @Override public HandlerList getHandlers() { - return null; + return handlers; } + + @SuppressWarnings("unused") + public static HandlerList getHandlerList() { + return handlers; + } + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 896fa61..c1f8c2a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -41,6 +41,7 @@ public class PAPIExpansion extends PlaceholderExpansion { if (args.length < 1) return null; if (args[0].equals("stats") && args.length == 2) { PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); + if (info == null) return placeholderNoData; return getValue(info, args[1]); } else if (args[0].equals("stats") && args.length == 3) { UUID uuid; @@ -62,6 +63,7 @@ public class PAPIExpansion extends PlaceholderExpansion { } else if (args[0].equals("rank-place") && args.length == 2) { if (getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); + if (info == null) return placeholderNoData; if (getValue(info, args[1]).equals("0")) { return "-"; } Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); if (count == null) { return placeholderNoData; } @@ -71,6 +73,7 @@ public class PAPIExpansion extends PlaceholderExpansion { try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; } PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); + if (info == null) return placeholderNoData; if (getValue(info, args[1]).equals("0")) { return "-"; } Integer count = database.getGameData().getRanking(getRanking(args[1]), uuid); if (count == null) { return placeholderNoData; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index 21b6a76..ebfedcd 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -78,28 +78,28 @@ public class WorldLoader { } public String save() { + World world = Bukkit.getServer().getWorld(mapName); + if(world == null){ + throw new RuntimeException("Invalid world to save: " + mapName); + } File current = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName); if (current.exists()) { try { - File destenation = new File(Main.getInstance().getWorldContainer()+File.separator+ saveName); - File temp_destenation = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName); + File destination = new File(Main.getInstance().getWorldContainer()+File.separator+ saveName); + File temp_destination = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName); copyFileFolder("region",true); copyFileFolder("entities",true); copyFileFolder("datapacks",false); + copyFileFolder("data",false); File srcFile = new File(current, "level.dat"); - File destFile = new File(temp_destenation, "level.dat"); + File destFile = new File(temp_destination, "level.dat"); copyFile(srcFile,destFile); - if (destenation.exists()) { - deleteDirectory(destenation); - if (!destenation.mkdir()) { - throw new RuntimeException("Failed to create directory: "+destenation.getPath()); - } + if (destination.exists()) { + deleteDirectory(destination); } - if(!destenation.delete()){ - throw new RuntimeException("Unable to delete folder: "+destenation.getPath()); - } - if (!temp_destenation.renameTo(destenation)) { - throw new RuntimeException("Failed to rename directory: "+temp_destenation.getPath()); + + if (!temp_destination.renameTo(destination)) { + throw new RuntimeException("Failed to rename directory: "+temp_destination.getPath()); } } catch(IOException e) { e.printStackTrace(); From b74b8136365ca2542242023fc91e370873d6eabf Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 17 May 2022 16:36:35 -0400 Subject: [PATCH 52/68] working on expanding database --- pom.xml | 28 ++++- .../net/tylermurphy/hideAndSeek/Main.java | 27 +++-- .../tylermurphy/hideAndSeek/command/Top.java | 2 +- .../tylermurphy/hideAndSeek/command/Wins.java | 2 +- .../hideAndSeek/database/Database.java | 43 ++++---- ...layerInfoTable.java => GameDataTable.java} | 63 +++++++---- .../hideAndSeek/database/LegacyTable.java | 104 ++++++++++++++++++ .../hideAndSeek/database/NameDataTable.java | 99 +++++++++++++++++ .../connections/DatabaseConnection.java | 29 +++++ .../database/connections/MySQLConnection.java | 61 ++++++++++ .../connections/SQLiteConnection.java | 64 +++++++++++ .../database/util/LegacyPlayerInfo.java | 56 ++++++++++ .../database/{ => util}/PlayerInfo.java | 4 +- .../game/listener/JoinLeaveHandler.java | 3 + .../hideAndSeek/util/PAPIExpansion.java | 2 +- src/test/java/MainTest.java | 42 +++++++ 16 files changed, 569 insertions(+), 60 deletions(-) rename src/main/java/net/tylermurphy/hideAndSeek/database/{PlayerInfoTable.java => GameDataTable.java} (74%) create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/LegacyTable.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/connections/DatabaseConnection.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/connections/SQLiteConnection.java create mode 100644 src/main/java/net/tylermurphy/hideAndSeek/database/util/LegacyPlayerInfo.java rename src/main/java/net/tylermurphy/hideAndSeek/database/{ => util}/PlayerInfo.java (95%) create mode 100644 src/test/java/MainTest.java diff --git a/pom.xml b/pom.xml index 8073d7a..fff9f6c 100644 --- a/pom.xml +++ b/pom.xml @@ -30,18 +30,18 @@ - - org.spigotmc:spigot-api - com.comphenix.protocol:ProtocolLib - org.jetbrains:annotations - net.bytebuddy:byte-buddy - + + com.github.cryptomorin:XSeries + org.xerial:sqlite-jdbc + com.zaxxer:HikariCP + *:* META-INF/*.MF + META-INF/*.md META-INF sqlite-jdbc.properties @@ -113,5 +113,21 @@ 2.11.1 provided + + com.zaxxer + HikariCP + 5.0.1 + + + org.junit.jupiter + junit-jupiter + 5.9.0-M1 + + + com.github.seeseemelk + MockBukkit-v1.17 + 1.13.0 + test + \ No newline at end of file diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index 2737e81..126deaa 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -19,6 +19,7 @@ package net.tylermurphy.hideAndSeek; +import jdk.jpackage.internal.IOUtils; import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; @@ -34,7 +35,9 @@ import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.Listener; +import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.java.JavaPluginLoader; import org.jetbrains.annotations.NotNull; import java.io.File; @@ -47,13 +50,26 @@ public class Main extends JavaPlugin implements Listener { private static Main instance; private static int version; - private Database database; - private Board board; + private final Database database; + private final Board board; + private Game game; - public void onEnable() { - + public Main() { + super(); instance = this; + board = new Board(); + database = new Database(); + } + + protected Main(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { + super(loader, description, dataFolder, file); + instance = this; + board = new Board(); + database = new Database(); + } + + public void onEnable() { this.registerListeners(); @@ -63,9 +79,6 @@ public class Main extends JavaPlugin implements Listener { CommandHandler.registerCommands(); - board = new Board(); - database = new Database(); - game = new Game(board); getServer().getScheduler().runTaskTimer(this, this::onTick,0,1).getTaskId(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index e0aa2fb..caa751b 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.database.PlayerInfo; +import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import org.bukkit.ChatColor; import org.bukkit.entity.Player; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index bb69cd4..8a0b6dc 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -20,7 +20,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; -import net.tylermurphy.hideAndSeek.database.PlayerInfo; +import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import org.bukkit.ChatColor; import org.bukkit.entity.Player; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index ce06244..0eceb98 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -21,48 +21,51 @@ package net.tylermurphy.hideAndSeek.database; import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; -import org.sqlite.SQLiteConfig; +import net.tylermurphy.hideAndSeek.database.connections.DatabaseConnection; +import net.tylermurphy.hideAndSeek.database.connections.SQLiteConnection; import java.io.ByteArrayInputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.util.UUID; public class Database { - private final File databaseFile = new File(Main.getInstance().getDataFolder(), "database.db"); - private final PlayerInfoTable playerInfo; - private final SQLiteConfig config; + private final GameDataTable playerInfo; + private final NameDataTable nameInfo; + private final DatabaseConnection connection; public Database(){ - try { - Class.forName("org.sqlite.JDBC"); - } catch (ClassNotFoundException e) { - Main.getInstance().getLogger().severe(e.getMessage()); - throw new RuntimeException(e.getMessage()); + + connection = new SQLiteConnection(); + + playerInfo = new GameDataTable(this); + + nameInfo = new NameDataTable(this); + + LegacyTable legacyTable = new LegacyTable(this); + if(legacyTable.exists()){ + if(legacyTable.copyData()){ + if(!legacyTable.drop()){ + Main.getInstance().getLogger().severe("Failed to drop old legacy table: player_info. Some data may be duplicated!"); + } + } } - - config = new SQLiteConfig(); - config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); - config.setTempStore(SQLiteConfig.TempStore.MEMORY); - - playerInfo = new PlayerInfoTable(this); } - public PlayerInfoTable getGameData(){ + public GameDataTable getGameData(){ return playerInfo; } + public NameDataTable getNameData() { return nameInfo; } + protected Connection connect() { Connection conn = null; try { - String url = "jdbc:sqlite:"+databaseFile; - conn = DriverManager.getConnection(url, config.toProperties()); + conn = connection.connect(); } catch (SQLException e) { Main.getInstance().getLogger().severe(e.getMessage()); e.printStackTrace(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java similarity index 74% rename from src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java rename to src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java index 500cdc0..128614d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfoTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java @@ -1,7 +1,7 @@ /* * This file is part of Kenshins Hide and Seek * - * Copyright (c) 2021 Tyler Murphy. + * Copyright (c) 2021-2022 Tyler Murphy. * * Kenshins Hide and Seek free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,6 +20,7 @@ package net.tylermurphy.hideAndSeek.database; import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.util.WinType; import org.jetbrains.annotations.Nullable; @@ -27,12 +28,12 @@ import org.jetbrains.annotations.Nullable; import java.sql.*; import java.util.*; -public class PlayerInfoTable { +public class GameDataTable { private final Map CACHE = new HashMap<>(); private final Database database; - protected PlayerInfoTable(Database database) { + protected GameDataTable(Database database) { String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n" + " uuid BINARY(16) PRIMARY KEY,\n" @@ -170,30 +171,48 @@ public class PlayerInfoTable { public void addWins(Board board, List uuids, List winners, Map hider_kills, Map hider_deaths, Map seeker_kills, Map seeker_deaths, WinType type) { for(UUID uuid : uuids) { - String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; PlayerInfo info = getInfo(uuid); if(info == null){ info = new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); } - try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { - statement.setBytes(1, database.encodeUUID(uuid)); - statement.setInt(2, info.getHiderWins() + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); - statement.setInt(3, info.getSeekerWins() + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); - statement.setInt(4, info.getHiderGames() + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); - statement.setInt(5, info.getSeekerGames() + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); - statement.setInt(6, info.getHiderKills() + hider_kills.getOrDefault(uuid.toString(), 0)); - statement.setInt(7, info.getSeekerKills() + seeker_kills.getOrDefault(uuid.toString(), 0)); - statement.setInt(8, info.getHiderDeaths() + hider_deaths.getOrDefault(uuid.toString(), 0)); - statement.setInt(9, info.getSeekerDeaths() + seeker_deaths.getOrDefault(uuid.toString(), 0)); - statement.execute(); - } catch (SQLException e) { - Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); - e.printStackTrace(); - return; - } finally { - CACHE.remove(uuid); - } + updateInfo( + database.encodeUUID(info.getUniqueId()), + info.getHiderWins() + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0), + info.getSeekerWins() + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0), + info.getHiderGames() + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0), + info.getSeekerGames() + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0), + info.getHiderKills() + hider_kills.getOrDefault(uuid.toString(), 0), + info.getSeekerKills() + seeker_kills.getOrDefault(uuid.toString(), 0), + info.getHiderDeaths() + hider_deaths.getOrDefault(uuid.toString(), 0), + info.getSeekerDeaths() + seeker_deaths.getOrDefault(uuid.toString(), 0) + ); } } + protected boolean updateInfo(byte[] uuid, int hider_wins, int seeker_wins, int hider_games, int seeker_games, int hider_kills, int seeker_kills, int hider_deaths, int seeker_deaths){ + boolean success; + String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)"; + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, uuid); + statement.setInt(2, hider_wins); + statement.setInt(3, seeker_wins); + statement.setInt(4, hider_games); + statement.setInt(5, seeker_games); + statement.setInt(6, hider_kills); + statement.setInt(7, seeker_kills); + statement.setInt(8, hider_deaths); + statement.setInt(9, seeker_deaths); + statement.execute(); + statement.close(); + success = true; + } catch (SQLException e) { + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + success = false; + } finally { + CACHE.remove(uuid); + } + return success; + } + } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/LegacyTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/LegacyTable.java new file mode 100644 index 0000000..580c2f5 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/LegacyTable.java @@ -0,0 +1,104 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database; + +import net.tylermurphy.hideAndSeek.Main; +import net.tylermurphy.hideAndSeek.database.Database; +import net.tylermurphy.hideAndSeek.database.util.LegacyPlayerInfo; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class LegacyTable { + + private final Database database; + private final boolean exists; + + protected LegacyTable(Database database) { + + String sql = "SELECT * FROM player_info LIMIT 1;"; + + boolean check; + try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { + ResultSet resultSet = statement.executeQuery(sql); + check = resultSet.next(); + } catch (SQLException e) { + check = false; + } + + this.exists = check; + this.database = database; + } + + public boolean exists(){ + return exists; + } + + public boolean copyData(){ + String sql = "SELECT * FROM player_info;"; + List legacyPlayerInfoList = new ArrayList<>(); + try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { + ResultSet resultSet = statement.executeQuery(sql); + while(resultSet.next()){ + legacyPlayerInfoList.add(new LegacyPlayerInfo( + resultSet.getBytes("uuid"), + resultSet.getInt("wins"), + resultSet.getInt("hider_wins"), + resultSet.getInt("seeker_wins"), + resultSet.getInt("games_played") + )); + } + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + for(LegacyPlayerInfo legacyInfo : legacyPlayerInfoList){ + database.getGameData().updateInfo( + legacyInfo.getUniqueId(), + legacyInfo.getHiderWins(), + legacyInfo.getSeekerWins(), + legacyInfo.getGamesPlayer() - legacyInfo.getSeekerWins(), + legacyInfo.getSeekerWins(), + 0, + 0, + 0, + 0 + ); + } + return true; + } + + public boolean drop(){ + String sql = "DROP table player_info"; + try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { + statement.execute(sql); + return true; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java new file mode 100644 index 0000000..cbf410a --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java @@ -0,0 +1,99 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database; + +import net.tylermurphy.hideAndSeek.Main; +import org.jetbrains.annotations.Nullable; + +import java.sql.*; +import java.util.UUID; + +public class NameDataTable { + + private final Database database; + + protected NameDataTable(Database database) { + + String sql = "CREATE TABLE IF NOT EXISTS hs_names (\n" + + " uuid BINARY(16) NOT NULL,\n" + + " name VARCHAR(48) NOT NULL,\n" + + " PRIMARY KEY (uuid,name)\n" + + ");"; + + try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { + statement.executeUpdate(sql); + } catch (SQLException e) { + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + } + + this.database = database; + } + + @Nullable + public String getName(UUID uuid) { + String sql = "SELECT * FROM hs_names WHERE uuid = ?;"; + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, database.encodeUUID(uuid)); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + return rs.getString("name"); + } + rs.close(); + } catch (SQLException e) { + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + } + return null; + } + + @Nullable + public UUID getUUID(String name) { + String sql = "SELECT * FROM hs_names WHERE name = ?;"; + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setString(1, name); + ResultSet rs = statement.executeQuery(); + if (rs.next()) { + return database.decodeUUID(rs.getBytes("uuid")); + } + rs.close(); + } catch (SQLException e) { + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + } + return null; + } + + public boolean update(UUID uuid, String name){ + String sql = "INSERT OR REPLACE INTO hs_names (uuid, name) VALUES (?,?)"; + try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setBytes(1, database.encodeUUID(uuid)); + statement.setString(2, name); + statement.execute(); + statement.close(); + return true; + } catch (SQLException e) { + Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); + e.printStackTrace(); + return false; + } + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/connections/DatabaseConnection.java b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/DatabaseConnection.java new file mode 100644 index 0000000..466bda5 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/DatabaseConnection.java @@ -0,0 +1,29 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database.connections; + +import java.sql.Connection; +import java.sql.SQLException; + +public interface DatabaseConnection { + + Connection connect() throws SQLException; + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java new file mode 100644 index 0000000..c29d1b3 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java @@ -0,0 +1,61 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database.connections; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import java.sql.Connection; +import java.sql.SQLException; + +public class MySQLConnection implements DatabaseConnection { + + private final HikariConfig config; + private final HikariDataSource ds; + + public MySQLConnection(){ + + String host = "to be implemented"; + String port = "to be implemented"; + String user = "to be implemented"; + String pass = "to be implemented"; + + config = new HikariConfig(); + + config.setJdbcUrl("jdbc:mariadb://"+host+":"+port+"/kenbot"); + config.addDataSourceProperty("cachePrepStmts", "true"); + config.addDataSourceProperty("prepStmtCacheSize", "250"); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); + config.addDataSourceProperty("user", user); + config.addDataSourceProperty("password",pass); + config.addDataSourceProperty("autoCommit", "true"); + config.setAutoCommit(true); + config.setMaximumPoolSize(20); + + ds = new HikariDataSource(config); + + } + + @Override + public Connection connect() throws SQLException { + return ds.getConnection(); + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/connections/SQLiteConnection.java b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/SQLiteConnection.java new file mode 100644 index 0000000..1a03106 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/SQLiteConnection.java @@ -0,0 +1,64 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database.connections; + +import net.tylermurphy.hideAndSeek.Main; +import org.sqlite.SQLiteConfig; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class SQLiteConnection implements DatabaseConnection { + + private final File databaseFile; + private final SQLiteConfig config; + + public SQLiteConnection(){ + + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException e) { + Main.getInstance().getLogger().severe(e.getMessage()); + throw new RuntimeException(e.getMessage()); + } + + databaseFile = new File(Main.getInstance().getDataFolder(), "database.db"); + + config = new SQLiteConfig(); + config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); + config.setTempStore(SQLiteConfig.TempStore.MEMORY); + } + + @Override + public Connection connect() { + Connection conn = null; + try { + String url = "jdbc:sqlite:"+databaseFile; + conn = DriverManager.getConnection(url, config.toProperties()); + } catch (SQLException e) { + Main.getInstance().getLogger().severe(e.getMessage()); + e.printStackTrace(); + } + return conn; + } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/util/LegacyPlayerInfo.java b/src/main/java/net/tylermurphy/hideAndSeek/database/util/LegacyPlayerInfo.java new file mode 100644 index 0000000..5b59779 --- /dev/null +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/util/LegacyPlayerInfo.java @@ -0,0 +1,56 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2021-2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package net.tylermurphy.hideAndSeek.database.util; + +import java.util.UUID; + +public class LegacyPlayerInfo { + + private final byte[] uniqueId; + private final int totalWins; + private final int hiderWins; + private final int seekerWins; + private final int gamesPlayed; + + public LegacyPlayerInfo(byte[] uniqueId, int totalWins, int hiderWins, int seekerWins, int gamesPlayed) { + this.uniqueId = uniqueId; + this.totalWins = totalWins; + this.hiderWins = hiderWins; + this.seekerWins = seekerWins; + this.gamesPlayed = gamesPlayed; + } + + public byte[] getUniqueId() { + return uniqueId; + } + + public int getTotalWins() { return totalWins; } + + public int getHiderWins() { + return hiderWins; + } + + public int getSeekerWins() { + return seekerWins; + } + + public int getGamesPlayer() { return gamesPlayed; } + +} diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java b/src/main/java/net/tylermurphy/hideAndSeek/database/util/PlayerInfo.java similarity index 95% rename from src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java rename to src/main/java/net/tylermurphy/hideAndSeek/database/util/PlayerInfo.java index 5c74e76..96fe9d8 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/PlayerInfo.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/util/PlayerInfo.java @@ -1,7 +1,7 @@ /* * This file is part of Kenshins Hide and Seek * - * Copyright (c) 2021 Tyler Murphy. + * Copyright (c) 2021-2022 Tyler Murphy. * * Kenshins Hide and Seek free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,7 +17,7 @@ * */ -package net.tylermurphy.hideAndSeek.database; +package net.tylermurphy.hideAndSeek.database.util; import java.util.UUID; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java index 37865b0..094ff68 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java @@ -23,6 +23,9 @@ public class JoinLeaveHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent event) { + if(!Main.getInstance().getDatabase().getNameData().update(event.getPlayer().getUniqueId(), event.getPlayer().getDisplayName())){ + Main.getInstance().getLogger().warning("Failed to save name data for user: " + event.getPlayer().getDisplayName()); + } Main.getInstance().getBoard().remove(event.getPlayer()); removeItems(event.getPlayer()); if (Main.getInstance().getGame().isNotSetup()) return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index c1f8c2a..72d1f4d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -3,7 +3,7 @@ package net.tylermurphy.hideAndSeek.util; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.Database; -import net.tylermurphy.hideAndSeek.database.PlayerInfo; +import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; diff --git a/src/test/java/MainTest.java b/src/test/java/MainTest.java new file mode 100644 index 0000000..9997e04 --- /dev/null +++ b/src/test/java/MainTest.java @@ -0,0 +1,42 @@ +/* + * This file is part of Kenshins Hide and Seek + * + * Copyright (c) 2022 Tyler Murphy. + * + * Kenshins Hide and Seek free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * he Free Software Foundation version 3. + * + * Kenshins Hide and Seek is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +import be.seeseemelk.mockbukkit.MockBukkit; +import be.seeseemelk.mockbukkit.ServerMock; +import net.tylermurphy.hideAndSeek.Main; +import org.junit.After; +import org.junit.Before; + +public class MainTest { + + private ServerMock server; + private Main plugin; + + @Before + public void setUp() { + server = MockBukkit.mock(); + plugin = MockBukkit.load(Main.class); + } + + @After + public void tearDown() { + MockBukkit.unmock(); + } + +} From 13e6b38aa97f59e5a432f2d88ea15738358df019 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 17 May 2022 19:26:00 -0400 Subject: [PATCH 53/68] mysql support, always glow, countdown_last, kill stat change, game board null fix --- pom.xml | 6 ++- .../tylermurphy/hideAndSeek/command/Top.java | 9 +++- .../tylermurphy/hideAndSeek/command/Wins.java | 20 ++++----- .../hideAndSeek/configuration/Config.java | 25 ++++++++++- .../configuration/ConfigManager.java | 4 ++ .../configuration/Localization.java | 24 ++++++++--- .../hideAndSeek/database/Database.java | 9 +++- .../database/connections/MySQLConnection.java | 16 +++---- .../tylermurphy/hideAndSeek/game/Board.java | 6 +-- .../tylermurphy/hideAndSeek/game/Game.java | 6 ++- .../hideAndSeek/game/events/Glow.java | 7 +++- .../game/listener/DamageHandler.java | 11 ++--- .../game/listener/JoinLeaveHandler.java | 4 +- .../hideAndSeek/util/PAPIExpansion.java | 37 ++++++++-------- src/main/resources/config.yml | 28 +++++++++++++ .../resources/lang/localization_de-DE.yml | 1 + .../resources/lang/localization_en-US.yml | 1 + src/test/java/MainTest.java | 42 ------------------- 18 files changed, 146 insertions(+), 110 deletions(-) delete mode 100644 src/test/java/MainTest.java diff --git a/pom.xml b/pom.xml index fff9f6c..b72260d 100644 --- a/pom.xml +++ b/pom.xml @@ -41,8 +41,10 @@ *:* META-INF/*.MF - META-INF/*.md - META-INF + META-INF/*.MD + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA sqlite-jdbc.properties diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index caa751b..9b55c9f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -22,6 +22,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import java.util.List; @@ -54,7 +55,13 @@ public class Top implements ICommand { return; } for(PlayerInfo info : infos) { - String name = Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); + OfflinePlayer temp = Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()); + String name; + if(temp == null){ + name = Main.getInstance().getDatabase().getNameData().getName(info.getUniqueId()); + } else { + name = temp.getName(); + } ChatColor color; switch (i) { case 1: color = ChatColor.YELLOW; break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index 8a0b6dc..491c9a4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -37,23 +37,21 @@ public class Wins implements ICommand { UUID uuid; String name; if (args.length == 0) { - Player player = Main.getInstance().getServer().getPlayer(sender.getName()); - if (player == null) { - sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName())); - return; - } - uuid = player.getUniqueId(); + uuid = sender.getUniqueId(); name = sender.getName(); } else { - try { - name = args[0]; + name = args[0]; + if(Main.getInstance().getServer().getOfflinePlayer(args[0]) == null){ + uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[0]); + } else { uuid = Main.getInstance().getServer().getOfflinePlayer(args[0]).getUniqueId(); - } catch (Exception e) { - sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); - return; } } + if(uuid == null){ + sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); + return; + } PlayerInfo info = Main.getInstance().getDatabase().getGameData().getInfo(uuid); if (info == null) { sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java index 03d7504..4aeac68 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Config.java @@ -55,7 +55,13 @@ public class Config { locale, leaveServer, placeholderError, - placeholderNoData; + placeholderNoData, + databaseType, + databaseHost, + databasePort, + databaseUser, + databasePass, + databaseName; public static Vector spawnPosition, @@ -71,6 +77,7 @@ public class Config { tauntEnabled, tauntCountdown, tauntLast, + alwaysGlow, glowEnabled, glowStackable, pvpEnabled, @@ -218,9 +225,10 @@ public class Config { tauntLast = config.getBoolean("taunt.whenLastPerson"); //Glow + alwaysGlow = config.getBoolean("alwaysGlow") && Main.getInstance().supports(9); glowLength = Math.max(1, config.getInt("glow.time")); glowStackable = config.getBoolean("glow.stackable"); - glowEnabled = config.getBoolean("glow.enabled") && Main.getInstance().supports(9); + glowEnabled = config.getBoolean("glow.enabled") && Main.getInstance().supports(9) && !alwaysGlow; if (glowEnabled) { glowPowerupItem = createItemStack("glow"); } @@ -314,6 +322,19 @@ public class Config { teleportItem = createItemStack("spectatorItems.teleport"); teleportItemPosition = config.getInt("spectatorItems.teleport.position"); + + //Database + databaseHost = config.getString("databaseHost"); + databasePort = config.getString("databasePort"); + databaseUser = config.getString("databaseUser"); + databasePass = config.getString("databasePass"); + databaseName = config.getString("databaseName"); + + databaseType = config.getString("databaseType").toUpperCase(); + if(!databaseType.equals("SQLITE") && !databaseType.equals("MYSQL")){ + Main.getInstance().getLogger().warning("databaseType: "+databaseType+" is not a valid configuration option!"); + databaseType = "SQLITE"; + } } public static void addToConfig(String path, Object value) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index f02eaba..381a41c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -205,6 +205,10 @@ public class ConfigManager { } } + public ConfigurationSection getDefaultConfigurationSection(String path) { + return defaultConfig.getConfigurationSection(path); + } + public void set(String path, Object value) { config.set(path, value); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java index be60b61..9418414 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/Localization.java @@ -28,6 +28,7 @@ import java.util.Map; public class Localization { public static final Map LOCAL = new HashMap<>(); + public static final Map DEFAULT_LOCAL = new HashMap<>(); private static final Map CHANGES = new HashMap() {{ put("en-US", new String[][]{{"WORLDBORDER_DECREASING"},{"START","TAUNTED"}}); @@ -61,17 +62,28 @@ public class Localization { for(String key : manager.getConfigurationSection("Localization").getKeys(false)) { LOCAL.put( - key, + key, new LocalizationString( ChatColor.translateAlternateColorCodes('&', manager.getString("Localization."+key) ) ) - ); + ); + } + + for(String key : manager.getDefaultConfigurationSection("Localization").getKeys(false)) { + DEFAULT_LOCAL.put( + key, + new LocalizationString( ChatColor.translateAlternateColorCodes('&', manager.getString("Localization."+key) ) ) + ); } } public static LocalizationString message(String key) { - LocalizationString temp = LOCAL.get(key); - if (temp == null) { - return new LocalizationString(ChatColor.RED + "" + ChatColor.ITALIC + key + " is not found in localization.yml. This is a plugin issue, please report it."); + LocalizationString message = LOCAL.get(key); + if (message == null) { + LocalizationString defaultMessage = DEFAULT_LOCAL.get(key); + if(defaultMessage == null) { + return new LocalizationString(ChatColor.RED + "" + ChatColor.ITALIC + key + " is not found in localization.yml. This is a plugin issue, please report it."); + } + return new LocalizationString(defaultMessage.toString()); } - return new LocalizationString(temp.toString()); + return new LocalizationString(message.toString()); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java index 0eceb98..0489b5d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/Database.java @@ -22,6 +22,7 @@ package net.tylermurphy.hideAndSeek.database; import com.google.common.io.ByteStreams; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.connections.DatabaseConnection; +import net.tylermurphy.hideAndSeek.database.connections.MySQLConnection; import net.tylermurphy.hideAndSeek.database.connections.SQLiteConnection; import java.io.ByteArrayInputStream; @@ -32,6 +33,8 @@ import java.sql.Connection; import java.sql.SQLException; import java.util.UUID; +import static net.tylermurphy.hideAndSeek.configuration.Config.databaseType; + public class Database { private final GameDataTable playerInfo; @@ -40,7 +43,11 @@ public class Database { public Database(){ - connection = new SQLiteConnection(); + if(databaseType.equals("SQLITE")) { + connection = new SQLiteConnection(); + } else { + connection = new MySQLConnection(); + } playerInfo = new GameDataTable(this); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java index c29d1b3..b7c1b1d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/connections/MySQLConnection.java @@ -25,26 +25,22 @@ import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.SQLException; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; + public class MySQLConnection implements DatabaseConnection { - private final HikariConfig config; private final HikariDataSource ds; public MySQLConnection(){ - String host = "to be implemented"; - String port = "to be implemented"; - String user = "to be implemented"; - String pass = "to be implemented"; + HikariConfig config = new HikariConfig(); - config = new HikariConfig(); - - config.setJdbcUrl("jdbc:mariadb://"+host+":"+port+"/kenbot"); + config.setJdbcUrl("jdbc:mariadb://"+databaseHost+":"+databasePort+"/"+databaseName); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - config.addDataSourceProperty("user", user); - config.addDataSourceProperty("password",pass); + config.addDataSourceProperty("user", databaseUser); + config.addDataSourceProperty("password",databasePass); config.addDataSourceProperty("autoCommit", "true"); config.setAutoCommit(true); config.setMaximumPoolSize(20); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index 04b0d37..a8e41c7 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -153,7 +153,7 @@ public class Board { } else { hider_kills.put(uuid.toString(), 1); } - } else if (getFirstSeeker().getUniqueId().equals(uuid)) { + } else if (Seeker.contains(uuid.toString())) { if (seeker_kills.containsKey(uuid.toString())) { seeker_kills.put(uuid.toString(), seeker_kills.get(uuid.toString())+1); } else { @@ -169,7 +169,7 @@ public class Board { } else { hider_deaths.put(uuid.toString(), 1); } - } else if (getFirstSeeker().getUniqueId().equals(uuid)) { + } else if (Seeker.contains(uuid.toString())) { if (seeker_deaths.containsKey(uuid.toString())) { seeker_deaths.put(uuid.toString(), seeker_deaths.get(uuid.toString())+1); } else { @@ -234,7 +234,7 @@ public class Board { private void createGameBoard(Player player, boolean recreate) { CustomBoard board = customBoards.get(player.getUniqueId().toString()); - if (recreate) { + if (recreate || board == null) { board = new CustomBoard(player, GAME_TITLE); board.updateTeams(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index c261b52..cb3ad1f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -242,12 +242,14 @@ public class Game { private void whileStarting() { if(gameTick % 20 == 0) { - if (startingTimer % 5 == 0 || startingTimer < 4) { + if (startingTimer % 5 == 0 || startingTimer < 5) { String message; if (startingTimer == 0) { message = message("START").toString(); status = Status.PLAYING; board.getPlayers().forEach(player -> PlayerLoader.resetPlayer(player, board)); + } else if (startingTimer == 1){ + message = message("START_COUNTDOWN_LAST").addAmount(startingTimer).toString(); } else { message = message("START_COUNTDOWN").addAmount(startingTimer).toString(); } @@ -305,7 +307,7 @@ public class Game { } if (worldBorderEnabled) worldBorder.update(); if (tauntEnabled) taunt.update(); - if (glowEnabled) glow.update(); + if (glowEnabled || alwaysGlow) glow.update(); } board.getSpectators().forEach(spectator -> spectator.setFlying(spectator.getAllowFlight())); checkWinConditions(); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java index a1d7295..8631ef5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/events/Glow.java @@ -10,8 +10,7 @@ import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; -import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength; -import static net.tylermurphy.hideAndSeek.configuration.Config.glowStackable; +import static net.tylermurphy.hideAndSeek.configuration.Config.*; public class Glow { @@ -37,6 +36,10 @@ public class Glow { } public void update() { + if(alwaysGlow){ + sendPackets(); + return; + } if (running) { sendPackets(); glowTime--; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 701f446..3b90d39 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -96,21 +96,18 @@ public class DamageHandler implements Listener { // Broadcast player death message if (board.isSeeker(player)) { game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); - if (board.getFirstSeeker().getName().equals(player.getName())) { - board.addDeath(player.getUniqueId()); - } } else if (board.isHider(player)) { if (attacker == null) { game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); } else { game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); } - board.addDeath(player.getUniqueId()); board.addSeeker(player); } - // Add leaderboard kills if attacker - if (attacker != null && ( board.isHider(attacker) || board.getFirstSeeker().getName().equals(attacker.getName()) ) ) - board.addKill(attacker.getUniqueId()); + // Add leaderboard stats + board.addDeath(player.getUniqueId()); + if (attacker != null) board.addKill(attacker.getUniqueId()); + //Reload player PlayerLoader.resetPlayer(player, board); board.reloadBoardTeams(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java index 094ff68..7ac4f85 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/JoinLeaveHandler.java @@ -23,8 +23,8 @@ public class JoinLeaveHandler implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PlayerJoinEvent event) { - if(!Main.getInstance().getDatabase().getNameData().update(event.getPlayer().getUniqueId(), event.getPlayer().getDisplayName())){ - Main.getInstance().getLogger().warning("Failed to save name data for user: " + event.getPlayer().getDisplayName()); + if(!Main.getInstance().getDatabase().getNameData().update(event.getPlayer().getUniqueId(), event.getPlayer().getName())){ + Main.getInstance().getLogger().warning("Failed to save name data for user: " + event.getPlayer().getName()); } Main.getInstance().getBoard().remove(event.getPlayer()); removeItems(event.getPlayer()); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 72d1f4d..7823fe9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -39,15 +39,17 @@ public class PAPIExpansion extends PlaceholderExpansion { Database database = Main.getInstance().getDatabase(); String[] args = params.split("_"); if (args.length < 1) return null; - if (args[0].equals("stats") && args.length == 2) { - PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); + if (args[0].equals("stats") && (args.length == 2 || args.length == 3)) { + PlayerInfo info = null; + if(args.length == 2) { + database.getGameData().getInfo(player.getUniqueId()); + } else { + UUID uuid; + try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } + info = database.getGameData().getInfo(uuid); + } if (info == null) return placeholderNoData; return getValue(info, args[1]); - } else if (args[0].equals("stats") && args.length == 3) { - UUID uuid; - try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } - PlayerInfo info = database.getGameData().getInfo(uuid); - return getValue(info, args[1]); } else if ((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3) { int place; try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } @@ -60,24 +62,21 @@ public class PAPIExpansion extends PlaceholderExpansion { } else { return Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); } - } else if (args[0].equals("rank-place") && args.length == 2) { + } else if (args[0].equals("rank-place") && (args.length == 2 || args.length == 3)) { if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); + PlayerInfo info = null; + if(args.length == 2){ + database.getGameData().getInfo(player.getUniqueId()); + } else { + UUID uuid; + try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } + info = database.getGameData().getInfo(uuid); + } if (info == null) return placeholderNoData; if (getValue(info, args[1]).equals("0")) { return "-"; } Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); if (count == null) { return placeholderNoData; } return count.toString(); - } else if (args[0].equals("rank-place") && args.length == 3) { - UUID uuid; - try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } - if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = database.getGameData().getInfo(player.getUniqueId()); - if (info == null) return placeholderNoData; - if (getValue(info, args[1]).equals("0")) { return "-"; } - Integer count = database.getGameData().getRanking(getRanking(args[1]), uuid); - if (count == null) { return placeholderNoData; } - return count.toString(); } return null; } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 2d76b4a..6153c46 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -94,6 +94,26 @@ leaveServer: hub # default: true mapSaveEnabled: true +# How you want to store game data. If you are running a single server, sqlite is fine, as no setup is necessary. +# But if you want the data to go across multiple servers, you can switch it to mysql. +# WARNING: Data is not saved across databases. You have to migrate the data yourself! +# +# SQLITE - A single database.db file in the plugin folder, good for a single server. +# +# MYSQL - Uses a mysql server to store data, good for multi-server setups or large servers. +# +# default: SQLITE +databaseType: SQLITE + +# The following settings are used for MYSQL databases ONLY. If you are running SQLITE, these +# will be ignored. If you are running MYSQL, you need to provide the database host url, database +# host port (usually 3306), database username, and database password. +databaseHost: localhost +databasePort: 3306 +databaseUser: root +databasePass: +databaseName: hideandseek + # The world border closes every interval, which is evey [delay] in minutes. # Thw world border starts at [size], and decreases 100 blocks every interval. # x & z are the center location. [enabled] is whenever the border is enabled. @@ -132,6 +152,14 @@ glow: material: SNOWBALL model-data: 0 +# This has the same glow effect as the glow powerup in that all seekers positions get +# shown to hiders. But enabling this force disables the powerup, and instead always shows +# the seekers positions to the hiders. Good for small maps. Since the glow effect wasn't added +# until Minecraft 1.9, any server running 1.8 will have this disabled regardless of the +# options below. +# default: false +alwaysGlow: false + # The message prefixes displayed before messages. The message contents themselves # can be changed in localization.yml. prefix: diff --git a/src/main/resources/lang/localization_de-DE.yml b/src/main/resources/lang/localization_de-DE.yml index 84ada18..a1a6eea 100644 --- a/src/main/resources/lang/localization_de-DE.yml +++ b/src/main/resources/lang/localization_de-DE.yml @@ -56,6 +56,7 @@ Localization: START_MIN_PLAYERS: "Um das Spiel zu starten benötigst du mindestens {AMOUNT} Spieler." START_INVALID_NAME: "Ungültiger Spieler: {PLAYER}." START_COUNTDOWN: "Die Hider haben {AMOUNT} Sekunden Zeit sich zu verstecken!" + START_COUNTDOWN_LAST: "Die Hider haben {AMOUNT} Sekunde Zeit sich zu verstecken!" START: "Los, Seeker! Es ist Zeit, die Hider zu finden." STOP: "Das Spiel wurde gestoppt." HIDER_TEAM_NAME: "&6&lHIDER" diff --git a/src/main/resources/lang/localization_en-US.yml b/src/main/resources/lang/localization_en-US.yml index 07d547b..96ccf7a 100644 --- a/src/main/resources/lang/localization_en-US.yml +++ b/src/main/resources/lang/localization_en-US.yml @@ -57,6 +57,7 @@ Localization: START_MIN_PLAYERS: "You must have at least {AMOUNT} players to start." START_INVALID_NAME: "Invalid player: {PLAYER}." START_COUNTDOWN: "Hiders have {AMOUNT} seconds to hide!" + START_COUNTDOWN_LAST: "Hiders have {AMOUNT} second to hide!" START: "Attention SEEKERS, its time to find the hiders!" STOP: "Game has been force stopped." HIDER_TEAM_NAME: "&6&lHIDER" diff --git a/src/test/java/MainTest.java b/src/test/java/MainTest.java deleted file mode 100644 index 9997e04..0000000 --- a/src/test/java/MainTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of Kenshins Hide and Seek - * - * Copyright (c) 2022 Tyler Murphy. - * - * Kenshins Hide and Seek free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * he Free Software Foundation version 3. - * - * Kenshins Hide and Seek is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -import be.seeseemelk.mockbukkit.MockBukkit; -import be.seeseemelk.mockbukkit.ServerMock; -import net.tylermurphy.hideAndSeek.Main; -import org.junit.After; -import org.junit.Before; - -public class MainTest { - - private ServerMock server; - private Main plugin; - - @Before - public void setUp() { - server = MockBukkit.mock(); - plugin = MockBukkit.load(Main.class); - } - - @After - public void tearDown() { - MockBukkit.unmock(); - } - -} From 0ce33ae3ce8ab24aa8d6cbb4527ea4aa695b7185 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 17 May 2022 19:35:12 -0400 Subject: [PATCH 54/68] pom fix --- pom.xml | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/pom.xml b/pom.xml index b72260d..42cd0f7 100644 --- a/pom.xml +++ b/pom.xml @@ -33,6 +33,7 @@ com.github.cryptomorin:XSeries org.xerial:sqlite-jdbc + org.mariadb.jdbc:mariadb-java-client com.zaxxer:HikariCP @@ -118,18 +119,12 @@ com.zaxxer HikariCP - 5.0.1 + 4.0.3 - org.junit.jupiter - junit-jupiter - 5.9.0-M1 - - - com.github.seeseemelk - MockBukkit-v1.17 - 1.13.0 - test + org.mariadb.jdbc + mariadb-java-client + 2.7.2 \ No newline at end of file From 2a0ddce7c3e077824757f6317d19696bf133e248 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 17 May 2022 19:37:05 -0400 Subject: [PATCH 55/68] remove bad import in Main --- src/main/java/net/tylermurphy/hideAndSeek/Main.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index 126deaa..f60659d 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -19,7 +19,6 @@ package net.tylermurphy.hideAndSeek; -import jdk.jpackage.internal.IOUtils; import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; From 0bcb3dee0e820a36b30be4c4c0b47e5fdda57160 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 17 May 2022 19:48:24 -0400 Subject: [PATCH 56/68] 1.4.3 Release Canidate 1 --- .../java/net/tylermurphy/hideAndSeek/Main.java | 15 +++++++++++---- .../tylermurphy/hideAndSeek/command/Debug.java | 6 ++++-- .../hideAndSeek/game/PlayerLoader.java | 2 ++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index f60659d..7bd86cb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -57,13 +57,24 @@ public class Main extends JavaPlugin implements Listener { public Main() { super(); instance = this; + + Config.loadConfig(); + Localization.loadLocalization(); + Items.loadItems(); + board = new Board(); database = new Database(); } protected Main(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { super(loader, description, dataFolder, file); + instance = this; + + Config.loadConfig(); + Localization.loadLocalization(); + Items.loadItems(); + board = new Board(); database = new Database(); } @@ -72,10 +83,6 @@ public class Main extends JavaPlugin implements Listener { this.registerListeners(); - Config.loadConfig(); - Localization.loadLocalization(); - Items.loadItems(); - CommandHandler.registerCommands(); game = new Game(board); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java index c1cec56..1275ceb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Debug.java @@ -38,7 +38,8 @@ public class Debug implements ICommand { } Main.getInstance().getBoard().addHider(player); PlayerLoader.loadHider(player, Main.getInstance().getGame().getGameWorld()); - PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); + if(Main.getInstance().getGame().getStatus() != Status.STARTING) + PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); })); debugMenu.setItem(1, createOption(1, XMaterial.GOLDEN_CHESTPLATE.parseMaterial(), "&cBecome a &lSeeker", 1, player -> { if(mapSaveEnabled) { @@ -46,7 +47,8 @@ public class Debug implements ICommand { } Main.getInstance().getBoard().addSeeker(player); PlayerLoader.loadSeeker(player, Main.getInstance().getGame().getGameWorld()); - PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); + if(Main.getInstance().getGame().getStatus() != Status.STARTING) + PlayerLoader.resetPlayer(player, Main.getInstance().getBoard()); })); debugMenu.setItem(2, createOption(2, XMaterial.IRON_CHESTPLATE.parseMaterial(), "&8Become a &lSpectator", 1, player -> { if(mapSaveEnabled) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java index 0ce7ac7..19a48f4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java @@ -123,6 +123,8 @@ public class PlayerLoader { } private static void loadPlayer(Player player){ + player.setFlying(false); + player.setAllowFlight(false); player.setGameMode(GameMode.ADVENTURE); player.getInventory().clear(); for(PotionEffect effect : player.getActivePotionEffects()) { From e79c4ad1c5dbbc3717fbb7ab1c5fcb7e2d538409 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 18 May 2022 21:45:38 -0400 Subject: [PATCH 57/68] 1.5.0 Release Canidate 2 (Previously 1.4.3) --- pom.xml | 4 +- .../net/tylermurphy/hideAndSeek/Main.java | 43 +++++++++++++------ .../hideAndSeek/command/About.java | 2 +- .../configuration/ConfigManager.java | 23 +++++++--- .../tylermurphy/hideAndSeek/game/Board.java | 8 ++-- .../tylermurphy/hideAndSeek/game/Game.java | 2 +- .../game/listener/DamageHandler.java | 4 +- .../hideAndSeek/world/WorldLoader.java | 2 + src/main/resources/plugin.yml | 4 +- 9 files changed, 61 insertions(+), 31 deletions(-) diff --git a/pom.xml b/pom.xml index 42cd0f7..7e1be5a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 net.tylermurphy - HideAndSeek - 1.4.3 + KenshinsHideAndSeek + 1.5.0 Hide and Seek Plugin UTF-8 diff --git a/src/main/java/net/tylermurphy/hideAndSeek/Main.java b/src/main/java/net/tylermurphy/hideAndSeek/Main.java index 7bd86cb..1248551 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/Main.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/Main.java @@ -24,6 +24,7 @@ import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.game.Board; +import net.tylermurphy.hideAndSeek.game.PlayerLoader; import net.tylermurphy.hideAndSeek.game.util.Status; import net.tylermurphy.hideAndSeek.util.CommandHandler; import net.tylermurphy.hideAndSeek.game.Game; @@ -31,6 +32,7 @@ import net.tylermurphy.hideAndSeek.game.listener.*; import net.tylermurphy.hideAndSeek.util.PAPIExpansion; import net.tylermurphy.hideAndSeek.util.TabCompleter; import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.Listener; @@ -44,6 +46,9 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition; +import static net.tylermurphy.hideAndSeek.configuration.Config.exitWorld; + public class Main extends JavaPlugin implements Listener { private static Main instance; @@ -56,11 +61,7 @@ public class Main extends JavaPlugin implements Listener { public Main() { super(); - instance = this; - - Config.loadConfig(); - Localization.loadLocalization(); - Items.loadItems(); + onConstructed(); board = new Board(); database = new Database(); @@ -68,15 +69,27 @@ public class Main extends JavaPlugin implements Listener { protected Main(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { super(loader, description, dataFolder, file); + onConstructed(); + + board = new Board(); + database = new Database(); + } + + private void onConstructed(){ instance = this; + Matcher matcher = Pattern.compile("MC: \\d\\.(\\d+)").matcher(Bukkit.getVersion()); + if (matcher.find()) { + version = Integer.parseInt(matcher.group(1)); + } else { + throw new IllegalArgumentException("Failed to parse server version from: " + Bukkit.getVersion()); + } + Config.loadConfig(); Localization.loadLocalization(); Items.loadItems(); - board = new Board(); - database = new Database(); } public void onEnable() { @@ -94,16 +107,18 @@ public class Main extends JavaPlugin implements Listener { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { new PAPIExpansion().register(); } - - Matcher matcher = Pattern.compile("MC: \\d\\.(\\d+)").matcher(Bukkit.getVersion()); - if (matcher.find()) { - version = Integer.parseInt(matcher.group(1)); - } else { - throw new IllegalArgumentException("Failed to parse server version from: " + Bukkit.getVersion()); - } } public void onDisable() { + + version = 0; + + board.getPlayers().forEach(player -> { + board.removeBoard(player); + PlayerLoader.unloadPlayer(player); + player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); + }); + Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this); board.cleanup(); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java index f996519..bda6016 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/About.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/About.java @@ -26,7 +26,7 @@ public class About implements ICommand { public void execute(Player sender, String[] args) { sender.sendMessage( - String.format("%s%sHide and Seek %s(%s1.4.3%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) + + String.format("%s%sHide and Seek %s(%s1.5.0%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) + String.format("%sAuthor: %s[KenshinEto]\n", ChatColor.GRAY, ChatColor.WHITE) + String.format("%sHelp Command: %s/hs %shelp", ChatColor.GRAY, ChatColor.AQUA, ChatColor.WHITE) ); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java index 381a41c..5e28258 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/configuration/ConfigManager.java @@ -46,12 +46,25 @@ public class ConfigManager { private ConfigManager(String filename, String defaultFilename) { - this.defaultFilename = defaultFilename; - this.file = new File(Main.getInstance().getDataFolder(), filename); + File dataFolder = Main.getInstance().getDataFolder(); + File oldDataFolder = new File(Main.getInstance().getDataFolder().getParent() + File.separator + "HideAndSeek"); - File folder = Main.getInstance().getDataFolder(); - if (!folder.exists()) { - if (!folder.mkdirs()) { + this.defaultFilename = defaultFilename; + this.file = new File(dataFolder, filename); + + if(oldDataFolder.exists()){ + if(!dataFolder.exists()){ + if(!oldDataFolder.renameTo(dataFolder)){ + throw new RuntimeException("Could not rename folder: " + oldDataFolder.getPath()); + } + } else { + throw new RuntimeException("Plugin folders for HideAndSeek & KenshinsHideAndSeek both exists. There can only be one!"); + } + + } + + if (!dataFolder.exists()) { + if (!dataFolder.mkdirs()) { throw new RuntimeException("Failed to make directory: " + file.getPath()); } } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index a8e41c7..bb1984e 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -79,11 +79,11 @@ public class Board { } public List getHiders() { - return Hider.stream().map(playerList::get).collect(Collectors.toList()); + return Hider.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList()); } public List getSeekers() { - return Seeker.stream().map(playerList::get).collect(Collectors.toList()); + return Seeker.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList()); } public Player getFirstSeeker() { @@ -91,11 +91,11 @@ public class Board { } public List getSpectators() { - return Spectator.stream().map(playerList::get).collect(Collectors.toList()); + return Spectator.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList()); } public List getPlayers() { - return new ArrayList<>(playerList.values()); + return playerList.values().stream().filter(Objects::nonNull).collect(Collectors.toList()); } public Player getPlayer(UUID uuid) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index cb3ad1f..34f3a46 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -121,11 +121,11 @@ public class Game { board.addSeeker(seeker); PlayerLoader.loadSeeker(seeker, getGameWorld()); board.getPlayers().forEach(player -> { - board.createGameBoard(player); if(board.isSeeker(player)) return; board.addHider(player); PlayerLoader.loadHider(player, getGameWorld()); }); + board.getPlayers().forEach(board::createGameBoard); worldBorder.resetWorldBorder(getGameWorld()); if (gameLength > 0) gameTimer = gameLength; status = Status.STARTING; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 3b90d39..086a48a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -69,9 +69,9 @@ public class DamageHandler implements Listener { // Spectators cannot take damage if (board.isSpectator(player)) { event.setCancelled(true); - if (Main.getInstance().supports(18) && player.getLocation().getY() < -64) { + if (Main.getInstance().supports(18) && player.getLocation().getBlockY() < -64) { player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); - } else if (player.getLocation().getY() < 0) { + } else if (!Main.getInstance().supports(18) && player.getLocation().getY() < 0) { player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); } return; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java index ebfedcd..1d4ff71 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/world/WorldLoader.java @@ -21,6 +21,7 @@ package net.tylermurphy.hideAndSeek.world; import net.tylermurphy.hideAndSeek.Main; import org.bukkit.Bukkit; +import org.bukkit.Location; import org.bukkit.World; import org.bukkit.WorldCreator; @@ -55,6 +56,7 @@ public class WorldLoader { Main.getInstance().getLogger().warning(saveName + " already unloaded."); return; } + world.getPlayers().forEach(player -> player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()))); if (Bukkit.getServer().unloadWorld(world, false)) { Main.getInstance().getLogger().info("Successfully unloaded " + saveName); }else{ diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 74c4855..c4224dc 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,6 +1,6 @@ -name: HideAndSeek +name: KenshinsHideAndSeek main: net.tylermurphy.hideAndSeek.Main -version: 1.4.3 +version: 1.5.0 author: KenshinEto load: STARTUP api-version: 1.13 From 217f412c39f7f06662a22f2608dc625a18e1d5e1 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 18 May 2022 21:51:20 -0400 Subject: [PATCH 58/68] 1.5.0 Release Canidate 2.1 --- .../hideAndSeek/game/listener/DamageHandler.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 086a48a..68fa84c 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -93,6 +93,9 @@ public class DamageHandler implements Listener { } // Teleport player to seeker spawn player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); + // Add leaderboard stats + board.addDeath(player.getUniqueId()); + if (attacker != null) board.addKill(attacker.getUniqueId()); // Broadcast player death message if (board.isSeeker(player)) { game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); @@ -104,9 +107,6 @@ public class DamageHandler implements Listener { } board.addSeeker(player); } - // Add leaderboard stats - board.addDeath(player.getUniqueId()); - if (attacker != null) board.addKill(attacker.getUniqueId()); //Reload player PlayerLoader.resetPlayer(player, board); board.reloadBoardTeams(); From 6b4bef24c05747280c60f48063ce57b5f654ce04 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 19 May 2022 17:14:01 -0400 Subject: [PATCH 59/68] 1.5.0 Release Canidate 3 --- .../net/tylermurphy/hideAndSeek/command/Top.java | 9 ++------- .../net/tylermurphy/hideAndSeek/command/Wins.java | 6 +----- .../hideAndSeek/database/NameDataTable.java | 13 +++++++++++++ .../java/net/tylermurphy/hideAndSeek/game/Game.java | 5 ++--- .../tylermurphy/hideAndSeek/util/PAPIExpansion.java | 4 ++-- 5 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java index 9b55c9f..6125a00 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Top.java @@ -21,6 +21,7 @@ package net.tylermurphy.hideAndSeek.command; import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; +import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; @@ -55,13 +56,7 @@ public class Top implements ICommand { return; } for(PlayerInfo info : infos) { - OfflinePlayer temp = Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()); - String name; - if(temp == null){ - name = Main.getInstance().getDatabase().getNameData().getName(info.getUniqueId()); - } else { - name = temp.getName(); - } + String name = Main.getInstance().getDatabase().getNameData().getName(info.getUniqueId()); ChatColor color; switch (i) { case 1: color = ChatColor.YELLOW; break; diff --git a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java index 491c9a4..e12d2d4 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/command/Wins.java @@ -42,11 +42,7 @@ public class Wins implements ICommand { } else { name = args[0]; - if(Main.getInstance().getServer().getOfflinePlayer(args[0]) == null){ - uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[0]); - } else { - uuid = Main.getInstance().getServer().getOfflinePlayer(args[0]).getUniqueId(); - } + uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[0]); } if(uuid == null){ sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java index cbf410a..e5ac4bb 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/NameDataTable.java @@ -20,8 +20,11 @@ package net.tylermurphy.hideAndSeek.database; import net.tylermurphy.hideAndSeek.Main; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.Nullable; +import java.lang.management.BufferPoolMXBean; import java.sql.*; import java.util.UUID; @@ -61,6 +64,11 @@ public class NameDataTable { Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } + OfflinePlayer retry = Bukkit.getOfflinePlayer(uuid); + if(retry != null){ + this.update(uuid, retry.getName()); + return retry.getName(); + } return null; } @@ -78,6 +86,11 @@ public class NameDataTable { Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage()); e.printStackTrace(); } + OfflinePlayer retry = Bukkit.getOfflinePlayer(name); + if(retry != null){ + this.update(retry.getUniqueId(), name); + return retry.getUniqueId(); + } return null; } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java index 34f3a46..78c5e01 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Game.java @@ -223,7 +223,7 @@ public class Game { private void whileWaiting() { if (!lobbyCountdownEnabled) return; if (lobbyMin <= board.size()) { - if (gameTimer == -1) + if (lobbyTimer < 0) lobbyTimer = countdown; if (board.size() >= changeCountdown) lobbyTimer = Math.min(lobbyTimer, 10); @@ -240,7 +240,6 @@ public class Game { } private void whileStarting() { - if(gameTick % 20 == 0) { if (startingTimer % 5 == 0 || startingTimer < 5) { String message; @@ -259,7 +258,7 @@ public class Game { } else if (countdownDisplay == CountdownDisplay.ACTIONBAR) { ActionBar.clearActionBar(player); ActionBar.sendActionBar(player, messagePrefix + message); - } else if (countdownDisplay == CountdownDisplay.TITLE) { + } else if (countdownDisplay == CountdownDisplay.TITLE && startingTimer != 30) { Titles.clearTitle(player); Titles.sendTitle(player, 10, 40, 10, " ", message); } diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 7823fe9..f1a1ce1 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -45,7 +45,7 @@ public class PAPIExpansion extends PlaceholderExpansion { database.getGameData().getInfo(player.getUniqueId()); } else { UUID uuid; - try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } + try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } info = database.getGameData().getInfo(uuid); } if (info == null) return placeholderNoData; @@ -69,7 +69,7 @@ public class PAPIExpansion extends PlaceholderExpansion { database.getGameData().getInfo(player.getUniqueId()); } else { UUID uuid; - try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; } + try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } info = database.getGameData().getInfo(uuid); } if (info == null) return placeholderNoData; From 2169712940956f3cd9ada7e84608a4a3592b293a Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Tue, 24 May 2022 09:03:44 -0400 Subject: [PATCH 60/68] 1.5.0 Release Candidate 4 --- src/main/java/net/tylermurphy/hideAndSeek/game/Board.java | 3 +-- .../net/tylermurphy/hideAndSeek/game/PlayerLoader.java | 1 + .../net/tylermurphy/hideAndSeek/util/PAPIExpansion.java | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java index bb1984e..c6aaaf5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/Board.java @@ -239,7 +239,6 @@ public class Board { board.updateTeams(); } - int timeLeft = Main.getInstance().getGame().getTimeLeft(); Status status = Main.getInstance().getGame().getStatus(); @@ -279,7 +278,7 @@ public class Board { board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_ACTIVE)); } } else if (line.contains("{GLOW}")) { - if (!glowEnabled) return; + if (!glowEnabled) continue; if (glow == null || status == Status.STARTING || !glow.isRunning()) { board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_INACTIVE)); } else { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java index 19a48f4..211a425 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java @@ -70,6 +70,7 @@ public class PlayerLoader { } public static void resetPlayer(Player player, Board board){ + if(board.isSeeker(player)) return; loadPlayer(player); if (board.isSeeker(player)) { if (pvpEnabled) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index f1a1ce1..678b46f 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -40,9 +40,9 @@ public class PAPIExpansion extends PlaceholderExpansion { String[] args = params.split("_"); if (args.length < 1) return null; if (args[0].equals("stats") && (args.length == 2 || args.length == 3)) { - PlayerInfo info = null; + PlayerInfo info; if(args.length == 2) { - database.getGameData().getInfo(player.getUniqueId()); + info = database.getGameData().getInfo(player.getUniqueId()); } else { UUID uuid; try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } @@ -64,9 +64,9 @@ public class PAPIExpansion extends PlaceholderExpansion { } } else if (args[0].equals("rank-place") && (args.length == 2 || args.length == 3)) { if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = null; + PlayerInfo info; if(args.length == 2){ - database.getGameData().getInfo(player.getUniqueId()); + info = database.getGameData().getInfo(player.getUniqueId()); } else { UUID uuid; try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } From 2c49249a34b40fe5c6e583af337edbb2770cc0a6 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Tue, 24 May 2022 13:57:01 -0500 Subject: [PATCH 61/68] clean up placeholder expansion --- .../hideAndSeek/database/GameDataTable.java | 3 +- .../hideAndSeek/util/PAPIExpansion.java | 66 ++++++++----------- 2 files changed, 31 insertions(+), 38 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java b/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java index 128614d..ce392a9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/database/GameDataTable.java @@ -58,7 +58,8 @@ public class GameDataTable { } @Nullable - public PlayerInfo getInfo(UUID uuid) { + public PlayerInfo getInfo(@Nullable UUID uuid) { + if (uuid == null) return null; if(CACHE.containsKey(uuid)) return CACHE.get(uuid); String sql = "SELECT * FROM hs_data WHERE uuid = ?;"; try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index f1a1ce1..bc92ef9 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -6,7 +6,9 @@ import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.util.PlayerInfo; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.util.Optional; import java.util.UUID; import static net.tylermurphy.hideAndSeek.configuration.Config.placeholderError; @@ -38,45 +40,32 @@ public class PAPIExpansion extends PlaceholderExpansion { public String onRequest(OfflinePlayer player, @NotNull String params) { Database database = Main.getInstance().getDatabase(); String[] args = params.split("_"); + if (args.length < 1) return null; - if (args[0].equals("stats") && (args.length == 2 || args.length == 3)) { - PlayerInfo info = null; - if(args.length == 2) { - database.getGameData().getInfo(player.getUniqueId()); - } else { - UUID uuid; - try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } - info = database.getGameData().getInfo(uuid); + if ((args.length == 2 || args.length == 3) && (args[0].equals("stats") || args[0].equals("rank-place"))) { + Optional info = this.getPlayerInfo(args.length == 2 ? player.getUniqueId() : database.getNameData().getUUID(args[2])); + if (info.isPresent()) { + switch (args[0]) { + case "stats": + return getValue(info.get(), args[1]); + case "rank-place": + if (getRanking(args[1]) == null) return placeholderError; + if (getValue(info.get(), args[1]).equals("0")) return "-"; + Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); + if (count == null) return placeholderNoData; + return count.toString(); + } } - if (info == null) return placeholderNoData; - return getValue(info, args[1]); - } else if ((args[0].equals("rank-score") || args[0].equals("rank-name") ) && args.length == 3) { - int place; - try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } - if (place < 1) { return placeholderError; } - if (getRanking(args[1]) == null) { return placeholderError; } + } + + if ((args[0].equals("rank-score") || args[0].equals("rank-name")) && args.length == 3) { + int place = Integer.parseInt(args[2]); + if (place < 1 || getRanking(args[1]) == null) return placeholderError; + PlayerInfo info = database.getGameData().getInfoRanking(getRanking(args[1]), place); if (info == null) return placeholderNoData; - if (args[0].equals("rank-score")) { - return getValue(info, args[1]); - } else { - return Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); - } - } else if (args[0].equals("rank-place") && (args.length == 2 || args.length == 3)) { - if (getRanking(args[1]) == null) { return placeholderError; } - PlayerInfo info = null; - if(args.length == 2){ - database.getGameData().getInfo(player.getUniqueId()); - } else { - UUID uuid; - try { uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[2]); } catch (Exception e) { return placeholderError; } - info = database.getGameData().getInfo(uuid); - } - if (info == null) return placeholderNoData; - if (getValue(info, args[1]).equals("0")) { return "-"; } - Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); - if (count == null) { return placeholderNoData; } - return count.toString(); + + return args[0].equals("rank-score") ? getValue(info, args[1]) : Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName(); } return null; } @@ -113,8 +102,7 @@ public class PAPIExpansion extends PlaceholderExpansion { } } - private String getRanking(String query) { - if (query == null) return null; + private String getRanking(@NotNull String query) { switch (query) { case "total-wins": return "(hider_wins + seeker_wins)"; @@ -145,4 +133,8 @@ public class PAPIExpansion extends PlaceholderExpansion { } } + private Optional getPlayerInfo(@Nullable UUID uniqueId) { + return Optional.ofNullable(Main.getInstance().getDatabase().getGameData().getInfo(uniqueId)); + } + } From 0cfce11a75b5f9b5ef33f819209505febe216420 Mon Sep 17 00:00:00 2001 From: bobby29831 Date: Tue, 24 May 2022 14:10:02 -0500 Subject: [PATCH 62/68] fix merge error (git kraken bug) --- .../java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 92fed1e..2a98433 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -47,8 +47,8 @@ public class PAPIExpansion extends PlaceholderExpansion { if (info.isPresent()) { switch (args[0]) { case "stats": - case "rank-place": return getValue(info.get(), args[1]); + case "rank-place": if (getRanking(args[1]) == null) return placeholderError; Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId()); if (getValue(info.get(), args[1]).equals("0")) return "-"; From a05ba6d1494f1ba0944c1e66a12a72405a2c9a7f Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 25 May 2022 19:39:54 -0400 Subject: [PATCH 63/68] 1.5.0 Release Candidate 4.1 --- .../java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java index 211a425..af59c21 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/PlayerLoader.java @@ -70,7 +70,7 @@ public class PlayerLoader { } public static void resetPlayer(Player player, Board board){ - if(board.isSeeker(player)) return; + if(board.isSpectator(player)) return; loadPlayer(player); if (board.isSeeker(player)) { if (pvpEnabled) From 23401507e4f102e2a8450237eb450d1507157434 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 26 May 2022 09:07:08 -0400 Subject: [PATCH 64/68] 1.5.0 Release Canidate 4.2 --- .../tylermurphy/hideAndSeek/game/listener/DamageHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 68fa84c..55741b6 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -62,7 +62,7 @@ public class DamageHandler implements Listener { return; } // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. - } else if (!pvpEnabled && !allowNaturalCauses) { + } else if (!pvpEnabled && !allowNaturalCauses && board.contains(player)) { event.setCancelled(true); return; } From 15dedc90a434fb21ce392ce0176c475776890a1c Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 26 May 2022 09:57:21 -0400 Subject: [PATCH 65/68] 1.5.0 Release Canidate 4.2b --- .../hideAndSeek/game/listener/DamageHandler.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 55741b6..7f0e4d5 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -61,12 +61,13 @@ public class DamageHandler implements Listener { event.setCancelled(true); return; } - // If there is no attacker, it must of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. - } else if (!pvpEnabled && !allowNaturalCauses && board.contains(player)) { + // If there is no attacker, it most of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. + // Also, if there was no attacker, if the damaged is not a player, ignore them. + } else if (!board.contains(player) || !pvpEnabled && !allowNaturalCauses && board.contains(player)) { event.setCancelled(true); return; } - // Spectators cannot take damage + // Spectators and cannot take damage if (board.isSpectator(player)) { event.setCancelled(true); if (Main.getInstance().supports(18) && player.getLocation().getBlockY() < -64) { From 7e5bd645023c439d806438d51653f74f1c11b686 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Thu, 26 May 2022 11:57:12 -0400 Subject: [PATCH 66/68] 1.5.0 Release Canidate 4.2c --- .../hideAndSeek/game/listener/DamageHandler.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java index 7f0e4d5..19ec83a 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/game/listener/DamageHandler.java @@ -61,9 +61,11 @@ public class DamageHandler implements Listener { event.setCancelled(true); return; } + // If there was no attacker, if the damaged is not a player, ignore them. + } else if (!board.contains(player)) { + return; // If there is no attacker, it most of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event. - // Also, if there was no attacker, if the damaged is not a player, ignore them. - } else if (!board.contains(player) || !pvpEnabled && !allowNaturalCauses && board.contains(player)) { + } else if (!pvpEnabled && !allowNaturalCauses && board.contains(player)) { event.setCancelled(true); return; } From 29b64f4c22b43b60c2bae66a2e32635b5b15e2f4 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Fri, 27 May 2022 09:54:44 -0400 Subject: [PATCH 67/68] 1.5.0 Release Canidate 4.3 --- .../java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java index 2a98433..032deca 100644 --- a/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java +++ b/src/main/java/net/tylermurphy/hideAndSeek/util/PAPIExpansion.java @@ -55,6 +55,11 @@ public class PAPIExpansion extends PlaceholderExpansion { if (count == null) return placeholderNoData; return count.toString(); } + } else switch (args[0]) { + case "stats": + return placeholderNoData; + case "rank-place": + return "-"; } } From b974ff9a1cc5d476c4fb0944f96895016c95e002 Mon Sep 17 00:00:00 2001 From: Tyler Murphy Date: Wed, 1 Jun 2022 20:02:07 -0400 Subject: [PATCH 68/68] Update CONTRIBUTING.md --- CONTRIBUTING.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c9511f3..1e992d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,5 @@ + +## Contributing Guidelines - Do not send any pull requests to the master branch - Any pull requests sent to master will be closed - Send pull requests to the current beta branch (usually named as an unreleased version) @@ -9,4 +11,4 @@ - If making a new language file, follow the local naming convention - localization-[LANGUAGE](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes#)_[TERRITORY](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).yml. You can find the 2-letter codes in the links. - Common sense, please... -- File subject to change in the future \ No newline at end of file +- File subject to change in the future