refactor: general improvements, fix spacing inconsistencies

This commit is contained in:
bobby29831 2022-05-13 12:01:31 -05:00
parent cd0f60bd13
commit 2f4ca0d0f9
39 changed files with 498 additions and 498 deletions

View file

@ -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();
}
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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();

View file

@ -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;
}

View file

@ -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);

View file

@ -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();

View file

@ -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();

View file

@ -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());
}

View file

@ -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);

View file

@ -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<Player> 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;
}

View file

@ -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 {

View file

@ -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<PlayerInfo> 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;

View file

@ -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;
}

View file

@ -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<String> 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<String> tempInteracts = config.getStringList("blockedInteracts");
for(String id : tempInteracts){
for(String id : tempInteracts) {
Optional<XMaterial> 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<String> 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<String> 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"));
}
}

View file

@ -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<String> getStringList(String path){
public List<String> getStringList(String path) {
List<String> 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<String, Object> temp = config.getValues(true);
for(Map.Entry<String, Object> 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<String, Object> 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();
}
}

View file

@ -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"),

View file

@ -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());

View file

@ -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) {

View file

@ -37,7 +37,7 @@ public class PlayerInfoTable {
private static final Map<UUID, PlayerInfo> 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<PlayerInfo> getInfoPage(int page){
public List<PlayerInfo> 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<PlayerInfo> 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<UUID> uuids, List<UUID> winners, Map<String,Integer> hider_kills, Map<String,Integer> hider_deaths, Map<String,Integer> seeker_kills, Map<String,Integer> seeker_deaths, WinType type){
for(UUID uuid : uuids){
public void addWins(List<UUID> uuids, List<UUID> winners, Map<String,Integer> hider_kills, Map<String,Integer> hider_deaths, Map<String,Integer> seeker_kills, Map<String,Integer> 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;

View file

@ -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<Player> getHiders(){
public static List<Player> getHiders() {
return Hider.stream().map(playerList::get).collect(Collectors.toList());
}
public static List<Player> getSeekers(){
public static List<Player> 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<Player> getSpectators(){
public static List<Player> getSpectators() {
return Spectator.stream().map(playerList::get).collect(Collectors.toList());
}
public static List<Player> getPlayers(){
public static List<Player> 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<String, Integer> getHiderKills(){
public static Map<String, Integer> getHiderKills() {
return new HashMap<>(hider_kills);
}
public static Map<String, Integer> getSeekerKills(){
public static Map<String, Integer> getSeekerKills() {
return new HashMap<>(seeker_kills);
}
public static Map<String, Integer> getHiderDeaths(){
public static Map<String, Integer> getHiderDeaths() {
return new HashMap<>(hider_deaths);
}
public static Map<String, Integer> getSeekerDeaths(){
public static Map<String, Integer> 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;
}

View file

@ -37,7 +37,7 @@ public class CommandHandler {
public static final Map<String,ICommand> 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 {

View file

@ -68,36 +68,36 @@ public class Game {
worldLoader = new WorldLoader(spawnWorld);
}
public static void start(){
public static void start() {
Optional<Player> 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<UUID> players = Board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList());
if(type == WinType.HIDER_WIN){
if (type == WinType.HIDER_WIN) {
List<UUID> 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<UUID> 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<Player> 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;
}

View file

@ -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;

View file

@ -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);

View file

@ -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();

View file

@ -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;

View file

@ -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);

View file

@ -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);
}
}

View file

@ -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());

View file

@ -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)";

View file

@ -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));

View file

@ -20,8 +20,7 @@
package net.tylermurphy.hideAndSeek.util;
public enum Status {
STANDBY,
STARTING,
PLAYING,
ENDING
STANDBY, STARTING, PLAYING, ENDING
}

View file

@ -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<String> 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("<player>")) {
if (parameter.equals("<player>")) {
return null;
} else {
List<String> temp = new ArrayList<>();

View file

@ -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;

View file

@ -9,20 +9,20 @@ public class Version {
private static final Map<String,Boolean> 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.length; i++){
for(int i=0; i<serverCheck.length; i++) {
serverCheck[i] = Integer.parseInt(serverCheckTemp[i]);
}
String[] customCheckTemp = testVersion.substring(2).split("\\.");
int[] customCheck = new int[customCheckTemp.length];
for(int i=0; i<customCheck.length; i++){
for(int i=0; i<customCheck.length; i++) {
customCheck[i] = Integer.parseInt(customCheckTemp[i]);
}
@ -31,12 +31,12 @@ public class Version {
return result;
}
private static boolean getResult(int[] customCheck, int[] serverCheck){
if(customCheck[0] > 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;

View file

@ -20,7 +20,7 @@
package net.tylermurphy.hideAndSeek.util;
public enum WinType {
HIDER_WIN,
SEEKER_WIN,
NONE
HIDER_WIN, SEEKER_WIN, NONE
}

View file

@ -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());
}
}