refactor and encapsulate classes

This commit is contained in:
Tyler Murphy 2022-05-13 21:17:46 -04:00
parent 7d152668d7
commit ea8f764931
50 changed files with 1130 additions and 1168 deletions

View file

@ -24,12 +24,12 @@ import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.configuration.Localization;
import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.CommandHandler; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.CommandHandler;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.game.listener.*; import net.tylermurphy.hideAndSeek.game.listener.*;
import net.tylermurphy.hideAndSeek.util.PAPIExpansion; import net.tylermurphy.hideAndSeek.util.PAPIExpansion;
import net.tylermurphy.hideAndSeek.util.TabCompleter; import net.tylermurphy.hideAndSeek.util.TabCompleter;
import net.tylermurphy.hideAndSeek.util.UUIDFetcher;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -42,14 +42,15 @@ import java.util.List;
public class Main extends JavaPlugin implements Listener { public class Main extends JavaPlugin implements Listener {
public static Main plugin; private static Main instance;
public static File root, data;
private int onTickTask; private Database database;
private Board board;
private Game game;
public void onEnable() { public void onEnable() {
plugin = this;
root = this.getServer().getWorldContainer(); instance = this;
data = this.getDataFolder();
this.registerListeners(); this.registerListeners();
@ -58,30 +59,29 @@ public class Main extends JavaPlugin implements Listener {
Items.loadItems(); Items.loadItems();
CommandHandler.registerCommands(); CommandHandler.registerCommands();
Board.reload();
Database.init();
UUIDFetcher.init();
onTickTask = Bukkit.getServer().getScheduler().runTaskTimer(this, () -> { board = new Board();
try{ database = new Database();
Game.onTick();
} catch (Exception e) { game = new Game(board);
e.printStackTrace();
} getServer().getScheduler().runTaskTimer(this, this::onTick,0,1).getTaskId();
},0,1).getTaskId();
Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PAPIExpansion().register(); new PAPIExpansion().register();
} }
} }
public void onDisable() { public void onDisable() {
Main.plugin.getServer().getScheduler().cancelTask(onTickTask);
Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this); Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this);
UUIDFetcher.cleanup(); board.cleanup();
Board.cleanup(); }
private void onTick() {
if(game.getStatus() == Status.ENDED) game = new Game(board);
game.onTick();
} }
private void registerListeners() { private void registerListeners() {
@ -102,5 +102,25 @@ public class Main extends JavaPlugin implements Listener {
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
return TabCompleter.handleTabComplete(sender, args); return TabCompleter.handleTabComplete(sender, args);
} }
public static Main getInstance() {
return instance;
}
public File getWorldContainer() {
return this.getServer().getWorldContainer();
}
public Database getDatabase() {
return database;
}
public Board getBoard(){
return board;
}
public Game getGame(){
return game;
}
} }

View file

@ -20,7 +20,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.game.CommandHandler; import net.tylermurphy.hideAndSeek.util.CommandHandler;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
public class Help implements ICommand { public class Help implements ICommand {

View file

@ -19,8 +19,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -31,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Join implements ICommand { public class Join implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.isNotSetup()) { if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + message("GAME_SETUP")); sender.sendMessage(errorPrefix + message("GAME_SETUP"));
return; return;
} }
@ -40,12 +39,12 @@ public class Join implements ICommand {
sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); sender.sendMessage(errorPrefix + message("COMMAND_ERROR"));
return; return;
} }
if (Board.contains(player)) { if (Main.getInstance().getBoard().contains(player)) {
sender.sendMessage(errorPrefix + message("GAME_INGAME")); sender.sendMessage(errorPrefix + message("GAME_INGAME"));
return; return;
} }
Game.join(player); Main.getInstance().getGame().join(player);
} }
public String getLabel() { public String getLabel() {

View file

@ -19,8 +19,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -31,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Leave implements ICommand { public class Leave implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.isNotSetup()) { if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + message("GAME_SETUP")); sender.sendMessage(errorPrefix + message("GAME_SETUP"));
return; return;
} }
@ -40,11 +39,11 @@ public class Leave implements ICommand {
sender.sendMessage(errorPrefix + message("COMMAND_ERROR")); sender.sendMessage(errorPrefix + message("COMMAND_ERROR"));
return; return;
} }
if (!Board.contains(player)) { if (!Main.getInstance().getBoard().contains(player)) {
sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME"));
return; return;
} }
Game.leave(player); Main.getInstance().getGame().leave(player);
} }
public String getLabel() { public String getLabel() {

View file

@ -19,11 +19,11 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.configuration.Config; import net.tylermurphy.hideAndSeek.configuration.Config;
import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.configuration.Localization; import net.tylermurphy.hideAndSeek.configuration.Localization;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix; import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
@ -34,7 +34,7 @@ public class Reload implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }

View file

@ -20,8 +20,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -39,7 +38,7 @@ public class SaveMap implements ICommand {
sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED")); sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED"));
return; return;
} }
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }
@ -57,12 +56,12 @@ public class SaveMap implements ICommand {
BukkitRunnable runnable = new BukkitRunnable() { BukkitRunnable runnable = new BukkitRunnable() {
public void run() { public void run() {
sender.sendMessage( sender.sendMessage(
Game.worldLoader.save() Main.getInstance().getGame().getWorldLoader().save()
); );
runningBackup = false; runningBackup = false;
} }
}; };
runnable.runTaskAsynchronously(Main.plugin); runnable.runTaskAsynchronously(Main.getInstance());
runningBackup = true; runningBackup = true;
} }

View file

@ -19,8 +19,8 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@ -31,7 +31,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetBorder implements ICommand { public class SetBorder implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }
@ -44,7 +44,7 @@ public class SetBorder implements ICommand {
addToConfig("worldBorder.enabled",false); addToConfig("worldBorder.enabled",false);
saveConfig(); saveConfig();
sender.sendMessage(messagePrefix + message("WORLDBORDER_DISABLE")); sender.sendMessage(messagePrefix + message("WORLDBORDER_DISABLE"));
Game.resetWorldBorder(spawnWorld); Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld);
return; return;
} }
int num,delay,change; int num,delay,change;
@ -90,7 +90,7 @@ public class SetBorder implements ICommand {
addToConfig("worldBorder.move", worldborderChange); addToConfig("worldBorder.move", worldborderChange);
sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay)); sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay));
saveConfig(); saveConfig();
Game.resetWorldBorder(spawnWorld); Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld);
} }
public String getLabel() { public String getLabel() {

View file

@ -19,8 +19,8 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -30,7 +30,7 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetBounds implements ICommand { public class SetBounds implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }

View file

@ -1,74 +0,0 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetExitLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
Vector newExitPosition = new Vector();
Player player = (Player) sender;
if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) {
sender.sendMessage(errorPrefix + message("NOT_AT_ZERO"));
return;
}
newExitPosition.setX(player.getLocation().getBlockX());
newExitPosition.setY(player.getLocation().getBlockY());
newExitPosition.setZ(player.getLocation().getBlockZ());
World world = player.getLocation().getWorld();
if (world == null) {
throw new RuntimeException("Unable to get world: " + spawnWorld);
}
exitWorld = world.getName();
exitPosition = newExitPosition;
sender.sendMessage(messagePrefix + message("EXIT_SPAWN"));
addToConfig("spawns.exit.x", exitPosition.getX());
addToConfig("spawns.exit.y", exitPosition.getY());
addToConfig("spawns.exit.z", exitPosition.getZ());
addToConfig("spawns.exit.world", player.getLocation().getWorld().getName());
saveConfig();
}
public String getLabel() {
return "setexit";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks exit location to current position and world";
}
}

View file

@ -1,74 +0,0 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetLobbyLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
Vector newLobbyPosition = new Vector();
Player player = (Player) sender;
if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) {
sender.sendMessage(errorPrefix + message("NOT_AT_ZERO"));
return;
}
newLobbyPosition.setX(player.getLocation().getBlockX());
newLobbyPosition.setY(player.getLocation().getBlockY());
newLobbyPosition.setZ(player.getLocation().getBlockZ());
World world = player.getLocation().getWorld();
if (world == null) {
throw new RuntimeException("Unable to get world: " + spawnWorld);
}
lobbyWorld = world.getName();
lobbyPosition = newLobbyPosition;
sender.sendMessage(messagePrefix + message("LOBBY_SPAWN"));
addToConfig("spawns.lobby.x", lobbyPosition.getX());
addToConfig("spawns.lobby.y", lobbyPosition.getY());
addToConfig("spawns.lobby.z", lobbyPosition.getZ());
addToConfig("spawns.lobby.world", player.getLocation().getWorld().getName());
saveConfig();
}
public String getLabel() {
return "setlobby";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks lobby location to current position";
}
}

View file

@ -1,83 +0,0 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.world.WorldLoader;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetSpawnLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (Game.status != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
Vector newSpawnPosition = new Vector();
Player player = (Player) sender;
if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0) {
sender.sendMessage(errorPrefix + message("NOT_AT_ZERO"));
return;
}
newSpawnPosition.setX(player.getLocation().getBlockX());
newSpawnPosition.setY(player.getLocation().getBlockY());
newSpawnPosition.setZ(player.getLocation().getBlockZ());
if (worldborderEnabled && newSpawnPosition.distance(worldborderPosition) > 100) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION"));
return;
}
World world = player.getLocation().getWorld();
if (world == null) {
throw new RuntimeException("Unable to get world: " + spawnWorld);
}
if (mapSaveEnabled && !world.getName().equals(spawnWorld)) {
Game.worldLoader.unloadMap();
Game.worldLoader = new WorldLoader(world.getName());
}
spawnWorld = world.getName();
spawnPosition = newSpawnPosition;
sender.sendMessage(messagePrefix + message("GAME_SPAWN"));
addToConfig("spawns.game.x", spawnPosition.getX());
addToConfig("spawns.game.y", spawnPosition.getY());
addToConfig("spawns.game.z", spawnPosition.getZ());
addToConfig("spawns.game.world", player.getLocation().getWorld().getName());
saveConfig();
}
public String getLabel() {
return "setspawn";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks spawn location to current position";
}
}

View file

