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.database.Database;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.CommandHandler;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.game.listener.*;
import net.tylermurphy.hideAndSeek.util.PAPIExpansion;
import net.tylermurphy.hideAndSeek.util.TabCompleter;
import net.tylermurphy.hideAndSeek.util.UUIDFetcher;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@ -42,14 +42,15 @@ import java.util.List;
public class Main extends JavaPlugin implements Listener {
public static Main plugin;
public static File root, data;
private int onTickTask;
private static Main instance;
private Database database;
private Board board;
private Game game;
public void onEnable() {
plugin = this;
root = this.getServer().getWorldContainer();
data = this.getDataFolder();
instance = this;
this.registerListeners();
@ -58,30 +59,29 @@ public class Main extends JavaPlugin implements Listener {
Items.loadItems();
CommandHandler.registerCommands();
Board.reload();
Database.init();
UUIDFetcher.init();
onTickTask = Bukkit.getServer().getScheduler().runTaskTimer(this, () -> {
try{
Game.onTick();
} catch (Exception e) {
e.printStackTrace();
}
},0,1).getTaskId();
board = new Board();
database = new Database();
game = new Game(board);
getServer().getScheduler().runTaskTimer(this, this::onTick,0,1).getTaskId();
Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PAPIExpansion().register();
}
}
public void onDisable() {
Main.plugin.getServer().getScheduler().cancelTask(onTickTask);
Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this);
UUIDFetcher.cleanup();
Board.cleanup();
board.cleanup();
}
private void onTick() {
if(game.getStatus() == Status.ENDED) game = new Game(board);
game.onTick();
}
private void registerListeners() {
@ -103,4 +103,24 @@ public class Main extends JavaPlugin implements Listener {
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;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import net.tylermurphy.hideAndSeek.util.CommandHandler;
import org.bukkit.command.CommandSender;
public class Help implements ICommand {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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 static net.tylermurphy.hideAndSeek.configuration.Config.glowLength;
@ -22,12 +23,12 @@ public class Glow {
}
private void sendPackets() {
for (Player hider : Board.getHiders())
for (Player seeker : Board.getSeekers())
for (Player hider : Main.getInstance().getBoard().getHiders())
for (Player seeker : Main.getInstance().getBoard().getSeekers())
Packet.setGlow(hider, seeker, true);
}
protected void update() {
public void update() {
if (running) {
sendPackets();
glowTime--;
@ -40,8 +41,8 @@ public class Glow {
private void stopGlow() {
running = false;
for (Player hider : Board.getHiders()) {
for (Player seeker : Board.getSeekers()) {
for (Player hider : Main.getInstance().getBoard().getHiders()) {
for (Player seeker : Main.getInstance().getBoard().getSeekers()) {
Packet.setGlow(hider, seeker, false);
}
}

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -17,7 +17,7 @@
*
*/
package net.tylermurphy.hideAndSeek.util;
package net.tylermurphy.hideAndSeek.game.util;
public enum CountdownDisplay {
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.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 {
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;

View file

@ -17,7 +17,7 @@
*
*/
package net.tylermurphy.hideAndSeek.util;
package net.tylermurphy.hideAndSeek.game.util;
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.location.SetExitLocation;
import net.tylermurphy.hideAndSeek.command.location.SetLobbyLocation;
import net.tylermurphy.hideAndSeek.command.location.SetSpawnLocation;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

View file

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

View file

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