@ -20,7 +20,6 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.io.File; import java.io.File;
@ -52,7 +51,7 @@ public class Setup implements ICommand {
count++; count++;
} }
if (mapSaveEnabled) { if (mapSaveEnabled) {
File destenation = new File(Main.root + File.separator + Game.getGameWorld()); File destenation = new File(Main.getInstance().getWorldContainer() + File.separator + Main.getInstance().getGame().getGameWorld());
if (!destenation.exists()) { if (!destenation.exists()) {
msg = msg + "\n" + message("SETUP_SAVEMAP"); msg = msg + "\n" + message("SETUP_SAVEMAP");
count++; count++;

View file

@ -20,9 +20,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -37,27 +35,27 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Start implements ICommand { public class Start implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.isNotSetup()) { if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + message("GAME_SETUP")); sender.sendMessage(errorPrefix + message("GAME_SETUP"));
return; return;
} }
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }
if (!Board.contains(sender)) { if (!Main.getInstance().getBoard().contains(sender)) {
sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME")); sender.sendMessage(errorPrefix + message("GAME_NOT_INGAME"));
return; return;
} }
if (Board.size() < minPlayers) { if (Main.getInstance().getBoard().size() < minPlayers) {
sender.sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); sender.sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers));
return; return;
} }
String seekerName; String seekerName;
if (args.length < 1) { if (args.length < 1) {
Optional<Player> rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); Optional<Player> rand = Main.getInstance().getBoard().getPlayers().stream().skip(new Random().nextInt(Main.getInstance().getBoard().size())).findFirst();
if (!rand.isPresent()) { if (!rand.isPresent()) {
Main.plugin.getLogger().warning("Failed to select random seeker."); Main.getInstance().getLogger().warning("Failed to select random seeker.");
return; return;
} }
seekerName = rand.get().getName(); seekerName = rand.get().getName();
@ -69,12 +67,12 @@ public class Start implements ICommand {
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName));
return; return;
} }
Player seeker = Board.getPlayer(temp.getUniqueId()); Player seeker = Main.getInstance().getBoard().getPlayer(temp.getUniqueId());
if (seeker == null) { if (seeker == null) {
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName)); sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName));
return; return;
} }
Game.start(seeker); Main.getInstance().getGame().start(seeker);
} }
public String getLabel() { public String getLabel() {

View file

@ -19,8 +19,8 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix; import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix;
@ -30,13 +30,13 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Stop implements ICommand { public class Stop implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
if (Game.isNotSetup()) { if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do"); sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do");
return; return;
} }
if (Game.status == Status.STARTING || Game.status == Status.PLAYING) { if (Main.getInstance().getGame().getStatus() == Status.STARTING || Main.getInstance().getGame().getStatus() == Status.PLAYING) {
Game.broadcastMessage(abortPrefix + message("STOP")); Main.getInstance().getGame().broadcastMessage(abortPrefix + message("STOP"));
Game.end(); Main.getInstance().getGame().end();
} else { } else {
sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS")); sender.sendMessage(errorPrefix + message("GAME_NOT_INPROGRESS"));
} }

View file

@ -20,7 +20,6 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.database.PlayerInfo; import net.tylermurphy.hideAndSeek.database.PlayerInfo;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -48,14 +47,14 @@ public class Top implements ICommand {
StringBuilder message = new StringBuilder(String.format( StringBuilder message = new StringBuilder(String.format(
"%s------- %sLEADERBOARD %s(Page %s) %s-------\n", "%s------- %sLEADERBOARD %s(Page %s) %s-------\n",
ChatColor.WHITE, ChatColor.BOLD, ChatColor.GRAY, page, ChatColor.WHITE)); ChatColor.WHITE, ChatColor.BOLD, ChatColor.GRAY, page, ChatColor.WHITE));
List<PlayerInfo> infos = Database.playerInfo.getInfoPage(page); List<PlayerInfo> infos = Main.getInstance().getDatabase().getGameData().getInfoPage(page);
int i = 1 + (page-1)*10; int i = 1 + (page-1)*10;
if (infos == null) { if (infos == null) {
sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); sender.sendMessage(errorPrefix + message("NO_GAME_INFO"));
return; return;
} }
for(PlayerInfo info : infos) { for(PlayerInfo info : infos) {
String name = Main.plugin.getServer().getOfflinePlayer(info.uuid).getName(); String name = Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName();
ChatColor color; ChatColor color;
switch (i) { switch (i) {
case 1: color = ChatColor.YELLOW; break; case 1: color = ChatColor.YELLOW; break;

View file

@ -20,9 +20,7 @@
package net.tylermurphy.hideAndSeek.command; package net.tylermurphy.hideAndSeek.command;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.database.PlayerInfo; import net.tylermurphy.hideAndSeek.database.PlayerInfo;
import net.tylermurphy.hideAndSeek.util.UUIDFetcher;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -35,12 +33,12 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Wins implements ICommand { public class Wins implements ICommand {
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
Main.plugin.getServer().getScheduler().runTaskAsynchronously(Main.plugin, () -> { Main.getInstance().getServer().getScheduler().runTaskAsynchronously(Main.getInstance(), () -> {
UUID uuid; UUID uuid;
String name; String name;
if (args.length == 0) { if (args.length == 0) {
Player player = Main.plugin.getServer().getPlayer(sender.getName()); Player player = Main.getInstance().getServer().getPlayer(sender.getName());
if (player == null) { if (player == null) {
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName())); sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName()));
return; return;
@ -51,13 +49,13 @@ public class Wins implements ICommand {
else { else {
try { try {
name = args[0]; name = args[0];
uuid = UUIDFetcher.getUUID(args[0]); uuid = Main.getInstance().getServer().getOfflinePlayer(args[0]).getUniqueId();
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0])); sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0]));
return; return;
} }
} }
PlayerInfo info = Database.playerInfo.getInfo(uuid); PlayerInfo info = Main.getInstance().getDatabase().getGameData().getInfo(uuid);
if (info == null) { if (info == null) {
sender.sendMessage(errorPrefix + message("NO_GAME_INFO")); sender.sendMessage(errorPrefix + message("NO_GAME_INFO"));
return; return;

View file

@ -0,0 +1,53 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command.location;
import net.tylermurphy.hideAndSeek.command.ICommand;
import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils;
import net.tylermurphy.hideAndSeek.command.location.util.Locations;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class SetExitLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) return;
Player player = (Player) sender;
LocationUtils.setLocation(player, Locations.EXIT, vector -> {
exitWorld = player.getLocation().getWorld().getName();
exitPosition = vector;
});
}
public String getLabel() {
return "setexit";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks exit location to current position and world";
}
}

View file

@ -0,0 +1,54 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command.location;
import net.tylermurphy.hideAndSeek.command.ICommand;
import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils;
import net.tylermurphy.hideAndSeek.command.location.util.Locations;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class SetLobbyLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) return;
Player player = (Player) sender;
LocationUtils.setLocation(player, Locations.LOBBY, vector -> {
lobbyWorld = player.getLocation().getWorld().getName();
lobbyPosition = vector;
});
}
public String getLabel() {
return "setlobby";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks lobby location to current position";
}
}

View file

@ -0,0 +1,66 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.command.location;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.command.ICommand;
import net.tylermurphy.hideAndSeek.command.location.util.LocationUtils;
import net.tylermurphy.hideAndSeek.command.location.util.Locations;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetSpawnLocation implements ICommand {
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) return;
Player player = (Player) sender;
LocationUtils.setLocation(player, Locations.GAME, vector -> {
if (worldborderEnabled && vector.distance(worldborderPosition) > 100) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION"));
throw new RuntimeException("World border not enabled or not in valid position!");
}
if (!player.getLocation().getWorld().getName().equals(spawnWorld)) {
Main.getInstance().getGame().getWorldLoader().unloadMap();
Main.getInstance().getGame().getWorldLoader().setNewMap(player.getLocation().getWorld().getName());
}
spawnWorld = player.getLocation().getWorld().getName();
spawnPosition = vector;
});
}
public String getLabel() {
return "setspawn";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Sets hide and seeks spawn location to current position";
}
}

View file

@ -0,0 +1,57 @@
package net.tylermurphy.hideAndSeek.command.location.util;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
import java.util.function.Consumer;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class LocationUtils {
/**
* Provides a vector for a player
* @param player the player to create the vector for
* @return the vector
*/
private static @Nullable Vector vector(Player player) {
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
player.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return null;
}
if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0 || player.getLocation().getBlockY() == 0){
player.sendMessage(errorPrefix + message("NOT_AT_ZERO"));
return null;
}
Location loc = player.getLocation();
return new Vector(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public static void setLocation(Player player, Locations place, @Nullable Consumer<Vector> consumer) {
Vector vec = vector(player);
World world = player.getLocation().getWorld();
if(world == null) {
throw new RuntimeException("Unable to get world: " + spawnWorld);
}
consumer.accept(vec);
player.sendMessage(messagePrefix + message(place.message()));
addToConfig(place.path("x"), vec.getX());
addToConfig(place.path("y"), vec.getY());
addToConfig(place.path("z"), vec.getZ());
addToConfig(place.path("world"), player.getLocation().getWorld().getName());
saveConfig();
}
}

View file

@ -0,0 +1,27 @@
package net.tylermurphy.hideAndSeek.command.location.util;
public enum Locations {
GAME("spawns.game", "GAME_SPAWN"),
LOBBY("spawns.lobby", "LOBBY_SPAWN"),
EXIT("spawns.exit", "EXIT_SPAWN");
private final String path, message;
Locations(String path, String message) {
this.path = path;
this.message = message;
}
public String message() {
return message;
}
public String path() {
return path;
}
public String path(String additive) {
return path + "." + additive;
}
}

View file

@ -23,8 +23,8 @@ import com.cryptomorin.xseries.XItemStack;
import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound; import com.cryptomorin.xseries.XSound;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.CountdownDisplay; import net.tylermurphy.hideAndSeek.game.util.CountdownDisplay;
import net.tylermurphy.hideAndSeek.util.Version; import net.tylermurphy.hideAndSeek.game.util.Version;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
@ -266,7 +266,7 @@ public class Config {
countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay")); countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay"));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
countdownDisplay = CountdownDisplay.CHAT; countdownDisplay = CountdownDisplay.CHAT;
Main.plugin.getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!"); Main.getInstance().getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!");
} }
blockedInteracts = new ArrayList<>(); blockedInteracts = new ArrayList<>();
List<String> tempInteracts = config.getStringList("blockedInteracts"); List<String> tempInteracts = config.getStringList("blockedInteracts");

View file

@ -47,9 +47,9 @@ public class ConfigManager {
private ConfigManager(String filename, String defaultFilename) { private ConfigManager(String filename, String defaultFilename) {
this.defaultFilename = defaultFilename; this.defaultFilename = defaultFilename;
this.file = new File(Main.data, filename); this.file = new File(Main.getInstance().getDataFolder(), filename);
File folder = Main.data; File folder = Main.getInstance().getDataFolder();
if (!folder.exists()) { if (!folder.exists()) {
if (!folder.mkdirs()) { if (!folder.mkdirs()) {
throw new RuntimeException("Failed to make directory: " + file.getPath()); throw new RuntimeException("Failed to make directory: " + file.getPath());
@ -58,7 +58,7 @@ public class ConfigManager {
if (!file.exists()) { if (!file.exists()) {
try{ try{
InputStream input = Main.plugin.getResource(defaultFilename); InputStream input = Main.getInstance().getResource(defaultFilename);
if (input == null) { if (input == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename); throw new RuntimeException("Could not create input stream for "+defaultFilename);
} }
@ -181,7 +181,7 @@ public class ConfigManager {
public void resetFile(String newDefaultFilename) { public void resetFile(String newDefaultFilename) {
this.defaultFilename = newDefaultFilename; this.defaultFilename = newDefaultFilename;
InputStream input = Main.plugin.getResource(defaultFilename); InputStream input = Main.getInstance().getResource(defaultFilename);
if (input == null) { if (input == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename); throw new RuntimeException("Could not create input stream for "+defaultFilename);
} }
@ -214,7 +214,7 @@ public class ConfigManager {
public void saveConfig() { public void saveConfig() {
try { try {
InputStream is = Main.plugin.getResource(defaultFilename); InputStream is = Main.getInstance().getResource(defaultFilename);
if (is == null) { if (is == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename); throw new RuntimeException("Could not create input stream for "+defaultFilename);
} }

View file

@ -20,7 +20,7 @@
package net.tylermurphy.hideAndSeek.configuration; package net.tylermurphy.hideAndSeek.configuration;
import com.cryptomorin.xseries.XItemStack; import com.cryptomorin.xseries.XItemStack;
import net.tylermurphy.hideAndSeek.util.Version; import net.tylermurphy.hideAndSeek.game.util.Version;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;

View file

@ -23,6 +23,7 @@ import com.google.common.io.ByteStreams;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import org.sqlite.SQLiteConfig; import org.sqlite.SQLiteConfig;
import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -34,38 +35,15 @@ import java.util.UUID;
public class Database { public class Database {
private static final File databaseFile = new File(Main.data, "database.db"); private final File databaseFile = new File(Main.getInstance().getDataFolder(), "database.db");
private final PlayerInfoTable playerInfo;
private final SQLiteConfig config;
public static PlayerInfoTable playerInfo; public Database(){
private static SQLiteConfig config;
protected static Connection connect() {
Connection conn = null;
try {
String url = "jdbc:sqlite:"+databaseFile;
conn = DriverManager.getConnection(url, config.toProperties());
} catch (SQLException e) {
Main.plugin.getLogger().severe(e.getMessage());
e.printStackTrace();
}
return conn;
}
protected static UUID convertBinaryStream(InputStream stream) {
ByteBuffer buffer = ByteBuffer.allocate(16);
try {
buffer.put(ByteStreams.toByteArray(stream));
buffer.flip();
return new UUID(buffer.getLong(), buffer.getLong());
} catch (IOException ignored) {}
return null;
}
public static void init() {
try { try {
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
Main.plugin.getLogger().severe(e.getMessage()); Main.getInstance().getLogger().severe(e.getMessage());
throw new RuntimeException(e.getMessage()); throw new RuntimeException(e.getMessage());
} }
@ -73,7 +51,55 @@ public class Database {
config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL); config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL);
config.setTempStore(SQLiteConfig.TempStore.MEMORY); config.setTempStore(SQLiteConfig.TempStore.MEMORY);
playerInfo = new PlayerInfoTable(); playerInfo = new PlayerInfoTable(this);
}
public PlayerInfoTable getGameData(){
return playerInfo;
}
protected Connection connect() {
Connection conn = null;
try {
String url = "jdbc:sqlite:"+databaseFile;
conn = DriverManager.getConnection(url, config.toProperties());
} catch (SQLException e) {
Main.getInstance().getLogger().severe(e.getMessage());
e.printStackTrace();
}
return conn;
}
protected byte[] encodeUUID(UUID uuid) {
try {
byte[] bytes = new byte[16];
ByteBuffer.wrap(bytes)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
InputStream is = new ByteArrayInputStream(bytes);
byte[] result = new byte[is.available()];
if (is.read(result) == -1) {
Main.getInstance().getLogger().severe("IO Error: Failed to read bytes from input stream");
return new byte[0];
}
return result;
} catch (IOException e) {
Main.getInstance().getLogger().severe("IO Error: " + e.getMessage());
return new byte[0];
}
}
protected UUID decodeUUID(byte[] bytes) {
InputStream is = new ByteArrayInputStream(bytes);
ByteBuffer buffer = ByteBuffer.allocate(16);
try {
buffer.put(ByteStreams.toByteArray(is));
buffer.flip();
return new UUID(buffer.getLong(), buffer.getLong());
} catch (IOException e) {
Main.getInstance().getLogger().severe("IO Error: " + e.getMessage());
}
return null;
} }
} }

View file

@ -19,25 +19,20 @@
package net.tylermurphy.hideAndSeek.database; package net.tylermurphy.hideAndSeek.database;
import com.google.common.io.ByteStreams;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.util.WinType; import net.tylermurphy.hideAndSeek.game.util.WinType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
public class PlayerInfoTable { public class PlayerInfoTable {
private static final Map<UUID, PlayerInfo> CACHE = new HashMap<>(); private final Map<UUID, PlayerInfo> CACHE = new HashMap<>();
private final Database database;
protected PlayerInfoTable() { protected PlayerInfoTable(Database database) {
String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n" String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n"
+ " uuid BINARY(16) PRIMARY KEY,\n" + " uuid BINARY(16) PRIMARY KEY,\n"
@ -51,51 +46,22 @@ public class PlayerInfoTable {
+ " seeker_deaths int NOT NULL\n" + " 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); statement.executeUpdate(sql);
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
this.database = database;
} }
private byte[] encodeUUID(UUID uuid) { @Nullable
try {
byte[] bytes = new byte[16];
ByteBuffer.wrap(bytes)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
InputStream is = new ByteArrayInputStream(bytes);
byte[] result = new byte[is.available()];
if (is.read(result) == -1) {
Main.plugin.getLogger().severe("IO Error: Failed to read bytes from input stream");
return new byte[0];
}
return result;
} catch (IOException e) {
Main.plugin.getLogger().severe("IO Error: " + e.getMessage());
return new byte[0];
}
}
private UUID decodeUUID(byte[] bytes) {
InputStream is = new ByteArrayInputStream(bytes);
ByteBuffer buffer = ByteBuffer.allocate(16);
try {
buffer.put(ByteStreams.toByteArray(is));
buffer.flip();
return new UUID(buffer.getLong(), buffer.getLong());
} catch (IOException e) {
Main.plugin.getLogger().severe("IO Error: " + e.getMessage());
}
return null;
}
@NotNull
public PlayerInfo getInfo(UUID uuid) { public PlayerInfo getInfo(UUID uuid) {
if(CACHE.containsKey(uuid)) return CACHE.get(uuid);
String sql = "SELECT * FROM hs_data WHERE 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)); statement.setBytes(1, database.encodeUUID(uuid));
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
PlayerInfo info = new PlayerInfo( PlayerInfo info = new PlayerInfo(
@ -116,20 +82,20 @@ public class PlayerInfoTable {
} }
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
return new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0); return null;
} }
@Nullable @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 ?;"; 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); statement.setInt(1, place-1);
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
UUID uuid = decodeUUID(rs.getBytes("uuid")); UUID uuid = database.decodeUUID(rs.getBytes("uuid"));
PlayerInfo info = new PlayerInfo( PlayerInfo info = new PlayerInfo(
uuid, uuid,
rs.getInt("hider_wins"), rs.getInt("hider_wins"),
@ -148,7 +114,7 @@ public class PlayerInfoTable {
} }
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -157,13 +123,13 @@ public class PlayerInfoTable {
@Nullable @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 ?;"; 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); statement.setInt(1, (page-1)*10);
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
List<PlayerInfo> infoList = new ArrayList<>(); List<PlayerInfo> infoList = new ArrayList<>();
while(rs.next()) { while(rs.next()) {
PlayerInfo info = new PlayerInfo( PlayerInfo info = new PlayerInfo(
decodeUUID(rs.getBytes("uuid")), database.decodeUUID(rs.getBytes("uuid")),
rs.getInt("hider_wins"), rs.getInt("hider_wins"),
rs.getInt("seeker_wins"), rs.getInt("seeker_wins"),
rs.getInt("hider_games"), rs.getInt("hider_games"),
@ -179,7 +145,7 @@ public class PlayerInfoTable {
connection.close(); connection.close();
return infoList; return infoList;
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -188,37 +154,40 @@ public class PlayerInfoTable {
@Nullable @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;"; 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)); statement.setBytes(1, database.encodeUUID(uuid));
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
if (rs.next()) { if (rs.next()) {
return rs.getInt("total"); return rs.getInt("total");
} }
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
return null; 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) { public void addWins(Board board, 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) { 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 (?,?,?,?,?,?,?,?,?)"; 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); PlayerInfo info = getInfo(uuid);
try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { if(info == null){
statement.setBytes(1, encodeUUID(uuid)); info = new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0);
}
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setBytes(1, database.encodeUUID(uuid));
statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0)); statement.setInt(2, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0));
statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0)); statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0));
statement.setInt(4, info.hider_games + (Board.isHider(uuid) || (Board.isSeeker(uuid) && !Board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0)); statement.setInt(4, info.hider_games + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0));
statement.setInt(5, info.seeker_games + (Board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0)); statement.setInt(5, info.seeker_games + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0));
statement.setInt(6, info.hider_kills + hider_kills.getOrDefault(uuid.toString(), 0)); statement.setInt(6, info.hider_kills + hider_kills.getOrDefault(uuid.toString(), 0));
statement.setInt(7, info.seeker_kills + seeker_kills.getOrDefault(uuid.toString(), 0)); statement.setInt(7, info.seeker_kills + seeker_kills.getOrDefault(uuid.toString(), 0));
statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0)); statement.setInt(8, info.hider_deaths + hider_deaths.getOrDefault(uuid.toString(), 0));
statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0)); statement.setInt(9, info.seeker_deaths + seeker_deaths.getOrDefault(uuid.toString(), 0));
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage()); Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
return; return;
} finally { } finally {

View file

@ -19,8 +19,12 @@
package net.tylermurphy.hideAndSeek.game; package net.tylermurphy.hideAndSeek.game;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Version; import net.tylermurphy.hideAndSeek.game.events.Border;
import net.tylermurphy.hideAndSeek.game.events.Glow;
import net.tylermurphy.hideAndSeek.game.events.Taunt;
import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.game.util.Version;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -35,110 +39,110 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Board { public class Board {
private static final List<String> Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>(); private final List<String> Hider = new ArrayList<>(), Seeker = new ArrayList<>(), Spectator = new ArrayList<>();
private static final Map<String, Player> playerList = new HashMap<>(); private final Map<String, Player> playerList = new HashMap<>();
private static final Map<String, CustomBoard> customBoards = new HashMap<>(); private final Map<String, CustomBoard> customBoards = new HashMap<>();
private static final Map<String, Integer> hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>(); private final Map<String, Integer> hider_kills = new HashMap<>(), seeker_kills = new HashMap<>(), hider_deaths = new HashMap<>(), seeker_deaths = new HashMap<>();
public static boolean contains(Player player) { public boolean contains(Player player) {
return playerList.containsKey(player.getUniqueId().toString()); return playerList.containsKey(player.getUniqueId().toString());
} }
public static boolean contains(CommandSender sender) { public boolean contains(CommandSender sender) {
return contains((Player) sender); return contains((Player) sender);
} }
public static boolean isHider(Player player) { public boolean isHider(Player player) {
return Hider.contains(player.getUniqueId().toString()); return Hider.contains(player.getUniqueId().toString());
} }
public static boolean isHider(UUID uuid) { public boolean isHider(UUID uuid) {
return Hider.contains(uuid.toString()); return Hider.contains(uuid.toString());
} }
public static boolean isSeeker(Player player) { public boolean isSeeker(Player player) {
return Seeker.contains(player.getUniqueId().toString()); return Seeker.contains(player.getUniqueId().toString());
} }
public static boolean isSeeker(UUID uuid) { public boolean isSeeker(UUID uuid) {
return Seeker.contains(uuid.toString()); return Seeker.contains(uuid.toString());
} }
public static boolean isSpectator(Player player) { public boolean isSpectator(Player player) {
return Spectator.contains(player.getUniqueId().toString()); return Spectator.contains(player.getUniqueId().toString());
} }
public static int sizeHider() { public int sizeHider() {
return Hider.size(); return Hider.size();
} }
public static int sizeSeeker() { public int sizeSeeker() {
return Seeker.size(); return Seeker.size();
} }
public static int size() { public int size() {
return playerList.values().size(); return playerList.values().size();
} }
public static List<Player> getHiders() { public List<Player> getHiders() {
return Hider.stream().map(playerList::get).collect(Collectors.toList()); return Hider.stream().map(playerList::get).collect(Collectors.toList());
} }
public static List<Player> getSeekers() { public List<Player> getSeekers() {
return Seeker.stream().map(playerList::get).collect(Collectors.toList()); return Seeker.stream().map(playerList::get).collect(Collectors.toList());
} }
public static Player getFirstSeeker() { public Player getFirstSeeker() {
return playerList.get(Seeker.get(0)); return playerList.get(Seeker.get(0));
} }
public static List<Player> getSpectators() { public List<Player> getSpectators() {
return Spectator.stream().map(playerList::get).collect(Collectors.toList()); return Spectator.stream().map(playerList::get).collect(Collectors.toList());
} }
public static List<Player> getPlayers() { public List<Player> getPlayers() {
return new ArrayList<>(playerList.values()); return new ArrayList<>(playerList.values());
} }
public static Player getPlayer(UUID uuid) { public Player getPlayer(UUID uuid) {
return playerList.get(uuid.toString()); return playerList.get(uuid.toString());
} }
public static void addHider(Player player) { public void addHider(Player player) {
Hider.add(player.getUniqueId().toString()); Hider.add(player.getUniqueId().toString());
Seeker.remove(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString());
Spectator.remove(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString());
playerList.put(player.getUniqueId().toString(), player); playerList.put(player.getUniqueId().toString(), player);
} }
public static void addSeeker(Player player) { public void addSeeker(Player player) {
Hider.remove(player.getUniqueId().toString()); Hider.remove(player.getUniqueId().toString());
Seeker.add(player.getUniqueId().toString()); Seeker.add(player.getUniqueId().toString());
Spectator.remove(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString());
playerList.put(player.getUniqueId().toString(), player); playerList.put(player.getUniqueId().toString(), player);
} }
public static void addSpectator(Player player) { public void addSpectator(Player player) {
Hider.remove(player.getUniqueId().toString()); Hider.remove(player.getUniqueId().toString());
Seeker.remove(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString());
Spectator.add(player.getUniqueId().toString()); Spectator.add(player.getUniqueId().toString());
playerList.put(player.getUniqueId().toString(), player); playerList.put(player.getUniqueId().toString(), player);
} }
public static void remove(Player player) { public void remove(Player player) {
Hider.remove(player.getUniqueId().toString()); Hider.remove(player.getUniqueId().toString());
Seeker.remove(player.getUniqueId().toString()); Seeker.remove(player.getUniqueId().toString());
Spectator.remove(player.getUniqueId().toString()); Spectator.remove(player.getUniqueId().toString());
playerList.remove(player.getUniqueId().toString()); playerList.remove(player.getUniqueId().toString());
} }
public static boolean onSameTeam(Player player1, Player player2) { public boolean onSameTeam(Player player1, Player player2) {
if (Hider.contains(player1.getUniqueId().toString()) && Hider.contains(player2.getUniqueId().toString())) return true; 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 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()); else return Spectator.contains(player1.getUniqueId().toString()) && Spectator.contains(player2.getUniqueId().toString());
} }
public static void reload() { public void reload() {
Hider.clear(); Hider.clear();
Seeker.clear(); Seeker.clear();
Spectator.clear(); Spectator.clear();
@ -148,7 +152,7 @@ public class Board {
seeker_deaths.clear(); seeker_deaths.clear();
} }
public static void addKill(UUID uuid) { public void addKill(UUID uuid) {
if (Hider.contains(uuid.toString())) { if (Hider.contains(uuid.toString())) {
if (hider_kills.containsKey(uuid.toString())) { if (hider_kills.containsKey(uuid.toString())) {
hider_kills.put(uuid.toString(), hider_kills.get(uuid.toString())+1); hider_kills.put(uuid.toString(), hider_kills.get(uuid.toString())+1);
@ -164,7 +168,7 @@ public class Board {
} }
} }
public static void addDeath(UUID uuid) { public void addDeath(UUID uuid) {
if (Hider.contains(uuid.toString())) { if (Hider.contains(uuid.toString())) {
if (hider_deaths.containsKey(uuid.toString())) { if (hider_deaths.containsKey(uuid.toString())) {
hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1); hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1);
@ -180,24 +184,24 @@ public class Board {
} }
} }
public static Map<String, Integer> getHiderKills() { public Map<String, Integer> getHiderKills() {
return new HashMap<>(hider_kills); return new HashMap<>(hider_kills);
} }
public static Map<String, Integer> getSeekerKills() { public Map<String, Integer> getSeekerKills() {
return new HashMap<>(seeker_kills); return new HashMap<>(seeker_kills);
} }
public static Map<String, Integer> getHiderDeaths() { public Map<String, Integer> getHiderDeaths() {
return new HashMap<>(hider_deaths); return new HashMap<>(hider_deaths);
} }
public static Map<String, Integer> getSeekerDeaths() { public Map<String, Integer> getSeekerDeaths() {
return new HashMap<>(seeker_deaths); return new HashMap<>(seeker_deaths);
} }
public static void createLobbyBoard(Player player) { public void createLobbyBoard(Player player) {
createLobbyBoard(player, true); createLobbyBoard(player, true);
} }
private static void createLobbyBoard(Player player, boolean recreate) { private void createLobbyBoard(Player player, boolean recreate) {
CustomBoard board = customBoards.get(player.getUniqueId().toString()); CustomBoard board = customBoards.get(player.getUniqueId().toString());
if (recreate) { if (recreate) {
board = new CustomBoard(player, LOBBY_TITLE); board = new CustomBoard(player, LOBBY_TITLE);
@ -210,10 +214,10 @@ public class Board {
} else if (line.contains("{COUNTDOWN}")) { } else if (line.contains("{COUNTDOWN}")) {
if (!lobbyCountdownEnabled) { if (!lobbyCountdownEnabled) {
board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_ADMINSTART)); board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_ADMINSTART));
} else if (Game.countdownTime == -1) { } else if (Main.getInstance().getGame().getLobbyTime() == -1) {
board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_WAITING)); board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_WAITING));
} else { } else {
board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_COUNTING.replace("{AMOUNT}",Game.countdownTime+""))); board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_COUNTING.replace("{AMOUNT}",Main.getInstance().getGame().getLobbyTime()+"")));
} }
} else if (line.contains("{COUNT}")) { } else if (line.contains("{COUNT}")) {
board.setLine(String.valueOf(i), line.replace("{COUNT}", getPlayers().size()+"")); board.setLine(String.valueOf(i), line.replace("{COUNT}", getPlayers().size()+""));
@ -230,51 +234,59 @@ public class Board {
customBoards.put(player.getUniqueId().toString(), board); customBoards.put(player.getUniqueId().toString(), board);
} }
public static void createGameBoard(Player player) { public void createGameBoard(Player player) {
createGameBoard(player, true); createGameBoard(player, true);
} }
private static void createGameBoard(Player player, boolean recreate) { private void createGameBoard(Player player, boolean recreate) {
CustomBoard board = customBoards.get(player.getUniqueId().toString()); CustomBoard board = customBoards.get(player.getUniqueId().toString());
if (recreate) { if (recreate) {
board = new CustomBoard(player, GAME_TITLE); board = new CustomBoard(player, GAME_TITLE);
board.updateTeams(); board.updateTeams();
} }
int timeLeft = Main.getInstance().getGame().getTimeLeft();
Status status = Main.getInstance().getGame().getStatus();
Taunt taunt = Main.getInstance().getGame().getTaunt();
Border worldBorder = Main.getInstance().getGame().getBorder();
Glow glow = Main.getInstance().getGame().getGlow();
int i = 0; int i = 0;
for(String line : GAME_CONTENTS) { for(String line : GAME_CONTENTS) {
if (line.equalsIgnoreCase("")) { if (line.equalsIgnoreCase("")) {
board.addBlank(); board.addBlank();
} else { } else {
if (line.contains("{TIME}")) { if (line.contains("{TIME}")) {
String value = Game.timeLeft/60 + "m" + Game.timeLeft%60 + "s"; String value = timeLeft/60 + "m" + timeLeft%60 + "s";
board.setLine(String.valueOf(i), line.replace("{TIME}", value)); board.setLine(String.valueOf(i), line.replace("{TIME}", value));
} else if (line.contains("{TEAM}")) { } else if (line.contains("{TEAM}")) {
String value = getTeam(player); String value = getTeam(player);
board.setLine(String.valueOf(i), line.replace("{TEAM}", value)); board.setLine(String.valueOf(i), line.replace("{TEAM}", value));
} else if (line.contains("{BORDER}")) { } else if (line.contains("{BORDER}")) {
if (!worldborderEnabled) continue; if (!worldborderEnabled) continue;
if (Game.worldBorder == null || Game.status == Status.STARTING) { if (worldBorder == null || status == Status.STARTING) {
board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replace("{AMOUNT}", "0"))); board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replace("{AMOUNT}", "0")));
} else if (!Game.worldBorder.isRunning()) { } else if (!worldBorder.isRunning()) {
board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()/60+"").replaceFirst("\\{AMOUNT}", Game.worldBorder.getDelay()%60+""))); board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_COUNTING.replaceFirst("\\{AMOUNT}", worldBorder.getDelay()/60+"").replaceFirst("\\{AMOUNT}", worldBorder.getDelay()%60+"")));
} else { } else {
board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_DECREASING)); board.setLine(String.valueOf(i), line.replace("{BORDER}", BORDER_DECREASING));
} }
} else if (line.contains("{TAUNT}")) { } else if (line.contains("{TAUNT}")) {
if (!tauntEnabled) continue; if (!tauntEnabled) continue;
if (Game.taunt == null || Game.status == Status.STARTING) { if (taunt == null || status == Status.STARTING) {
board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replace("{AMOUNT}", "0"))); 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)); board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_EXPIRED));
} else if (!Game.taunt.isRunning()) { } else if (!taunt.isRunning()) {
board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() / 60 + "").replaceFirst("\\{AMOUNT}", Game.taunt.getDelay() % 60 + ""))); board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_COUNTING.replaceFirst("\\{AMOUNT}", taunt.getDelay() / 60 + "").replaceFirst("\\{AMOUNT}", taunt.getDelay() % 60 + "")));
} else { } else {
board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_ACTIVE)); board.setLine(String.valueOf(i), line.replace("{TAUNT}", TAUNT_ACTIVE));
} }
} else if (line.contains("{GLOW}")) { } else if (line.contains("{GLOW}")) {
if (!glowEnabled) return; if (!glowEnabled) return;
if (Game.glow == null || Game.status == Status.STARTING || !Game.glow.isRunning()) { if (glow == null || status == Status.STARTING || !glow.isRunning()) {
board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_INACTIVE)); board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_INACTIVE));
} else { } else {
board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_ACTIVE)); board.setLine(String.valueOf(i), line.replace("{GLOW}", GLOW_ACTIVE));
@ -293,50 +305,50 @@ public class Board {
customBoards.put(player.getUniqueId().toString(), board); customBoards.put(player.getUniqueId().toString(), board);
} }
public static void removeBoard(Player player) { public void removeBoard(Player player) {
ScoreboardManager manager = Bukkit.getScoreboardManager(); ScoreboardManager manager = Bukkit.getScoreboardManager();
assert manager != null; assert manager != null;
player.setScoreboard(manager.getMainScoreboard()); player.setScoreboard(manager.getMainScoreboard());
customBoards.remove(player.getUniqueId().toString()); customBoards.remove(player.getUniqueId().toString());
} }
public static void reloadLobbyBoards() { public void reloadLobbyBoards() {
for(Player player : playerList.values()) for(Player player : playerList.values())
createLobbyBoard(player, false); createLobbyBoard(player, false);
} }
public static void reloadGameBoards() { public void reloadGameBoards() {
for(Player player : playerList.values()) for(Player player : playerList.values())
createGameBoard(player, false); createGameBoard(player, false);
} }
public static void reloadBoardTeams() { public void reloadBoardTeams() {
for(CustomBoard board : customBoards.values()) for(CustomBoard board : customBoards.values())
board.updateTeams(); board.updateTeams();
} }
private static String getSeekerPercent() { private String getSeekerPercent() {
if (playerList.values().size() < 2) if (playerList.values().size() < 2)
return " --"; return " --";
else else
return " "+(int)(100*(1.0/playerList.size())); return " "+(int)(100*(1.0/playerList.size()));
} }
private static String getHiderPercent() { private String getHiderPercent() {
if (playerList.size() < 2) if (playerList.size() < 2)
return " --"; return " --";
else else
return " "+(int)(100-100*(1.0/playerList.size())); return " "+(int)(100-100*(1.0/playerList.size()));
} }
private static String getTeam(Player player) { private String getTeam(Player player) {
if (isHider(player)) return message("HIDER_TEAM_NAME").toString(); if (isHider(player)) return message("HIDER_TEAM_NAME").toString();
else if (isSeeker(player)) return message("SEEKER_TEAM_NAME").toString(); else if (isSeeker(player)) return message("SEEKER_TEAM_NAME").toString();
else if (isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString(); else if (isSpectator(player)) return message("SPECTATOR_TEAM_NAME").toString();
else return ChatColor.WHITE + "UNKNOWN"; else return ChatColor.WHITE + "UNKNOWN";
} }
public static void cleanup() { public void cleanup() {
playerList.clear(); playerList.clear();
Hider.clear(); Hider.clear();
Seeker.clear(); Seeker.clear();
@ -380,13 +392,13 @@ class CustomBoard {
assert hiderTeam != null; assert hiderTeam != null;
for(String entry : hiderTeam.getEntries()) for(String entry : hiderTeam.getEntries())
hiderTeam.removeEntry(entry); hiderTeam.removeEntry(entry);
for(Player player : Board.getHiders()) for(Player player : Main.getInstance().getBoard().getHiders())
hiderTeam.addEntry(player.getName()); hiderTeam.addEntry(player.getName());
Team seekerTeam = board.getTeam("Seeker"); Team seekerTeam = board.getTeam("Seeker");
assert seekerTeam != null; assert seekerTeam != null;
for(String entry : seekerTeam.getEntries()) for(String entry : seekerTeam.getEntries())
seekerTeam.removeEntry(entry); seekerTeam.removeEntry(entry);
for(Player player : Board.getSeekers()) for(Player player : Main.getInstance().getBoard().getSeekers())
seekerTeam.addEntry(player.getName()); seekerTeam.addEntry(player.getName());
if (Version.atLeast("1.9")) { if (Version.atLeast("1.9")) {
if (nametagsVisible) { if (nametagsVisible) {

View file

@ -23,24 +23,16 @@ import com.cryptomorin.xseries.messages.ActionBar;
import com.cryptomorin.xseries.messages.Titles; import com.cryptomorin.xseries.messages.Titles;
import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams; import com.google.common.io.ByteStreams;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.configuration.Items; import net.tylermurphy.hideAndSeek.game.events.Border;
import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.game.events.Glow;
import net.tylermurphy.hideAndSeek.game.events.Taunt;
import net.tylermurphy.hideAndSeek.game.listener.RespawnHandler; import net.tylermurphy.hideAndSeek.game.listener.RespawnHandler;
import net.tylermurphy.hideAndSeek.util.*; import net.tylermurphy.hideAndSeek.game.util.*;
import net.tylermurphy.hideAndSeek.world.WorldLoader; import net.tylermurphy.hideAndSeek.world.WorldLoader;
import org.bukkit.*; import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File; import java.io.File;
import java.util.*; import java.util.*;
@ -48,303 +40,239 @@ import java.util.stream.Collectors;
import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message; import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
import static net.tylermurphy.hideAndSeek.game.Game.broadcastMessage;
public class Game { public class Game {
public static Taunt taunt; private final Taunt taunt;
public static Glow glow; private final Glow glow;
public static Border worldBorder; private final Border worldBorder;
public static WorldLoader worldLoader; private final WorldLoader worldLoader;
public static int tick = 0;
public static int countdownTime = -1;
public static int gameId = 0;
public static int timeLeft = 0;
public static Status status = Status.STANDBY;
private static boolean hiderLeave = false; private final Board board;
static { private Status status;
worldLoader = new WorldLoader(spawnWorld);
private int gameTick;
private int lobbyTimer;
private int startingTimer;
private int gameTimer;
private boolean hiderLeft;
public Game(Board board){
this.taunt = new Taunt();
this.glow = new Glow();
this.worldBorder = new Border();
this.worldLoader = new WorldLoader(spawnWorld);
this.status = Status.STANDBY;
this.board = board;
this.gameTick = 0;
this.lobbyTimer = -1;
this.startingTimer = -1;
this.gameTimer = 0;
this.hiderLeft = false;
} }
public static void start() { public Status getStatus(){
Optional<Player> rand = Board.getPlayers().stream().skip(new Random().nextInt(Board.size())).findFirst(); return status;
if (!rand.isPresent()) {
Main.plugin.getLogger().warning("Failed to select random seeker.");
return;
}
String seekerName = rand.get().getName();
Player temp = Bukkit.getPlayer(seekerName);
if (temp == null) {
Main.plugin.getLogger().warning("Failed to select random seeker.");
return;
}
Player seeker = Board.getPlayer(temp.getUniqueId());
if (seeker == null) {
Main.plugin.getLogger().warning("Failed to select random seeker.");
return;
}
start(seeker);
} }
public static void start(Player seeker) { public int getTimeLeft(){
if (status == Status.STARTING || status == Status.PLAYING) return; return gameTimer;
if (mapSaveEnabled && worldLoader.getWorld() != null) { }
worldLoader.rollback();
} else if (mapSaveEnabled) { public int getLobbyTime(){
worldLoader.loadMap(); return lobbyTimer;
}
public Glow getGlow(){
return glow;
}
public Border getBorder(){
return worldBorder;
}
public Taunt getTaunt(){
return taunt;
}
public WorldLoader getWorldLoader(){
return worldLoader;
}
public void start() {
try {
Optional<Player> rand = board.getPlayers().stream().skip(new Random().nextInt(board.size())).findFirst();
String seekerName = rand.get().getName();
Player temp = Bukkit.getPlayer(seekerName);
Player seeker = board.getPlayer(temp.getUniqueId());
start(seeker);
} catch (Exception e){
Main.getInstance().getLogger().warning("Failed to select random seeker.");
} }
Board.reload(); }
for(Player temp : Board.getPlayers()) {
if (temp.getName().equals(seeker.getName())) public void start(Player seeker) {
continue; if (mapSaveEnabled) worldLoader.rollback();
Board.addHider(temp); board.reload();
} board.addSeeker(seeker);
Board.addSeeker(seeker); PlayerUtil.loadSeeker(seeker, getGameWorld());
currentWorldborderSize = worldborderSize; board.getPlayers().forEach(player -> {
for(Player player : Board.getPlayers()) { board.createGameBoard(player);
player.getInventory().clear(); if(board.isSeeker(player)) return;
player.setGameMode(GameMode.ADVENTURE); board.addHider(player);
player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ())); PlayerUtil.loadHider(player, getGameWorld());
for(PotionEffect effect : player.getActivePotionEffects()) { });
player.removePotionEffect(effect.getType()); worldBorder.resetWorldBorder(getGameWorld());
} if (gameLength > 0) gameTimer = gameLength;
}
for(Player player : Board.getSeekers()) {
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS,1000000,127,false,false));
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW,1000000,127,false,false));
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,1000000,128,false,false));
Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("SEEKER_TEAM_NAME"), ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString());
}
for(Player player : Board.getHiders()) {
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false));
Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString());
}
if (tauntEnabled)
taunt = new Taunt();
if (glowEnabled)
glow = new Glow();
worldBorder = new Border();
worldBorder.resetWorldborder(getGameWorld());
if (gameLength > 0)
timeLeft = gameLength;
for(Player player : Board.getPlayers())
Board.createGameBoard(player);
Board.reloadGameBoards();
status = Status.STARTING; status = Status.STARTING;
int temp = gameId; startingTimer = 30;
if (countdownDisplay != CountdownDisplay.TITLE) {
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30), gameId, 0);
}
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10);
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20);
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25);
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27);
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28);
sendHideCountdownMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29);
Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> {
if (temp != gameId) return;
sendHideCountdownMessage(messagePrefix + message("START"), gameId, 0);
for(Player player : Board.getPlayers()) resetPlayer(player);
status = Status.PLAYING;
}, 20 * 30);
} }
public static void stop(WinType type) { private void stop(WinType type) {
if (status == Status.STANDBY || status == Status.ENDING) return;
status = Status.ENDING; status = Status.ENDING;
for(Player player : Board.getPlayers()) { List<UUID> players = board.getPlayers().stream().map(Entity::getUniqueId).collect(Collectors.toList());
player.getInventory().clear();
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100));
if (Version.atLeast("1.9")) {
for(Player temp : Board.getPlayers()) {
Packet.setGlow(player, temp, false);
}
}
}
List<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()); 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); Main.getInstance().getDatabase().getGameData().addWins(board, 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<>(); List<UUID> winners = new ArrayList<>();
winners.add(Board.getFirstSeeker().getUniqueId()); winners.add(board.getFirstSeeker().getUniqueId());
Database.playerInfo.addWins(players, winners, Board.getHiderKills(), Board.getHiderDeaths(), Board.getSeekerKills(), Board.getSeekerDeaths(), type); Main.getInstance().getDatabase().getGameData().addWins(board, players, winners, board.getHiderKills(), board.getHiderDeaths(), board.getSeekerKills(), board.getSeekerDeaths(), type);
} }
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.plugin, Game::end, 5*20); Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), this::end, 5*20);
} }
public static void end() { public void end() {
if (status == Status.STANDBY) return; board.getPlayers().forEach(PlayerUtil::unloadPlayer);
tick = 0; worldBorder.resetWorldBorder(getGameWorld());
countdownTime = -1; board.getPlayers().forEach(player -> {
status = Status.STANDBY;
gameId++;
timeLeft = 0;
worldBorder.resetWorldborder(getGameWorld());
for(Player player : Board.getPlayers()) {
for(Player player2 : Board.getPlayers()) {
player.showPlayer(player2);
}
player.setAllowFlight(false);
player.setFlying(false);
if (Version.atLeast("1.9")) {
for(Player temp : Board.getPlayers()) {
Packet.setGlow(player, temp, false);
}
}
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100));
if (leaveOnEnd) { if (leaveOnEnd) {
Board.removeBoard(player); board.removeBoard(player);
Board.remove(player); board.remove(player);
player.getInventory().clear();
handleBungeeLeave(player); handleBungeeLeave(player);
} else { } else {
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ()));
Board.createLobbyBoard(player); board.createLobbyBoard(player);
player.setGameMode(GameMode.ADVENTURE); board.addHider(player);
Board.addHider(player); PlayerUtil.joinPlayer(player);
player.getInventory().clear();
if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.isOp()))
player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem);
if (lobbyLeaveItem != null)
player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem);
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.addPotionEffect(new PotionEffect(PotionEffectType.HEAL, 1, 100));
} }
} });
RespawnHandler.temp_loc.clear(); RespawnHandler.temp_loc.clear();
if (mapSaveEnabled) worldLoader.unloadMap(); if (mapSaveEnabled) worldLoader.unloadMap();
Board.reloadLobbyBoards(); board.reloadLobbyBoards();
status = Status.ENDED;
} }
public static void join(Player player) { public void join(Player player) {
if (Game.status == Status.STANDBY || Game.status == Status.ENDING) { if (status != Status.STARTING && status != Status.PLAYING) {
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ())); PlayerUtil.joinPlayer(player);
player.getInventory().clear(); board.addHider(player);
if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start"))) board.createLobbyBoard(player);
player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem); board.reloadLobbyBoards();
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)); else broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player));
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.setGameMode(GameMode.ADVENTURE);
Board.createLobbyBoard(player);
Board.reloadLobbyBoards();
} else { } else {
Board.addSpectator(player); PlayerUtil.loadSpectator(player, getGameWorld());
board.addSpectator(player);
board.createGameBoard(player);
player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR")); player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR"));
player.setGameMode(GameMode.ADVENTURE);
for(Player player2 : Board.getPlayers()) {
player2.hidePlayer(player);
}
Board.createGameBoard(player);
player.teleport(new Location(Bukkit.getWorld(getGameWorld()), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ()));
player.setAllowFlight(true);
player.setFlying(true);
player.setFallDistance(0.0F);
Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString());
}
player.setFoodLevel(20);
if (Version.atLeast("1.9")) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
} else {
player.setHealth(player.getMaxHealth());
} }
} }
public static void leave(Player player) { public void leave(Player player) {
player.setFlying(false); PlayerUtil.unloadPlayer(player);
player.setAllowFlight(false);
player.setFallDistance(0.0F);
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)); else 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; hiderLeft = true;
} }
Board.removeBoard(player); board.removeBoard(player);
Board.remove(player); board.remove(player);
player.getInventory().clear(); if (status == Status.STANDBY) {
if (Game.status == Status.STANDBY) { board.reloadLobbyBoards();
Board.reloadLobbyBoards();
} else { } else {
Board.reloadGameBoards(); board.reloadGameBoards();
Board.reloadBoardTeams(); board.reloadBoardTeams();
}
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
} }
handleBungeeLeave(player); handleBungeeLeave(player);
} }
private static void handleBungeeLeave(Player player) { private void handleBungeeLeave(Player player) {
if (bungeeLeave) { if (bungeeLeave) {
ByteArrayDataOutput out = ByteStreams.newDataOutput(); ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect"); out.writeUTF("Connect");
out.writeUTF(leaveServer); out.writeUTF(leaveServer);
player.sendPluginMessage(Main.plugin, "BungeeCord", out.toByteArray()); player.sendPluginMessage(Main.getInstance(), "BungeeCord", out.toByteArray());
} else { } else {
player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
} }
} }
public static void onTick() { public void onTick() {
if (isNotSetup()) return; if (isNotSetup()) return;
if (status == Status.STANDBY) whileWaiting(); if (status == Status.STANDBY) whileWaiting();
else if (status == Status.STARTING) whileStarting(); else if (status == Status.STARTING) whileStarting();
else if (status == Status.PLAYING) whilePlaying(); else if (status == Status.PLAYING) whilePlaying();
tick++; gameTick++;
} }
private static void whileWaiting() { private void whileWaiting() {
if (!lobbyCountdownEnabled) return; if (!lobbyCountdownEnabled) return;
if (lobbyMin <= Board.size()) { if (lobbyMin <= board.size()) {
if (countdownTime == -1) if (gameTimer == -1)
countdownTime = countdown; lobbyTimer = countdown;
if (Board.size() >= changeCountdown) if (board.size() >= changeCountdown)
countdownTime = Math.min(countdownTime, 10); lobbyTimer = Math.min(lobbyTimer, 10);
if (tick % 20 == 0) { if (gameTick % 20 == 0) {
countdownTime--; lobbyTimer--;
Board.reloadLobbyBoards(); board.reloadLobbyBoards();
} }
if (countdownTime == 0) { if (lobbyTimer == 0) {
start(); start();
} }
} else { } else {
countdownTime = -1; lobbyTimer = -1;
} }
} }
private static void whileStarting() { private void whileStarting() {
for(Player spectator : Board.getSpectators()) {
spectator.setFlying(spectator.getAllowFlight()); if(gameTick % 20 == 0) {
if (startingTimer % 5 == 0 || startingTimer < 4) {
String message;
if (startingTimer == 0) {
message = message("START").toString();
status = Status.PLAYING;
board.getPlayers().forEach(player -> PlayerUtil.resetPlayer(player, board));
} else {
message = message("START_COUNTDOWN").addAmount(startingTimer).toString();
}
board.getPlayers().forEach(player -> {
if (countdownDisplay == CountdownDisplay.CHAT) {
player.sendMessage(messagePrefix + message);
} else if (countdownDisplay == CountdownDisplay.ACTIONBAR) {
ActionBar.clearActionBar(player);
ActionBar.sendActionBar(player, messagePrefix + message);
} else if (countdownDisplay == CountdownDisplay.TITLE) {
Titles.clearTitle(player);
Titles.sendTitle(player, 10, 40, 10, " ", message);
}
});
}
startingTimer--;
} }
checkWinConditions(); checkWinConditions();
} }
private static void whilePlaying() { private void whilePlaying() {
for(Player hider : Board.getHiders()) { for(Player hider : board.getHiders()) {
int distance = 100, temp = 100; int distance = 100, temp = 100;
for(Player seeker : Board.getSeekers()) { for(Player seeker : board.getSeekers()) {
try { try {
temp = (int) hider.getLocation().distance(seeker.getLocation()); temp = (int) hider.getLocation().distance(seeker.getLocation());
} catch (Exception e) { } catch (Exception e) {
@ -354,7 +282,7 @@ public class Game {
distance = temp; distance = temp;
} }
} }
if (seekerPing) switch(tick%10) { if (seekerPing) switch(gameTick %10) {
case 0: case 0:
if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch); if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch);
if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch); if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch);
@ -371,13 +299,10 @@ public class Game {
break; break;
} }
} }
for(Player spectator : Board.getSpectators()) { if (gameTick %20 == 0) {
spectator.setFlying(spectator.getAllowFlight());
}
if (tick%20 == 0) {
if (gameLength > 0) { if (gameLength > 0) {
Board.reloadGameBoards(); board.reloadGameBoards();
timeLeft--; gameTimer--;
} }
if (worldborderEnabled) worldBorder.update(); if (worldborderEnabled) worldBorder.update();
if (tauntEnabled) taunt.update(); if (tauntEnabled) taunt.update();
@ -386,68 +311,31 @@ public class Game {
checkWinConditions(); checkWinConditions();
} }
public static void resetWorldBorder(String worldName) { public void broadcastMessage(String message) {
worldBorder = new Border(); for(Player player : board.getPlayers()) {
worldBorder.resetWorldborder(worldName);
}
public static void broadcastMessage(String message) {
for(Player player : Board.getPlayers()) {
player.sendMessage(message); player.sendMessage(message);
} }
} }
public static boolean isNotSetup() { public boolean isNotSetup() {
if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true; 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 (lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true;
if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true; if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true;
if (mapSaveEnabled) { if (mapSaveEnabled) {
File destination = new File(Main.root + File.separator + getGameWorld()); File destination = new File(Main.getInstance().getWorldContainer() + File.separator + getGameWorld());
if (!destination.exists()) return true; if (!destination.exists()) return true;
} }
return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0; return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0;
} }
public static String getGameWorld() { public String getGameWorld() {
if (mapSaveEnabled) return "hideandseek_"+spawnWorld; if (mapSaveEnabled) return "hideandseek_"+spawnWorld;
else return spawnWorld; else return spawnWorld;
} }
public static void resetPlayer(Player player) { private void checkWinConditions() {
player.getInventory().clear(); if (board.sizeHider() < 1) {
for (PotionEffect effect : player.getActivePotionEffects()) { if (hiderLeft) {
player.removePotionEffect(effect.getType());
}
if (Board.isSeeker(player)) {
if (pvpEnabled)
for(ItemStack item : Items.SEEKER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.SEEKER_EFFECTS)
player.addPotionEffect(effect);
} else if (Board.isHider(player)) {
if (pvpEnabled)
for(ItemStack item : Items.HIDER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.HIDER_EFFECTS)
player.addPotionEffect(effect);
if (glowEnabled) {
player.getInventory().addItem(glowPowerupItem);
}
}
}
public static void removeItems(Player player) {
for(ItemStack si : Items.SEEKER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if (si.isSimilar(i)) player.getInventory().remove(i);
for(ItemStack hi : Items.HIDER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if (hi.isSimilar(i)) player.getInventory().remove(i);
}
private static void checkWinConditions() {
if (Board.sizeHider() < 1) {
if (hiderLeave) {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT"));
else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_QUIT"));
stop(WinType.NONE); stop(WinType.NONE);
@ -456,179 +344,16 @@ public class Game {
else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND"));
stop(WinType.SEEKER_WIN); stop(WinType.SEEKER_WIN);
} }
} else if (Board.sizeSeeker() < 1) { } else if (board.sizeSeeker() < 1) {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT"));
else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT")); else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT"));
stop(WinType.NONE); stop(WinType.NONE);
} else if (timeLeft < 1) { } else if (gameTimer < 1) {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME"));
else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME")); else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME"));
stop(WinType.HIDER_WIN); stop(WinType.HIDER_WIN);
} }
hiderLeave = false; hiderLeft = false;
}
private static void sendHideCountdownMessage(String message, int gameId, int delay) {
Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> {
if (gameId == Game.gameId) {
for(Player player : Board.getPlayers()) {
if (countdownDisplay == CountdownDisplay.CHAT) {
player.sendMessage(message);
} else if (countdownDisplay == CountdownDisplay.ACTIONBAR) {
ActionBar.clearActionBar(player);
ActionBar.sendActionBar(player,message);
} else if (countdownDisplay == CountdownDisplay.TITLE) {
Titles.clearTitle(player);
Titles.sendTitle(player, 10, 40, 10, " ", message);
}
}
}
}, delay);
}
}
class Taunt {
private UUID tauntPlayer;
private int delay;
private boolean running;
public Taunt() {
this.delay = tauntDelay;
}
protected void update() {
if (delay == 0) {
if (running) launchTaunt();
else if (tauntLast || Board.sizeHider() > 1) executeTaunt();
} else {
delay--;
delay = Math.max(delay, 0);
}
}
private void executeTaunt() {
Optional<Player> rand = Board.getHiders().stream().skip(new Random().nextInt(Board.size())).findFirst();
if (!rand.isPresent()) {
Main.plugin.getLogger().warning("Failed to select random seeker.");
return;
}
Player taunted = rand.get();
taunted.sendMessage(message("TAUNTED").toString());
broadcastMessage(tauntPrefix + message("TAUNT"));
tauntPlayer = taunted.getUniqueId();
running = true;
delay = 30;
}
private void launchTaunt() {
Player taunted = Board.getPlayer(tauntPlayer);
if (taunted != null) {
if (!Board.isHider(taunted)) {
Main.plugin.getLogger().info("Taunted played died and is now seeker. Skipping taunt.");
tauntPlayer = null;
running = false;
delay = tauntDelay;
return;
}
World world = taunted.getLocation().getWorld();
if (world == null) {
Main.plugin.getLogger().severe("Game world is null while trying to launch taunt.");
tauntPlayer = null;
running = false;
delay = tauntDelay;
return;
}
Firework fw = (Firework) world.spawnEntity(taunted.getLocation(), EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
fwm.setPower(4);
fwm.addEffect(FireworkEffect.builder()
.withColor(Color.BLUE)
.withColor(Color.RED)
.withColor(Color.YELLOW)
.with(FireworkEffect.Type.STAR)
.with(FireworkEffect.Type.BALL)
.with(FireworkEffect.Type.BALL_LARGE)
.flicker(true)
.withTrail()
.build());
fw.setFireworkMeta(fwm);
broadcastMessage(tauntPrefix + message("TAUNT_ACTIVATE"));
}
tauntPlayer = null;
running = false;
delay = tauntDelay;
}
public int getDelay() {
return delay;
}
public boolean isRunning() {
return running;
}
}
class Border {
private int delay;
private boolean running;
public Border() {
delay = 60 * worldborderDelay;
}
void update() {
if (delay == 30 && !running) {
broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN"));
} else if (delay == 0) {
if (running) {
delay = 60 * worldborderDelay;
running = false;
}
else decreaceWorldborder();
}
delay--;
}
private void decreaceWorldborder() {
if (currentWorldborderSize == 100) return;
int change = worldborderChange;
if (currentWorldborderSize-worldborderChange < 100) {
change = currentWorldborderSize-100;
}
running = true;
broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change));
currentWorldborderSize -= worldborderChange;
World world = Bukkit.getWorld(Game.getGameWorld());
assert world != null;
org.bukkit.WorldBorder border = world.getWorldBorder();
border.setSize(border.getSize()-change,30);
delay = 30;
}
public void resetWorldborder(String worldName) {
World world = Bukkit.getWorld(worldName);
assert world != null;
org.bukkit.WorldBorder border = world.getWorldBorder();
if (worldborderEnabled) {
border.setSize(worldborderSize);
border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ());
currentWorldborderSize = worldborderSize;
} else {
border.setSize(30000000);
border.setCenter(0, 0);
}
}
public int getDelay() {
return delay;
}
public boolean isRunning() {
return running;
} }
} }

View file

@ -0,0 +1,71 @@
package net.tylermurphy.hideAndSeek.game.events;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.World;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Border {
private int delay;
private boolean running;
public Border() {
delay = 60 * worldborderDelay;
}
public void update() {
if (delay == 30 && !running) {
Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_WARN"));
} else if (delay == 0) {
if (running) {
delay = 60 * worldborderDelay;
running = false;
}
else decreaceWorldborder();
}
delay--;
}
private void decreaceWorldborder() {
if (currentWorldborderSize == 100) return;
int change = worldborderChange;
if (currentWorldborderSize-worldborderChange < 100) {
change = currentWorldborderSize-100;
}
running = true;
Main.getInstance().getGame().broadcastMessage(worldborderPrefix + message("WORLDBORDER_DECREASING").addAmount(change));
currentWorldborderSize -= worldborderChange;
World world = Bukkit.getWorld(Main.getInstance().getGame().getGameWorld());
assert world != null;
org.bukkit.WorldBorder border = world.getWorldBorder();
border.setSize(border.getSize()-change,30);
delay = 30;
}
public void resetWorldBorder(String worldName) {
World world = Bukkit.getWorld(worldName);
assert world != null;
org.bukkit.WorldBorder border = world.getWorldBorder();
if (worldborderEnabled) {
border.setSize(worldborderSize);
border.setCenter(worldborderPosition.getX(), worldborderPosition.getZ());
currentWorldborderSize = worldborderSize;
} else {
border.setSize(30000000);
border.setCenter(0, 0);
}
delay = 60 * worldborderDelay;
}
public int getDelay() {
return delay;
}
public boolean isRunning() {
return running;
}
}

View file

@ -1,6 +1,7 @@
package net.tylermurphy.hideAndSeek.game; package net.tylermurphy.hideAndSeek.game.events;
import net.tylermurphy.hideAndSeek.util.Packet; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Packet;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength; import static net.tylermurphy.hideAndSeek.configuration.Config.glowLength;
@ -22,12 +23,12 @@ public class Glow {
} }
private void sendPackets() { private void sendPackets() {
for (Player hider : Board.getHiders()) for (Player hider : Main.getInstance().getBoard().getHiders())
for (Player seeker : Board.getSeekers()) for (Player seeker : Main.getInstance().getBoard().getSeekers())
Packet.setGlow(hider, seeker, true); Packet.setGlow(hider, seeker, true);
} }
protected void update() { public void update() {
if (running) { if (running) {
sendPackets(); sendPackets();
glowTime--; glowTime--;
@ -40,8 +41,8 @@ public class Glow {
private void stopGlow() { private void stopGlow() {
running = false; running = false;
for (Player hider : Board.getHiders()) { for (Player hider : Main.getInstance().getBoard().getHiders()) {
for (Player seeker : Board.getSeekers()) { for (Player seeker : Main.getInstance().getBoard().getSeekers()) {
Packet.setGlow(hider, seeker, false); Packet.setGlow(hider, seeker, false);
} }
} }

View file

@ -0,0 +1,101 @@
package net.tylermurphy.hideAndSeek.game.events;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.inventory.meta.FireworkMeta;
import java.util.Optional;
import java.util.Random;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.tauntDelay;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Taunt {
private UUID tauntPlayer;
private int delay;
private boolean running;
public Taunt() {
this.delay = tauntDelay;
}
public void update() {
if (delay == 0) {
if (running) launchTaunt();
else if (tauntLast || Main.getInstance().getBoard().sizeHider() > 1) executeTaunt();
} else {
delay--;
delay = Math.max(delay, 0);
}
}
private void executeTaunt() {
Optional<Player> rand = Main.getInstance().getBoard().getHiders().stream().skip(new Random().nextInt(Main.getInstance().getBoard().size())).findFirst();
if (!rand.isPresent()) {
Main.getInstance().getLogger().warning("Failed to select random seeker.");
return;
}
Player taunted = rand.get();
taunted.sendMessage(message("TAUNTED").toString());
Main.getInstance().getGame().broadcastMessage(tauntPrefix + message("TAUNT"));
tauntPlayer = taunted.getUniqueId();
running = true;
delay = 30;
}
private void launchTaunt() {
Player taunted = Main.getInstance().getBoard().getPlayer(tauntPlayer);
if (taunted != null) {
if (!Main.getInstance().getBoard().isHider(taunted)) {
Main.getInstance().getLogger().info("Taunted played died and is now seeker. Skipping taunt.");
tauntPlayer = null;
running = false;
delay = tauntDelay;
return;
}
World world = taunted.getLocation().getWorld();
if (world == null) {
Main.getInstance().getLogger().severe("Game world is null while trying to launch taunt.");
tauntPlayer = null;
running = false;
delay = tauntDelay;
return;
}
Firework fw = (Firework) world.spawnEntity(taunted.getLocation(), EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
fwm.setPower(4);
fwm.addEffect(FireworkEffect.builder()
.withColor(Color.BLUE)
.withColor(Color.RED)
.withColor(Color.YELLOW)
.with(FireworkEffect.Type.STAR)
.with(FireworkEffect.Type.BALL)
.with(FireworkEffect.Type.BALL_LARGE)
.flicker(true)
.withTrail()
.build());
fw.setFireworkMeta(fwm);
Main.getInstance().getGame().broadcastMessage(tauntPrefix + message("TAUNT_ACTIVATE"));
}
tauntPlayer = null;
running = false;
delay = tauntDelay;
}
public int getDelay() {
return delay;
}
public boolean isRunning() {
return running;
}
}

View file

@ -1,8 +1,7 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -23,10 +22,10 @@ public class BlockedCommandHandler implements Listener {
String[] temp = array[0].split(":"); String[] temp = array[0].split(":");
for(String handle : blockedCommands) { for(String handle : blockedCommands) {
if ( if (
array[0].substring(1).equalsIgnoreCase(handle) && Board.contains(player) || array[0].substring(1).equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player) ||
temp[temp.length-1].equalsIgnoreCase(handle) && Board.contains(player) temp[temp.length-1].equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player)
) { ) {
if (Game.status == Status.STANDBY) return; if (Main.getInstance().getGame().getStatus() == Status.STANDBY) return;
player.sendMessage(errorPrefix + message("BLOCKED_COMMAND")); player.sendMessage(errorPrefix + message("BLOCKED_COMMAND"));
event.setCancelled(true); event.setCancelled(true);
break; break;

View file

@ -1,6 +1,6 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -19,9 +19,9 @@ public class ChatHandler implements Listener {
event.getPlayer().setAllowFlight(false); event.getPlayer().setAllowFlight(false);
event.getPlayer().setFlying(false); event.getPlayer().setFlying(false);
} }
if (Board.isSeeker(event.getPlayer())) { if (Main.getInstance().getBoard().isSeeker(event.getPlayer())) {
event.setCancelled(true); event.setCancelled(true);
Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage())); Main.getInstance().getBoard().getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage()));
} }
} }

View file

@ -1,13 +1,14 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import com.cryptomorin.xseries.XSound; import com.cryptomorin.xseries.XSound;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Version; import net.tylermurphy.hideAndSeek.game.util.PlayerUtil;
import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.game.util.Version;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile; import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -24,6 +25,10 @@ public class DamageHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
Board board = Main.getInstance().getBoard();
Game game = Main.getInstance().getGame();
// If you are not a player, get out of here // If you are not a player, get out of here
if (!(event.getEntity() instanceof Player)) return; if (!(event.getEntity() instanceof Player)) return;
// Define variables // Define variables
@ -44,18 +49,18 @@ public class DamageHandler implements Listener {
// Makes sure that if there was an attacking player, that the event is allowed for the game // 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 // 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); event.setCancelled(true);
return; return;
// Ignore event if neither player are in the game // 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; return;
// Ignore event if players are on the same team, or one of them is a spectator // 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); event.setCancelled(true);
return; return;
// Ignore the event if pvp is disabled, and a hider is trying to attack a seeker // 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); event.setCancelled(true);
return; return;
} }
@ -63,49 +68,52 @@ public class DamageHandler implements Listener {
} else if (!pvpEnabled && !allowNaturalCauses) { } else if (!pvpEnabled && !allowNaturalCauses) {
event.setCancelled(true); event.setCancelled(true);
return; return;
// Spectators cannot take damage }
} else if (Board.isSpectator(player)) { // Spectators cannot take damage
if (board.isSpectator(player)) {
event.setCancelled(true); 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())); 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())); player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ()));
} }
return; return;
} }
// Players cannot take damage while game is not in session
if (board.contains(player) && (game.getStatus() == Status.STANDBY || game.getStatus() == Status.STARTING)){
event.setCancelled(true);
return;
}
// Handle death event // Handle death event
event.setCancelled(true); event.setCancelled(true);
// Reset health and play death effect // 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); XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1);
} else { } else {
player.setHealth(player.getMaxHealth());
XSound.ENTITY_PLAYER_HURT.play(player, 1, 1); XSound.ENTITY_PLAYER_HURT.play(player, 1, 1);
} }
// Teleport player to seeker spawn // Teleport player to seeker spawn
player.teleport(new Location(Bukkit.getWorld(Game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ())); player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ()));
// Broadcast player death message // Broadcast player death message
if (Board.isSeeker(player)) { if (board.isSeeker(player)) {
Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString()); 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()); board.addDeath(player.getUniqueId());
} }
} else if (Board.isHider(player)) { } else if (board.isHider(player)) {
if (attacker == null) { if (attacker == null) {
Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString()); game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString());
} else { } else {
Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString()); game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString());
} }
Board.addDeath(player.getUniqueId()); board.addDeath(player.getUniqueId());
Board.addSeeker(player); board.addSeeker(player);
} }
// Add leaderboard kills if attacker // 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()); board.addKill(attacker.getUniqueId());
Game.resetPlayer(player); PlayerUtil.resetPlayer(player, board);
Board.reloadBoardTeams(); board.reloadBoardTeams();
} }
} }

View file

@ -1,9 +1,8 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import com.cryptomorin.xseries.XMaterial; import com.cryptomorin.xseries.XMaterial;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -20,40 +19,40 @@ public class InteractHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (!Board.contains(event.getPlayer())) return; if (!Main.getInstance().getBoard().contains(event.getPlayer())) return;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
ItemStack temp = event.getItem(); ItemStack temp = event.getItem();
if (temp == null) return; if (temp == null) return;
if (Game.status == Status.STANDBY) if (Main.getInstance().getGame().getStatus() == Status.STANDBY)
onPlayerInteractLobby(temp, event); onPlayerInteractLobby(temp, event);
if (Game.status == Status.PLAYING) if (Main.getInstance().getGame().getStatus() == Status.PLAYING)
onPlayerInteractGame(temp, event); 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()) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) {
event.setCancelled(true); event.setCancelled(true);
Game.leave(event.getPlayer()); Main.getInstance().getGame().leave(event.getPlayer());
} }
if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) {
event.setCancelled(true); event.setCancelled(true);
if (Game.isNotSetup()) { if (Main.getInstance().getGame().isNotSetup()) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP")); event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP"));
return; return;
} }
if (Game.status != Status.STANDBY) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS")); event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return; return;
} }
if (Board.size() < minPlayers) { if (Main.getInstance().getBoard().size() < minPlayers) {
event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers)); event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers));
return; return;
} }
Game.start(); Main.getInstance().getGame().start();
} }
} }
@ -61,8 +60,8 @@ public class InteractHandler implements Listener {
if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) { if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(glowPowerupItem.getItemMeta().getDisplayName()) && temp.getType() == glowPowerupItem.getType()) {
if (!glowEnabled) return; if (!glowEnabled) return;
Player player = event.getPlayer(); Player player = event.getPlayer();
if (Board.isHider(player)) { if (Main.getInstance().getBoard().isHider(player)) {
Game.glow.onProjectile(); Main.getInstance().getGame().getGlow().onProjectile();
player.getInventory().remove(glowPowerupItem); player.getInventory().remove(glowPowerupItem);
assert XMaterial.SNOWBALL.parseMaterial() != null; assert XMaterial.SNOWBALL.parseMaterial() != null;
player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial()); player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial());

View file

@ -1,8 +1,8 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
@ -13,6 +13,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import static net.tylermurphy.hideAndSeek.configuration.Config.*; import static net.tylermurphy.hideAndSeek.configuration.Config.*;
@ -22,20 +23,20 @@ public class JoinLeaveHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
Board.remove(event.getPlayer()); Main.getInstance().getBoard().remove(event.getPlayer());
Game.removeItems(event.getPlayer()); removeItems(event.getPlayer());
if (Game.isNotSetup()) return; if (Main.getInstance().getGame().isNotSetup()) return;
if (autoJoin) { if (autoJoin) {
Game.join(event.getPlayer()); Main.getInstance().getGame().join(event.getPlayer());
} else if (teleportToExit) { } else if (teleportToExit) {
if (event.getPlayer().getWorld().getName().equals(Game.getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) { if (event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld()) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) {
event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
event.getPlayer().setGameMode(GameMode.ADVENTURE); event.getPlayer().setGameMode(GameMode.ADVENTURE);
} }
} else { } else {
if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) { if (mapSaveEnabled && event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) {
if (Game.status != Status.STANDBY && Game.status != Status.ENDING) { if (Main.getInstance().getGame().getStatus() != Status.STANDBY && Main.getInstance().getGame().getStatus() != Status.ENDING) {
Game.join(event.getPlayer()); Main.getInstance().getGame().join(event.getPlayer());
} else { } else {
event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())); event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
event.getPlayer().setGameMode(GameMode.ADVENTURE); event.getPlayer().setGameMode(GameMode.ADVENTURE);
@ -55,16 +56,25 @@ public class JoinLeaveHandler implements Listener {
} }
private void handleLeave(Player player) { private void handleLeave(Player player) {
Board.remove(player); Main.getInstance().getBoard().remove(player);
if (Game.status == Status.STANDBY) { if (Main.getInstance().getGame().getStatus() == Status.STANDBY) {
Board.reloadLobbyBoards(); Main.getInstance().getBoard().reloadLobbyBoards();
} else { } else {
Board.reloadGameBoards(); Main.getInstance().getBoard().reloadGameBoards();
} }
for(PotionEffect effect : player.getActivePotionEffects()) { for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType()); player.removePotionEffect(effect.getType());
} }
Game.removeItems(player); removeItems(player);
}
private void removeItems(Player player) {
for(ItemStack si : Items.SEEKER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if (si.isSimilar(i)) player.getInventory().remove(i);
for(ItemStack hi : Items.HIDER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if (hi.isSimilar(i)) player.getInventory().remove(i);
} }
} }

View file

@ -1,7 +1,6 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
@ -14,11 +13,11 @@ public class MovementHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onMove(PlayerMoveEvent event) { public void onMove(PlayerMoveEvent event) {
if (!Board.contains(event.getPlayer())) return; if (!Main.getInstance().getBoard().contains(event.getPlayer())) return;
if (!event.getPlayer().getWorld().getName().equals(Game.getGameWorld())) return; if (!event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return;
if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return; if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return;
if (event.getTo() == null || event.getTo().getWorld() == null) return; if (event.getTo() == null || event.getTo().getWorld() == null) return;
if (!event.getTo().getWorld().getName().equals(Game.getGameWorld())) return; if (!event.getTo().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return;
if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) { if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) {
event.setCancelled(true); event.setCancelled(true);
} }

View file

@ -1,8 +1,8 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.game.Board; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Game; import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status; import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -17,7 +17,7 @@ public class PlayerHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) { public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) { if (event.getEntity() instanceof Player) {
if (!Board.contains((Player) event.getEntity())) return; if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return;
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -26,7 +26,7 @@ public class PlayerHandler implements Listener {
public void onPlayerRegainHealth(EntityRegainHealthEvent event) { public void onPlayerRegainHealth(EntityRegainHealthEvent event) {
if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) { if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) {
if (event.getEntity() instanceof Player) { if (event.getEntity() instanceof Player) {
if (!Board.contains((Player) event.getEntity())) return; if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return;
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -36,7 +36,7 @@ public class PlayerHandler implements Listener {
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player) { if (event.getWhoClicked() instanceof Player) {
Player player = (Player) event.getWhoClicked(); Player player = (Player) event.getWhoClicked();
if (Board.contains(player) && Game.status == Status.STANDBY) { if (Main.getInstance().getBoard().contains(player) && Main.getInstance().getGame().getStatus() == Status.STANDBY) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -44,7 +44,7 @@ public class PlayerHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onItemDrop(PlayerDropItemEvent event) { public void onItemDrop(PlayerDropItemEvent event) {
if (Board.contains(event.getPlayer())) { if (Main.getInstance().getBoard().contains(event.getPlayer())) {
event.setCancelled(true); event.setCancelled(true);
} }
} }

View file

@ -1,7 +1,6 @@
package net.tylermurphy.hideAndSeek.game.listener; package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.Main; import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.Board;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -21,17 +20,17 @@ public class RespawnHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent event) { public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity(); Player player = event.getEntity();
if (!Board.contains(player)) return; if (!Main.getInstance().getBoard().contains(player)) return;
event.setKeepInventory(true); event.setKeepInventory(true);
event.setDeathMessage(""); event.setDeathMessage("");
temp_loc.put(player.getUniqueId(), player.getLocation()); temp_loc.put(player.getUniqueId(), player.getLocation());
Main.plugin.getLogger().severe("Player " + player.getName() + " died when not supposed to. Attempting to roll back death."); Main.getInstance().getLogger().severe("Player " + player.getName() + " died when not supposed to. Attempting to roll back death.");
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event) { public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (!Board.contains(player)) return; if (!Main.getInstance().getBoard().contains(player)) return;
if (temp_loc.containsKey(player.getUniqueId())) { if (temp_loc.containsKey(player.getUniqueId())) {
player.teleport(temp_loc.get(player.getUniqueId())); player.teleport(temp_loc.get(player.getUniqueId()));
temp_loc.remove(player.getUniqueId()); temp_loc.remove(player.getUniqueId());

View file

@ -17,7 +17,7 @@
* *
*/ */
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.game.util;
public enum CountdownDisplay { public enum CountdownDisplay {
CHAT, CHAT,

View file

@ -17,7 +17,7 @@
* *
*/ */
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.game.util;
import com.comphenix.protocol.PacketType; import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolLibrary;

View file

@ -0,0 +1,120 @@
package net.tylermurphy.hideAndSeek.game.util;
import com.cryptomorin.xseries.messages.Titles;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.game.Board;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.lobbyPosition;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class PlayerUtil {
public static void loadHider(Player player, String gameWorld){
player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ()));
loadPlayer(player);
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false));
Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("HIDER_TEAM_NAME"), ChatColor.WHITE + message("HIDERS_SUBTITLE").toString());
}
public static void loadSeeker(Player player, String gameWorld){
player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ()));
loadPlayer(player);
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS,1000000,127,false,false));
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW,1000000,127,false,false));
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,1000000,128,false,false));
Titles.sendTitle(player, 10, 70, 20, ChatColor.WHITE + "" + message("SEEKER_TEAM_NAME"), ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString());
}
public static void loadSpectator(Player player, String gameWorld){
player.teleport(new Location(Bukkit.getWorld(gameWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ()));
loadPlayer(player);
player.setAllowFlight(true);
player.setFlying(true);
player.setFallDistance(0.0F);
Main.getInstance().getBoard().getPlayers().forEach(otherPlayer -> {
otherPlayer.hidePlayer(player);
});
Titles.sendTitle(player, 10, 70, 20, ChatColor.GRAY + "" + ChatColor.BOLD + "SPECTATING", ChatColor.WHITE + message("SPECTATOR_SUBTITLE").toString());
}
public static void resetPlayer(Player player, Board board){
loadPlayer(player);
if (board.isSeeker(player)) {
if (pvpEnabled)
for(ItemStack item : Items.SEEKER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.SEEKER_EFFECTS)
player.addPotionEffect(effect);
} else if (board.isHider(player)) {
if (pvpEnabled)
for(ItemStack item : Items.HIDER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.HIDER_EFFECTS)
player.addPotionEffect(effect);
if (glowEnabled) {
player.getInventory().addItem(glowPowerupItem);
}
}
}
public static void unloadPlayer(Player player){
player.setGameMode(GameMode.ADVENTURE);
player.getInventory().clear();
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
if (Version.atLeast("1.9")) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
for(Player temp : Main.getInstance().getBoard().getPlayers()) {
Packet.setGlow(player, temp, false);
}
} else {
player.setHealth(player.getMaxHealth());
}
Main.getInstance().getBoard().getPlayers().forEach(temp -> {
player.showPlayer(temp);
temp.showPlayer(player);
});
player.setAllowFlight(false);
player.setFlying(false);
player.setFallDistance(0.0F);
}
public static void joinPlayer(Player player){
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ()));
loadPlayer(player);
if (lobbyStartItem != null && (!lobbyItemStartAdmin || player.hasPermission("hideandseek.start")))
player.getInventory().setItem(lobbyItemStartPosition, lobbyStartItem);
if (lobbyLeaveItem != null)
player.getInventory().setItem(lobbyItemLeavePosition, lobbyLeaveItem);
}
private static void loadPlayer(Player player){
player.setGameMode(GameMode.ADVENTURE);
player.getInventory().clear();
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.setFoodLevel(20);
if (Version.atLeast("1.9")) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
} else {
player.setHealth(player.getMaxHealth());
}
}
}

View file

@ -17,10 +17,10 @@
* *
*/ */
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.game.util;
public enum Status { public enum Status {
STANDBY, STARTING, PLAYING, ENDING STANDBY, STARTING, PLAYING, ENDING, ENDED
} }

View file

@ -1,4 +1,4 @@
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.game.util;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;

View file

@ -17,7 +17,7 @@
* *
*/ */
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.game.util;
public enum WinType { public enum WinType {

View file

@ -17,9 +17,12 @@
* *
*/ */
package net.tylermurphy.hideAndSeek.game; package net.tylermurphy.hideAndSeek.util;
import net.tylermurphy.hideAndSeek.command.*; import net.tylermurphy.hideAndSeek.command.*;
import net.tylermurphy.hideAndSeek.command.location.SetExitLocation;
import net.tylermurphy.hideAndSeek.command.location.SetLobbyLocation;
import net.tylermurphy.hideAndSeek.command.location.SetSpawnLocation;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;

View file

@ -1,6 +1,7 @@
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.util;
import me.clip.placeholderapi.expansion.PlaceholderExpansion; import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.database.Database; import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.database.PlayerInfo; import net.tylermurphy.hideAndSeek.database.PlayerInfo;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -35,42 +36,43 @@ public class PAPIExpansion extends PlaceholderExpansion {
@Override @Override
public String onRequest(OfflinePlayer player, @NotNull String params) { public String onRequest(OfflinePlayer player, @NotNull String params) {
Database database = Main.getInstance().getDatabase();
String[] args = params.split("_"); String[] args = params.split("_");
if (args.length < 1) return null; if (args.length < 1) return null;
if (args[0].equals("stats") && args.length == 2) { if (args[0].equals("stats") && args.length == 2) {
PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); PlayerInfo info = database.getGameData().getInfo(player.getUniqueId());
return getValue(info, args[1]); 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; UUID uuid;
try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; }
PlayerInfo info = Database.playerInfo.getInfo(uuid); PlayerInfo info = database.getGameData().getInfo(uuid);
return getValue(info, args[1]); 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; int place;
try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; } try { place = Integer.parseInt(args[2]); } catch (NumberFormatException e) { return placeholderError; }
if (place < 1) { return placeholderError; } if (place < 1) { return placeholderError; }
if (getRanking(args[1]) == null) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; }
PlayerInfo info = Database.playerInfo.getInfoRanking(getRanking(args[1]), place); PlayerInfo info = database.getGameData().getInfoRanking(getRanking(args[1]), place);
if (info == null) return placeholderNoData; if (info == null) return placeholderNoData;
if (args[0].equals("rank-score")) { if (args[0].equals("rank-score")) {
return getValue(info, args[1]); return getValue(info, args[1]);
} else { } else {
return UUIDFetcher.getPlayer(info.uuid).getName(); return Main.getInstance().getServer().getOfflinePlayer(info.uuid).getName();
} }
} else if (args[0].equals("rank-place") && args.length == 2) { } else if (args[0].equals("rank-place") && args.length == 2) {
if (getRanking(args[1]) == null) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; }
PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); PlayerInfo info = database.getGameData().getInfo(player.getUniqueId());
if (getValue(info, args[1]).equals("0")) { return "-"; } if (getValue(info, args[1]).equals("0")) { return "-"; }
Integer count = Database.playerInfo.getRanking(getRanking(args[1]), player.getUniqueId()); Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId());
if (count == null) { return placeholderNoData; } if (count == null) { return placeholderNoData; }
return count.toString(); 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; UUID uuid;
try { uuid = UUIDFetcher.getUUID(args[2]); } catch (Exception e) { return placeholderError; } try { uuid = Main.getInstance().getServer().getOfflinePlayer(args[2]).getUniqueId(); } catch (Exception e) { return placeholderError; }
if (getRanking(args[1]) == null) { return placeholderError; } if (getRanking(args[1]) == null) { return placeholderError; }
PlayerInfo info = Database.playerInfo.getInfo(player.getUniqueId()); PlayerInfo info = database.getGameData().getInfo(player.getUniqueId());
if (getValue(info, args[1]).equals("0")) { return "-"; } if (getValue(info, args[1]).equals("0")) { return "-"; }
Integer count = Database.playerInfo.getRanking(getRanking(args[1]), uuid); Integer count = database.getGameData().getRanking(getRanking(args[1]), uuid);
if (count == null) { return placeholderNoData; } if (count == null) { return placeholderNoData; }
return count.toString(); return count.toString();
} }

View file

@ -19,7 +19,6 @@
package net.tylermurphy.hideAndSeek.util; package net.tylermurphy.hideAndSeek.util;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.ArrayList; import java.util.ArrayList;

View file

@ -1,119 +0,0 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.util;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public final class UUIDFetcher {
private static final Map<String,UUID> CACHE = new HashMap<>();
private static final Map<UUID,OfflinePlayer> PLAYER_CACHE = new HashMap<>();
private static final String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/";
private static int cacheTask;
public static void init() {
cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, () -> {
CACHE.clear();
PLAYER_CACHE.clear();
}, 600 * 20, 600 * 20);
}
public static void cleanup() {
Main.plugin.getServer().getScheduler().cancelTask(cacheTask);
}
public static UUID getUUID(String playername) {
if (CACHE.containsKey(playername)) return CACHE.get(playername);
String output = callURL(UUID_URL + playername);
StringBuilder result = new StringBuilder();
readData(output, result);
String u = result.toString();
StringBuilder uuid = new StringBuilder();
for (int i = 0; i <= 31; i++) {
uuid.append(u.charAt(i));
if (i == 7 || i == 11 || i == 15 || i == 19) {
uuid.append('-');
}
}
CACHE.put(playername, UUID.fromString(uuid.toString()));
return UUID.fromString(uuid.toString());
}
public static OfflinePlayer getPlayer(UUID uuid) {
if (PLAYER_CACHE.containsKey(uuid)) return PLAYER_CACHE.get(uuid);
OfflinePlayer temp = Bukkit.getOfflinePlayer(uuid);
PLAYER_CACHE.put(uuid, temp);
return temp;
}
private static void readData(String toRead, StringBuilder result) {
for (int i = toRead.length() - 3; i >= 0; i--) {
if (toRead.charAt(i) != '"') {
result.insert(0, toRead.charAt(i));
} else {
break;
}
}
}
private static String callURL(String urlStr) {
StringBuilder sb = new StringBuilder();
URLConnection urlConn;
InputStreamReader in;
try {
URL url = new URL(urlStr);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}

View file

@ -32,14 +32,19 @@ import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class WorldLoader { public class WorldLoader {
final String mapName; private String mapName;
final String saveName; private String saveName;
public WorldLoader(String mapName) { public WorldLoader(String mapName) {
this.mapName = mapName; this.mapName = mapName;
this.saveName = "hideandseek_"+ mapName; this.saveName = "hideandseek_"+ mapName;
} }
public void setNewMap(String mapName){
this.mapName = mapName;
this.saveName = "hideandseek_"+ mapName;
}
public World getWorld() { public World getWorld() {
return Bukkit.getServer().getWorld(saveName); return Bukkit.getServer().getWorld(saveName);
} }
@ -47,13 +52,13 @@ public class WorldLoader {
public void unloadMap() { public void unloadMap() {
World world = Bukkit.getServer().getWorld(saveName); World world = Bukkit.getServer().getWorld(saveName);
if (world == null) { if (world == null) {
Main.plugin.getLogger().warning(saveName + " already unloaded."); Main.getInstance().getLogger().warning(saveName + " already unloaded.");
return; return;
} }
if (Bukkit.getServer().unloadWorld(world, false)) { if (Bukkit.getServer().unloadWorld(world, false)) {
Main.plugin.getLogger().info("Successfully unloaded " + saveName); Main.getInstance().getLogger().info("Successfully unloaded " + saveName);
}else{ }else{
Main.plugin.getLogger().severe("COULD NOT UNLOAD " + saveName); Main.getInstance().getLogger().severe("COULD NOT UNLOAD " + saveName);
} }
} }
@ -61,7 +66,7 @@ public class WorldLoader {
Bukkit.getServer().createWorld(new WorldCreator(saveName).generator(new VoidGenerator())); Bukkit.getServer().createWorld(new WorldCreator(saveName).generator(new VoidGenerator()));
World world = Bukkit.getServer().getWorld(saveName); World world = Bukkit.getServer().getWorld(saveName);
if (world == null) { if (world == null) {
Main.plugin.getLogger().severe("COULD NOT LOAD " + saveName); Main.getInstance().getLogger().severe("COULD NOT LOAD " + saveName);
return; return;
} }
world.setAutoSave(false); world.setAutoSave(false);
@ -73,11 +78,11 @@ public class WorldLoader {
} }
public String save() { public String save() {
File current = new File(Main.root+File.separator+ mapName); File current = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName);
if (current.exists()) { if (current.exists()) {
try { try {
File destenation = new File(Main.root+File.separator+ saveName); File destenation = new File(Main.getInstance().getWorldContainer()+File.separator+ saveName);
File temp_destenation = new File(Main.root+File.separator+"temp_"+ saveName); File temp_destenation = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName);
copyFileFolder("region",true); copyFileFolder("region",true);
copyFileFolder("entities",true); copyFileFolder("entities",true);
copyFileFolder("datapacks",false); copyFileFolder("datapacks",false);
@ -104,22 +109,18 @@ public class WorldLoader {
} }
private void copyFileFolder(String name, Boolean isMca) throws IOException { private void copyFileFolder(String name, Boolean isMca) throws IOException {
File region = new File(Main.root+File.separator+ mapName +File.separator+name); File region = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName +File.separator+name);
File temp = new File(Main.root+File.separator+"temp_"+ saveName +File.separator+name); File temp = new File(Main.getInstance().getWorldContainer()+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.exists())
if (!temp.mkdirs()) if (!temp.mkdirs())
throw new IOException("Couldn't create region directory!"); throw new IOException("Couldn't create region directory!");
String[] files = region.list(); String[] files = region.list();
if (files == null) { if (files == null) {
Main.plugin.getLogger().severe("Region directory is null or cannot be accessed"); Main.getInstance().getLogger().severe("Region directory is null or cannot be accessed");
return; return;
} }
for (String file : files) { for (String file : files) {
System.out.println("Testing file "+ file);
if (isMca) { if (isMca) {
int minX = (int)Math.floor(saveMinX / 512.0); int minX = (int)Math.floor(saveMinX / 512.0);
int minZ = (int)Math.floor(saveMinZ / 512.0); int minZ = (int)Math.floor(saveMinZ / 512.0);
@ -128,7 +129,7 @@ public class WorldLoader {
String[] parts = file.split("\\."); String[] parts = file.split("\\.");
if (parts.length > 1) { if (parts.length > 1) {
Main.plugin.getLogger().info(file); Main.getInstance().getLogger().info(file);
if ( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ ) if ( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ )
continue; continue;
} }