Merge pull request #68 from tylermurphy534/1.5.0

1.5.0
This commit is contained in:
Tyler Murphy 2022-06-01 20:03:01 -04:00 committed by GitHub
commit c506030cba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
73 changed files with 3667 additions and 2132 deletions

View file

@ -30,7 +30,7 @@ jobs:
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: Upload artificats
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: artifacts-beta

View file

@ -1,13 +1,14 @@
## Contributing Guidelines
- Do not send any pull requests to the master branch
- Any pull requests sent to master will be closed
- Send pull requets to the current beta branch (usually named as an unreleased version)
- Please tell us why you think this change is nessessary
- We dont want to spend lots of time browsing through your code changes
- Send pull requests to the current beta branch (usually named as an unreleased version)
- Please tell us why you think this change is necessary
- We don't want to spend lots of time browsing through your code changes
- Describe your changes
- Do not repoen a pull request if we closed it for not being a nessary feature
- Do not reopen a pull request if we closed it for not being a necessary feature
- Do not change credits in any of the files
- If making a new language file, follow the local naming convencion
- localization-[LANGUAGE](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes#)_[TERROTORY](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).yml. You can find the 2 letter codes in the links.
- If making a new language file, follow the local naming convention
- localization-[LANGUAGE](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes#)_[TERRITORY](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).yml. You can find the 2-letter codes in the links.
- Common sense, please...
- File subject to change in the future

41
pom.xml
View file

@ -1,7 +1,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>net.tylermurphy</groupId>
<artifactId>HideAndSeek</artifactId>
<version>1.4.2</version>
<artifactId>KenshinsHideAndSeek</artifactId>
<version>1.5.0</version>
<name>Hide and Seek Plugin</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -30,19 +30,22 @@
</relocation>
</relocations>
<artifactSet>
<excludes>
<exclude>org.spigotmc:spigot-api</exclude>
<exclude>com.comphenix.protocol:ProtocolLib</exclude>
<exclude>org.jetbrains:annotations</exclude>
<exclude>net.bytebuddy:byte-buddy</exclude>
</excludes>
<includes>
<include>com.github.cryptomorin:XSeries</include>
<include>org.xerial:sqlite-jdbc</include>
<include>org.mariadb.jdbc:mariadb-java-client</include>
<include>com.zaxxer:HikariCP</include>
</includes>
</artifactSet>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.MF</exclude>
<exclude>META-INF</exclude>
<exclude>META-INF/*.MD</exclude>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
<exclude>sqlite-jdbc.properties</exclude>
</excludes>
</filter>
@ -74,6 +77,10 @@
<id>dmulloy2-repo</id>
<url>https://repo.dmulloy2.net/repository/public/</url>
</repository>
<repository>
<id>placeholderapi</id>
<url>https://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>
<dependencies>
<dependency>
@ -103,5 +110,21 @@
<artifactId>XSeries</artifactId>
<version>8.7.1</version>
</dependency>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.11.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
</project>

View file

@ -19,68 +19,125 @@
package net.tylermurphy.hideAndSeek;
import java.io.File;
import java.util.List;
import net.tylermurphy.hideAndSeek.configuration.Config;
import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.configuration.Localization;
import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.util.UUIDFetcher;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.PlayerLoader;
import net.tylermurphy.hideAndSeek.game.util.Status;
import net.tylermurphy.hideAndSeek.util.CommandHandler;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.game.listener.*;
import net.tylermurphy.hideAndSeek.util.PAPIExpansion;
import net.tylermurphy.hideAndSeek.util.TabCompleter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.bukkit.scheduler.BukkitTask;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import net.tylermurphy.hideAndSeek.game.EventListener;
import net.tylermurphy.hideAndSeek.util.TabCompleter;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.configuration.Config;
import net.tylermurphy.hideAndSeek.configuration.Localization;
import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.game.Board;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition;
import static net.tylermurphy.hideAndSeek.configuration.Config.exitWorld;
public class Main extends JavaPlugin implements Listener {
public static Main plugin;
public static File root, data;
private int onTickTask;
private static Main instance;
private static int version;
public void onEnable() {
plugin = this;
root = this.getServer().getWorldContainer();
data = this.getDataFolder();
getServer().getPluginManager().registerEvents(new EventListener(), this);
private final Database database;
private final Board board;
private Game game;
public Main() {
super();
onConstructed();
board = new Board();
database = new Database();
}
protected Main(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
onConstructed();
board = new Board();
database = new Database();
}
private void onConstructed(){
instance = this;
Matcher matcher = Pattern.compile("MC: \\d\\.(\\d+)").matcher(Bukkit.getVersion());
if (matcher.find()) {
version = Integer.parseInt(matcher.group(1));
} else {
throw new IllegalArgumentException("Failed to parse server version from: " + Bukkit.getVersion());
}
Config.loadConfig();
Localization.loadLocalization();
Items.loadItems();
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();
public void onEnable() {
this.registerListeners();
CommandHandler.registerCommands();
game = new Game(board);
getServer().getScheduler().runTaskTimer(this, this::onTick,0,1).getTaskId();
Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new PAPIExpansion().register();
}
}
public void onDisable() {
Main.plugin.getServer().getScheduler().cancelTask(onTickTask);
version = 0;
board.getPlayers().forEach(player -> {
board.removeBoard(player);
PlayerLoader.unloadPlayer(player);
player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
});
Bukkit.getServer().getMessenger().unregisterOutgoingPluginChannel(this);
UUIDFetcher.cleanup();
Board.cleanup();
board.cleanup();
}
private void onTick() {
if(game.getStatus() == Status.ENDED) game = new Game(board);
game.onTick();
}
private void registerListeners() {
getServer().getPluginManager().registerEvents(new BlockedCommandHandler(), this);
getServer().getPluginManager().registerEvents(new ChatHandler(), this);
getServer().getPluginManager().registerEvents(new DamageHandler(), this);
getServer().getPluginManager().registerEvents(new InteractHandler(), this);
getServer().getPluginManager().registerEvents(new InventoryHandler(), this);
getServer().getPluginManager().registerEvents(new JoinLeaveHandler(), this);
getServer().getPluginManager().registerEvents(new MovementHandler(), this);
getServer().getPluginManager().registerEvents(new PlayerHandler(), this);
getServer().getPluginManager().registerEvents(new RespawnHandler(), this);
}
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
@ -91,4 +148,28 @@ 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;
}
public boolean supports(int v){
return version >= v;
}
}

View file

@ -20,13 +20,13 @@
package net.tylermurphy.hideAndSeek.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class About implements ICommand {
public void execute(CommandSender sender, String[] args) {
public void execute(Player sender, String[] args) {
sender.sendMessage(
String.format("%s%sHide and Seek %s(%s1.4.2%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) +
String.format("%s%sHide and Seek %s(%s1.5.0%s)\n", ChatColor.AQUA, ChatColor.BOLD, ChatColor.GRAY,ChatColor.WHITE,ChatColor.GRAY) +
String.format("%sAuthor: %s[KenshinEto]\n", ChatColor.GRAY, ChatColor.WHITE) +
String.format("%sHelp Command: %s/hs %shelp", ChatColor.GRAY, ChatColor.AQUA, ChatColor.WHITE)
);

View file

@ -0,0 +1,112 @@
package net.tylermurphy.hideAndSeek.command;
import com.cryptomorin.xseries.XMaterial;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.PlayerLoader;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition;
public class Debug implements ICommand {
private static final Map<Integer, Consumer<Player>> debugMenuFunctions = new HashMap<>();
private Inventory debugMenu;
public void execute(Player sender, String[] args) {
if(debugMenu == null) createMenu();
sender.openInventory(debugMenu);
}
private void createMenu(){
debugMenu = Main.getInstance().getServer().createInventory(null, 9, "Debug Menu");
debugMenu.setItem(0, createOption(0, XMaterial.LEATHER_CHESTPLATE.parseMaterial(), "&6Become a &lHider", 1, player -> {
if(mapSaveEnabled) {
if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap();
}
Main.getInstance().getBoard().addHider(player);
PlayerLoader.loadHider(player, Main.getInstance().getGame().getGameWorld());
if(Main.getInstance().getGame().getStatus() != Status.STARTING)
PlayerLoader.resetPlayer(player, Main.getInstance().getBoard());
}));
debugMenu.setItem(1, createOption(1, XMaterial.GOLDEN_CHESTPLATE.parseMaterial(), "&cBecome a &lSeeker", 1, player -> {
if(mapSaveEnabled) {
if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap();
}
Main.getInstance().getBoard().addSeeker(player);
PlayerLoader.loadSeeker(player, Main.getInstance().getGame().getGameWorld());
if(Main.getInstance().getGame().getStatus() != Status.STARTING)
PlayerLoader.resetPlayer(player, Main.getInstance().getBoard());
}));
debugMenu.setItem(2, createOption(2, XMaterial.IRON_CHESTPLATE.parseMaterial(), "&8Become a &lSpectator", 1, player -> {
if(mapSaveEnabled) {
if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap();
}
Main.getInstance().getBoard().addSpectator(player);
PlayerLoader.loadSpectator(player, Main.getInstance().getGame().getGameWorld());
}));
debugMenu.setItem(3, createOption(3, XMaterial.BARRIER.parseMaterial(), "&cUnload from Game", 1, player -> {
Main.getInstance().getBoard().remove(player);
PlayerLoader.unloadPlayer(player);
player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
}));
debugMenu.setItem(4, createOption(4, XMaterial.BARRIER.parseMaterial(), "&cDie In Game", 2, player -> {
if((Main.getInstance().getBoard().isSeeker(player) || Main.getInstance().getBoard().isHider(player)) && Main.getInstance().getGame().getStatus() == Status.PLAYING){
player.setHealth(0.1);
}
}));
debugMenu.setItem(6, createOption(6, Material.ENDER_PEARL, "&d&lTeleport: &fGame spawn", 1, player -> {
if(mapSaveEnabled) {
if(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()) == null) Main.getInstance().getGame().getWorldLoader().loadMap();
}
player.teleport(new Location(Bukkit.getWorld(Main.getInstance().getGame().getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ()));
}));
debugMenu.setItem(7, createOption(7, Material.ENDER_PEARL, "&d&lTeleport: &fLobby", 2, player -> {
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(), lobbyPosition.getY(), lobbyPosition.getZ()));
}));
debugMenu.setItem(8, createOption(8, Material.ENDER_PEARL, "&d&lTeleport: &fExit", 3, player -> {
player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
}));
}
private ItemStack createOption(int slow, Material material, String name, int amount, Consumer<Player> callback){
ItemStack temp = new ItemStack(material, amount);
ItemMeta meta = temp.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
temp.setItemMeta(meta);
debugMenuFunctions.put(slow, callback);
return temp;
}
public static void handleOption(Player player, int slotId){
Main.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> {
Consumer<Player> callback = debugMenuFunctions.get(slotId);
if(callback != null) callback.accept(player);
}, 0);
}
public String getLabel() {
return "debug";
}
public String getUsage() {
return "";
}
public String getDescription() {
return "Run debug commands";
}
}

View file

@ -19,14 +19,13 @@
package net.tylermurphy.hideAndSeek.command;
import org.bukkit.command.CommandSender;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import net.tylermurphy.hideAndSeek.util.CommandHandler;
import org.bukkit.entity.Player;
public class Help implements ICommand {
public void execute(CommandSender sender, String[] args) {
public void execute(Player sender, String[] args) {
StringBuilder message = new StringBuilder();
for(ICommand command : CommandHandler.COMMAND_REGISTER.values()) {
message.append(String.format("%s/hs %s%s %s%s\n %s%s%s", ChatColor.AQUA, ChatColor.WHITE, command.getLabel().toLowerCase(), ChatColor.BLUE, command.getUsage(), ChatColor.GRAY, ChatColor.ITALIC, command.getDescription() + "\n"));

View file

@ -19,11 +19,11 @@
package net.tylermurphy.hideAndSeek.command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public interface ICommand {
void execute(CommandSender sender, String[] args);
void execute(Player sender, String[] args);
String getLabel();

View file

@ -19,34 +19,31 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Join implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.isNotSetup()) {
public void execute(Player sender, String[] args) {
if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + message("GAME_SETUP"));
return;
}
Player player = Bukkit.getServer().getPlayer(sender.getName());
if(player == null) {
if (player == null) {
sender.sendMessage(errorPrefix + message("COMMAND_ERROR"));
return;
}
if(Board.isPlayer(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,35 +19,30 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Leave implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.isNotSetup()) {
public void execute(Player sender, String[] args) {
if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + message("GAME_SETUP"));
return;
}
Player player = Bukkit.getServer().getPlayer(sender.getName());
if(player == null) {
if (player == null) {
sender.sendMessage(errorPrefix + message("COMMAND_ERROR"));
return;
}
if(!Board.isPlayer(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,23 +19,22 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.command.CommandSender;
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.util.Status;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Config.messagePrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Reload implements ICommand {
public void execute(CommandSender sender, String[] args) {
public void execute(Player sender, String[] args) {
if(Game.status != Status.STANDBY) {
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}

View file

@ -19,47 +19,49 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import net.tylermurphy.hideAndSeek.Main;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SaveMap implements ICommand {
public static boolean runningBackup = false;
public void execute(CommandSender sender, String[] args) {
if(Game.status != Status.STANDBY) {
public void execute(Player sender, String[] args) {
if (!mapSaveEnabled) {
sender.sendMessage(errorPrefix + message("MAPSAVE_DISABLED"));
return;
}
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) {
if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) {
sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN"));
return;
}
sender.sendMessage(messagePrefix + message("MAPSAVE_START"));
sender.sendMessage(warningPrefix + message("MAPSAVE_WARNING"));
World world = Bukkit.getServer().getWorld(spawnWorld);
if(world == null){
if (world == null) {
throw new RuntimeException("Unable to get world: " + spawnWorld);
}
world.save();
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,33 +19,31 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.command.CommandSender;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetBorder implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.status != Status.STANDBY) {
public void execute(Player sender, String[] args) {
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
if(spawnPosition == null) {
if (spawnPosition == null) {
sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN"));
return;
}
if(args.length < 3) {
worldborderEnabled = false;
if (args.length < 3) {
worldBorderEnabled = false;
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;
@ -61,37 +59,37 @@ public class SetBorder implements ICommand {
sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(args[2]));
return;
}
if(num < 100) {
if (num < 100) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_MIN_SIZE"));
return;
}
if(change < 1) {
if (change < 1) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_CHANGE_SIZE"));
return;
}
Vector newWorldborderPosition = new Vector();
Vector vec = new Vector();
Player player = (Player) sender;
newWorldborderPosition.setX(player.getLocation().getBlockX());
newWorldborderPosition.setY(0);
newWorldborderPosition.setZ(player.getLocation().getBlockZ());
if(spawnPosition.distance(newWorldborderPosition) > 100) {
vec.setX(player.getLocation().getBlockX());
vec.setY(0);
vec.setZ(player.getLocation().getBlockZ());
if (spawnPosition.distance(vec) > 100) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION"));
return;
}
worldborderPosition = newWorldborderPosition;
worldborderSize = num;
worldborderDelay = delay;
worldborderChange = change;
worldborderEnabled = true;
addToConfig("worldBorder.x", worldborderPosition.getBlockX());
addToConfig("worldBorder.z", worldborderPosition.getBlockZ());
addToConfig("worldBorder.delay", worldborderDelay);
addToConfig("worldBorder.size", worldborderSize);
worldBorderPosition = vec;
worldBorderSize = num;
worldBorderDelay = delay;
worldBorderChange = change;
worldBorderEnabled = true;
addToConfig("worldBorder.x", worldBorderPosition.getBlockX());
addToConfig("worldBorder.z", worldBorderPosition.getBlockZ());
addToConfig("worldBorder.delay", worldBorderDelay);
addToConfig("worldBorder.size", worldBorderSize);
addToConfig("worldBorder.enabled", true);
addToConfig("worldBorder.move", worldborderChange);
addToConfig("worldBorder.move", worldBorderChange);
sender.sendMessage(messagePrefix + message("WORLDBORDER_ENABLE").addAmount(num).addAmount(delay));
saveConfig();
Game.resetWorldborder(spawnWorld);
Main.getInstance().getGame().getBorder().resetWorldBorder(spawnWorld);
}
public String getLabel() {

View file

@ -19,43 +19,41 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.command.CommandSender;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class SetBounds implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.status != Status.STANDBY) {
public void execute(Player sender, String[] args) {
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
sender.sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
if(spawnPosition == null) {
if (spawnPosition == null) {
sender.sendMessage(errorPrefix + message("ERROR_GAME_SPAWN"));
return;
}
Player player = (Player) sender;
if(!player.getWorld().getName().equals(spawnWorld)){
if (!player.getWorld().getName().equals(spawnWorld)) {
sender.sendMessage(errorPrefix + message("BOUNDS_WRONG_WORLD"));
return;
}
if(player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0){
if (player.getLocation().getBlockX() == 0 || player.getLocation().getBlockZ() == 0) {
sender.sendMessage(errorPrefix + message("NOT_AT_ZERO"));
return;
}
boolean first = true;
if(saveMinX != 0 && saveMinZ != 0 && saveMaxX != 0 && saveMaxZ != 0) {
if (saveMinX != 0 && saveMinZ != 0 && saveMaxX != 0 && saveMaxZ != 0) {
saveMinX = 0; saveMinZ= 0; saveMaxX = 0; saveMaxZ = 0;
}
if(saveMaxX == 0) {
if (saveMaxX == 0) {
addToConfig("bounds.max.x", player.getLocation().getBlockX());
saveMaxX = player.getLocation().getBlockX();
} else if(saveMaxX < player.getLocation().getBlockX()) {
} else if (saveMaxX < player.getLocation().getBlockX()) {
first = false;
addToConfig("bounds.max.x", player.getLocation().getBlockX());
addToConfig("bounds.min.x", saveMaxX);
@ -66,10 +64,10 @@ public class SetBounds implements ICommand {
addToConfig("bounds.min.x", player.getLocation().getBlockX());
saveMinX = player.getLocation().getBlockX();
}
if(saveMaxZ == 0) {
if (saveMaxZ == 0) {
addToConfig("bounds.max.z", player.getLocation().getBlockZ());
saveMaxZ = player.getLocation().getBlockZ();
} else if(saveMaxZ < player.getLocation().getBlockZ()) {
} else if (saveMaxZ < player.getLocation().getBlockZ()) {
first = false;
addToConfig("bounds.max.z", player.getLocation().getBlockZ());
addToConfig("bounds.min.z", saveMaxZ);

View file

@ -1,75 +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 static net.tylermurphy.hideAndSeek.configuration.Config.*;
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.Localization.*;
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,75 +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 static net.tylermurphy.hideAndSeek.configuration.Config.*;
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.Localization.*;
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,85 +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 static net.tylermurphy.hideAndSeek.configuration.Config.*;
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.addToConfig;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
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(!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

@ -19,44 +19,45 @@
package net.tylermurphy.hideAndSeek.command;
import org.bukkit.command.CommandSender;
import net.tylermurphy.hideAndSeek.Main;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import org.bukkit.entity.Player;
import java.io.File;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Setup implements ICommand {
public void execute(CommandSender sender, String[] args) {
public void execute(Player sender, String[] args) {
String msg = message("SETUP").toString();
int count = 0;
if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) {
if (spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) {
msg = msg + "\n" + message("SETUP_GAME");
count++;
}
if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) {
if (lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) {
msg = msg + "\n" + message("SETUP_LOBBY");
count++;
}
if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) {
if (exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) {
msg = msg + "\n" + message("SETUP_EXIT");
count++;
}
if(saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0) {
if (saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0) {
msg = msg + "\n" + message("SETUP_BOUNDS");
count++;
}
File destenation = new File(Main.root+File.separator+"hideandseek_"+spawnWorld);
if(!destenation.exists()) {
if (mapSaveEnabled) {
File destenation = new File(Main.getInstance().getWorldContainer() + File.separator + Main.getInstance().getGame().getGameWorld());
if (!destenation.exists()) {
msg = msg + "\n" + message("SETUP_SAVEMAP");
count++;
}
if(count < 1) {
}
if (count < 1) {
sender.sendMessage(messagePrefix + message("SETUP_COMPLETE"));
} else {
sender.sendMessage(msg);

View file

@ -19,46 +19,42 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.tylermurphy.hideAndSeek.Main;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Optional;
import java.util.Random;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Config.minPlayers;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Start implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.isNotSetup()) {
public void execute(Player sender, String[] args) {
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.isPlayer(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();
if(!rand.isPresent()){
Main.plugin.getLogger().warning("Failed to select random seeker.");
if (args.length < 1) {
Optional<Player> rand = Main.getInstance().getBoard().getPlayers().stream().skip(new Random().nextInt(Main.getInstance().getBoard().size())).findFirst();
if (!rand.isPresent()) {
Main.getInstance().getLogger().warning("Failed to select random seeker.");
return;
}
seekerName = rand.get().getName();
@ -66,16 +62,16 @@ public class Start implements ICommand {
seekerName = args[0];
}
Player temp = Bukkit.getPlayer(seekerName);
if(temp == null) {
if (temp == null) {
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(seekerName));
return;
}
Player seeker = Board.getPlayer(temp.getUniqueId());
if(seeker == null) {
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,27 +19,24 @@
package net.tylermurphy.hideAndSeek.command;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.entity.Player;
import net.tylermurphy.hideAndSeek.game.Game;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.util.WinType;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.abortPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Stop implements ICommand {
public void execute(CommandSender sender, String[] args) {
if(Game.isNotSetup()) {
public void execute(Player sender, String[] args) {
if (Main.getInstance().getGame().isNotSetup()) {
sender.sendMessage(errorPrefix + "Game is not setup. Run /hs setup to see what you needed to do");
return;
}
if(Game.status == Status.STARTING || Game.status == Status.PLAYING) {
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("STOP"));
else Game.broadcastMessage(abortPrefix + message("STOP"));
Game.stop(WinType.NONE);
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,47 +20,52 @@
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.database.util.PlayerInfo;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import java.util.List;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Top implements ICommand {
public void execute(CommandSender sender, String[] args) {
public void execute(Player sender, String[] args) {
int page;
if(args.length == 0) page = 1;
if (args.length == 0) page = 1;
else try{
page = Integer.parseInt(args[0]);
} catch(Exception e){
} catch(Exception e) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(args[0]));
return;
}
if(page < 1){
if (page < 1) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_INVALID_INPUT").addAmount(page));
return;
}
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;
for(PlayerInfo info : infos){
String name = Main.plugin.getServer().getOfflinePlayer(info.uuid).getName();
if (infos == null) {
sender.sendMessage(errorPrefix + message("NO_GAME_INFO"));
return;
}
for(PlayerInfo info : infos) {
String name = Main.getInstance().getDatabase().getNameData().getName(info.getUniqueId());
ChatColor color;
switch (i){
switch (i) {
case 1: color = ChatColor.YELLOW; break;
case 2: color = ChatColor.GRAY; break;
case 3: color = ChatColor.GOLD; break;
default: color = ChatColor.WHITE; break;
}
message.append(String.format("%s%s. %s%s %s%s\n",
color, i, ChatColor.RED, info.wins, ChatColor.WHITE, name));
color, i, ChatColor.RED, info.getSeekerWins() +info.getHiderWins(), ChatColor.WHITE, name));
i++;
}
sender.sendMessage(message.toString());

View file

@ -20,45 +20,36 @@
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 net.tylermurphy.hideAndSeek.database.util.PlayerInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class Wins implements ICommand {
public void execute(CommandSender sender, String[] args) {
Main.plugin.getServer().getScheduler().runTaskAsynchronously(Main.plugin, () -> {
public void execute(Player sender, String[] args) {
Main.getInstance().getServer().getScheduler().runTaskAsynchronously(Main.getInstance(), () -> {
UUID uuid;
String name;
if(args.length == 0) {
Player player = Main.plugin.getServer().getPlayer(sender.getName());
if(player == null){
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(sender.getName()));
return;
}
uuid = player.getUniqueId();
if (args.length == 0) {
uuid = sender.getUniqueId();
name = sender.getName();
}
else {
try {
name = args[0];
uuid = UUIDFetcher.getUUID(args[0]);
} catch (Exception e){
uuid = Main.getInstance().getDatabase().getNameData().getUUID(args[0]);
}
if(uuid == null){
sender.sendMessage(errorPrefix + message("START_INVALID_NAME").addPlayer(args[0]));
return;
}
}
PlayerInfo info = Database.playerInfo.getInfo(uuid);
if(info == null){
PlayerInfo info = Main.getInstance().getDatabase().getGameData().getInfo(uuid);
if (info == null) {
sender.sendMessage(errorPrefix + message("NO_GAME_INFO"));
return;
}
@ -66,8 +57,8 @@ public class Wins implements ICommand {
message = message + message("INFORMATION_FOR").addPlayer(name) + "\n";
message = message + "==============================\n";
message = message + String.format("%sTOTAL WINS: %s%s\n%sHIDER WINS: %s%s\n%sSEEKER WINS: %s%s\n%sGAMES PLAYED: %s",
ChatColor.YELLOW, ChatColor.WHITE, info.wins, ChatColor.GOLD, ChatColor.WHITE, info.hider_wins,
ChatColor.RED, ChatColor.WHITE, info.seeker_wins, ChatColor.WHITE, info.games_played);
ChatColor.YELLOW, ChatColor.WHITE, info.getSeekerWins() +info.getHiderWins(), ChatColor.GOLD, ChatColor.WHITE, info.getHiderWins(),
ChatColor.RED, ChatColor.WHITE, info.getSeekerWins(), ChatColor.WHITE, info.getSeekerGames() +info.getHiderGames());
message = message + ChatColor.WHITE + "" + ChatColor.BOLD + "\n==============================";
sender.sendMessage(message);

View file

@ -0,0 +1,49 @@
/*
* 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.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class SetExitLocation implements ICommand {
public void execute(Player sender, String[] args) {
LocationUtils.setLocation(sender, Locations.EXIT, vector -> {
exitWorld = sender.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,50 @@
/*
* 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.entity.Player;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class SetLobbyLocation implements ICommand {
public void execute(Player sender, String[] args) {
LocationUtils.setLocation(sender, Locations.LOBBY, vector -> {
lobbyWorld = sender.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,62 @@
/*
* 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.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(Player sender, String[] args) {
LocationUtils.setLocation(sender, Locations.GAME, vector -> {
if (worldBorderEnabled && vector.distance(worldBorderPosition) > 100) {
sender.sendMessage(errorPrefix + message("WORLDBORDER_POSITION"));
throw new RuntimeException("World border not enabled or not in valid position!");
}
if (!sender.getLocation().getWorld().getName().equals(spawnWorld)) {
Main.getInstance().getGame().getWorldLoader().unloadMap();
Main.getInstance().getGame().getWorldLoader().setNewMap(sender.getLocation().getWorld().getName());
}
spawnWorld = sender.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,59 @@
package net.tylermurphy.hideAndSeek.command.location.util;
import net.tylermurphy.hideAndSeek.Main;
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;
/**
* @author bobby29831
*/
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,25 @@
package net.tylermurphy.hideAndSeek.command.location.util;
/**
* @author bobby29831
*/
public enum Locations {
GAME("spawns.game"),
LOBBY("spawns.lobby"),
EXIT("spawns.exit");
private final String path;
Locations(String path) {
this.path = path;
}
public String message() {
return this + "_SPAWN";
}
public String path(String additive) {
return path + "." + additive;
}
}

View file

@ -21,13 +21,16 @@ package net.tylermurphy.hideAndSeek.configuration;
import com.cryptomorin.xseries.XItemStack;
import com.cryptomorin.xseries.XMaterial;
import net.tylermurphy.hideAndSeek.util.Version;
import com.cryptomorin.xseries.XSound;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.CountdownDisplay;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
@ -36,36 +39,45 @@ import java.util.Optional;
public class Config {
private static ConfigManager config, leaderboard;
private static ConfigManager config;
public static String
messagePrefix,
errorPrefix,
tauntPrefix,
worldborderPrefix,
worldBorderPrefix,
abortPrefix,
gameoverPrefix,
gameOverPrefix,
warningPrefix,
spawnWorld,
exitWorld,
lobbyWorld,
locale,
leaveServer;
leaveServer,
placeholderError,
placeholderNoData,
databaseType,
databaseHost,
databasePort,
databaseUser,
databasePass,
databaseName;
public static Vector
spawnPosition,
lobbyPosition,
exitPosition,
worldborderPosition;
worldBorderPosition;
public static boolean
nametagsVisible,
nameTagsVisible,
permissionsRequired,
announceMessagesToNonPlayers,
worldborderEnabled,
worldBorderEnabled,
tauntEnabled,
tauntCountdown,
tauntLast,
alwaysGlow,
glowEnabled,
glowStackable,
pvpEnabled,
@ -74,14 +86,17 @@ public class Config {
lobbyCountdownEnabled,
seekerPing,
bungeeLeave,
lobbyItemStartAdmin;
lobbyItemStartAdmin,
leaveOnEnd,
mapSaveEnabled,
allowNaturalCauses;
public static int
minPlayers,
worldborderSize,
worldborderDelay,
worldBorderSize,
worldBorderDelay,
currentWorldborderSize,
worldborderChange,
worldBorderChange,
gameLength,
saveMinX,
saveMinZ,
@ -97,7 +112,14 @@ public class Config {
seekerPingLevel2,
seekerPingLevel3,
lobbyItemLeavePosition,
lobbyItemStartPosition;
lobbyItemStartPosition,
flightToggleItemPosition,
teleportItemPosition;
public static float
seekerPingLeadingVolume,
seekerPingVolume,
seekerPingPitch;
public static List<String>
blockedCommands,
@ -123,18 +145,28 @@ public class Config {
public static ItemStack
lobbyLeaveItem,
lobbyStartItem;
lobbyStartItem,
glowPowerupItem,
flightToggleItem,
teleportItem;
public static XSound
ringingSound,
heartbeatSound;
public static CountdownDisplay
countdownDisplay;
public static void loadConfig() {
config = new ConfigManager("config.yml");
config = ConfigManager.create("config.yml");
config.saveConfig();
leaderboard = new ConfigManager("leaderboard.yml");
ConfigManager leaderboard = ConfigManager.create("leaderboard.yml");
//Spawn
spawnPosition = new Vector(
config.getDouble("spawns.game.x"),
Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.game.y"))),
Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.game.y"))),
config.getDouble("spawns.game.z")
);
spawnWorld = config.getString("spawns.game.world");
@ -142,7 +174,7 @@ public class Config {
///Lobby
lobbyPosition = new Vector(
config.getDouble("spawns.lobby.x"),
Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.lobby.y"))),
Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.lobby.y"))),
config.getDouble("spawns.lobby.z")
);
lobbyWorld = config.getString("spawns.lobby.world");
@ -151,21 +183,21 @@ public class Config {
exitPosition = new Vector(
config.getDouble("spawns.exit.x"),
Math.max(Version.atLeast("1.18") ? -64 : 0, Math.min(255, config.getDouble("spawns.exit.y"))),
Math.max(Main.getInstance().supports(18) ? -64 : 0, Math.min(255, config.getDouble("spawns.exit.y"))),
config.getDouble("spawns.exit.z")
);
exitWorld = config.getString("spawns.exit.world");
//World border
worldborderPosition = new Vector(
worldBorderPosition = new Vector(
config.getInt("worldBorder.x"),
0,
config.getInt("worldBorder.z")
);
worldborderSize = Math.max(100, config.getInt("worldBorder.size"));
worldborderDelay = Math.max(1, config.getInt("worldBorder.delay"));
worldborderEnabled = config.getBoolean("worldBorder.enabled");
worldborderChange = config.getInt("worldBorder.moveAmount");
worldBorderSize = Math.max(100, config.getInt("worldBorder.size"));
worldBorderDelay = Math.max(1, config.getInt("worldBorder.delay"));
worldBorderEnabled = config.getBoolean("worldBorder.enabled");
worldBorderChange = config.getInt("worldBorder.moveAmount");
//Prefix
char SYMBOLE = '\u00A7';
@ -174,9 +206,9 @@ public class Config {
messagePrefix = config.getString("prefix.default").replace("&", SYMBOLE_STRING);
errorPrefix = config.getString("prefix.error").replace("&", SYMBOLE_STRING);
tauntPrefix = config.getString("prefix.taunt").replace("&", SYMBOLE_STRING);
worldborderPrefix = config.getString("prefix.border").replace("&", SYMBOLE_STRING);
worldBorderPrefix = config.getString("prefix.border").replace("&", SYMBOLE_STRING);
abortPrefix = config.getString("prefix.abort").replace("&", SYMBOLE_STRING);
gameoverPrefix = config.getString("prefix.gameover").replace("&", SYMBOLE_STRING);
gameOverPrefix = config.getString("prefix.gameover").replace("&", SYMBOLE_STRING);
warningPrefix = config.getString("prefix.warning").replace("&", SYMBOLE_STRING);
//Map Bounds
@ -184,6 +216,7 @@ public class Config {
saveMinZ = config.getInt("bounds.min.z");
saveMaxX = config.getInt("bounds.max.x");
saveMaxZ = config.getInt("bounds.max.z");
mapSaveEnabled = config.getBoolean("mapSaveEnabled");
//Taunt
tauntEnabled = config.getBoolean("taunt.enabled");
@ -192,9 +225,13 @@ public class Config {
tauntLast = config.getBoolean("taunt.whenLastPerson");
//Glow
alwaysGlow = config.getBoolean("alwaysGlow") && Main.getInstance().supports(9);
glowLength = Math.max(1, config.getInt("glow.time"));
glowStackable = config.getBoolean("glow.stackable");
glowEnabled = config.getBoolean("glow.enabled") && Version.atLeast("1.9");
glowEnabled = config.getBoolean("glow.enabled") && Main.getInstance().supports(9) && !alwaysGlow;
if (glowEnabled) {
glowPowerupItem = createItemStack("glow");
}
//Lobby
minPlayers = Math.max(2, config.getInt("minPlayers"));
@ -209,23 +246,40 @@ public class Config {
seekerPingLevel1 = config.getInt("seekerPing.distances.level1");
seekerPingLevel2 = config.getInt("seekerPing.distances.level2");
seekerPingLevel3 = config.getInt("seekerPing.distances.level3");
seekerPingLeadingVolume = config.getFloat("seekerPing.sounds.leadingVolume");
seekerPingVolume = config.getFloat("seekerPing.sounds.volume");
seekerPingPitch = config.getFloat("seekerPing.sounds.pitch");
Optional<XSound> heartbeatOptional = XSound.matchXSound(config.getString("seekerPing.sounds.heartbeatNoise"));
heartbeatSound = heartbeatOptional.orElse(XSound.BLOCK_NOTE_BLOCK_BASEDRUM);
Optional<XSound> ringingOptional = XSound.matchXSound(config.getString("seekerPing.sounds.ringingNoise"));
ringingSound = ringingOptional.orElse(XSound.BLOCK_NOTE_BLOCK_PLING);
//Other
nametagsVisible = config.getBoolean("nametagsVisible");
nameTagsVisible = config.getBoolean("nametagsVisible");
permissionsRequired = config.getBoolean("permissionsRequired");
gameLength = config.getInt("gameLength");
pvpEnabled = config.getBoolean("pvp");
allowNaturalCauses = config.getBoolean("allowNaturalCauses");
autoJoin = config.getBoolean("autoJoin");
teleportToExit = config.getBoolean("teleportToExit");
locale = config.getString("locale", "local");
blockedCommands = config.getStringList("blockedCommands");
leaveOnEnd = config.getBoolean("leaveOnEnd");
placeholderError = config.getString("placeholder.incorrect");
placeholderNoData = config.getString("placeholder.noData");
try {
countdownDisplay = CountdownDisplay.valueOf(config.getString("hideCountdownDisplay"));
} catch (IllegalArgumentException e) {
countdownDisplay = CountdownDisplay.CHAT;
Main.getInstance().getLogger().warning("hideCountdownDisplay: "+config.getString("hideCountdownDisplay")+" is not a valid configuration option!");
}
blockedInteracts = new ArrayList<>();
List<String> tempInteracts = config.getStringList("blockedInteracts");
for(String id : tempInteracts){
for(String id : tempInteracts) {
Optional<XMaterial> optional_mat = XMaterial.matchXMaterial(id);
if(optional_mat.isPresent()){
if (optional_mat.isPresent()) {
Material mat = optional_mat.get().parseMaterial();
if(mat != null){
if (mat != null) {
blockedInteracts.add(mat.name());
}
}
@ -252,29 +306,35 @@ public class Config {
BORDER_DECREASING = leaderboard.getString("border.decreasing");
//Lobby Items
if(config.getBoolean("lobbyItems.leave.enabled")) {
ConfigurationSection item = new YamlConfiguration().createSection("temp");
item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.leave.name")));
item.set("material", config.getString("lobbyItems.leave.material"));
List<String> lore = config.getStringList("lobbyItems.leave.lore");
if (lore != null && !lore.isEmpty()) item.set("lore", lore);
ItemStack temp = null;
try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){}
lobbyLeaveItem = temp;
if (config.getBoolean("lobbyItems.leave.enabled")) {
lobbyLeaveItem = createItemStack("lobbyItems.leave");
lobbyItemLeavePosition = config.getInt("lobbyItems.leave.position");
}
if(config.getBoolean("lobbyItems.start.enabled")) {
ConfigurationSection item = new YamlConfiguration().createSection("temp");
item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString("lobbyItems.start.name")));
item.set("material", config.getString("lobbyItems.start.material"));
List<String> lore = config.getStringList("lobbyItems.start.lore");
if (lore != null && !lore.isEmpty()) item.set("lore", lore);
ItemStack temp = null;
try{ temp = XItemStack.deserialize(item); } catch(Exception ignored){}
lobbyStartItem = temp;
if (config.getBoolean("lobbyItems.start.enabled")) {
lobbyStartItem = createItemStack("lobbyItems.start");
lobbyItemStartAdmin = config.getBoolean("lobbyItems.start.adminOnly");
lobbyItemStartPosition = config.getInt("lobbyItems.start.position");
}
//Spectator Items
flightToggleItem = createItemStack("spectatorItems.flight");
flightToggleItemPosition = config.getInt("spectatorItems.flight.position");
teleportItem = createItemStack("spectatorItems.teleport");
teleportItemPosition = config.getInt("spectatorItems.teleport.position");
//Database
databaseHost = config.getString("databaseHost");
databasePort = config.getString("databasePort");
databaseUser = config.getString("databaseUser");
databasePass = config.getString("databasePass");
databaseName = config.getString("databaseName");
databaseType = config.getString("databaseType").toUpperCase();
if(!databaseType.equals("SQLITE") && !databaseType.equals("MYSQL")){
Main.getInstance().getLogger().warning("databaseType: "+databaseType+" is not a valid configuration option!");
databaseType = "SQLITE";
}
}
public static void addToConfig(String path, Object value) {
@ -285,4 +345,21 @@ public class Config {
config.saveConfig();
}
@Nullable
private static ItemStack createItemStack(String path){
ConfigurationSection item = new YamlConfiguration().createSection("temp");
item.set("name", ChatColor.translateAlternateColorCodes('&',config.getString(path+".name")));
item.set("material", config.getString(path+".material"));
if (Main.getInstance().supports(14)) {
if (config.contains(path+".model-data") && config.getInt(path+".model-data") != 0) {
item.set("model-data", config.getInt(path+".model-data"));
}
}
List<String> lore = config.getStringList(path+".lore");
if (lore != null && !lore.isEmpty()) item.set("lore", lore);
ItemStack temp = null;
try{ temp = XItemStack.deserialize(item); } catch(Exception ignored) {}
return temp;
}
}

View file

@ -21,6 +21,7 @@ package net.tylermurphy.hideAndSeek.configuration;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.*;
@ -35,111 +36,136 @@ public class ConfigManager {
private YamlConfiguration config,defaultConfig;
private String defaultFilename;
public ConfigManager(String filename){
this.file = new File(Main.data, filename);
this.defaultFilename = file.getName();
public static ConfigManager create(String filename) {
return new ConfigManager(filename, filename);
}
File folder = Main.data;
if(!folder.exists()){
if(!folder.mkdirs()){
public static ConfigManager create(String filename, String defaultFilename) {
return new ConfigManager(filename, defaultFilename);
}
private ConfigManager(String filename, String defaultFilename) {
File dataFolder = Main.getInstance().getDataFolder();
File oldDataFolder = new File(Main.getInstance().getDataFolder().getParent() + File.separator + "HideAndSeek");
this.defaultFilename = defaultFilename;
this.file = new File(dataFolder, filename);
if(oldDataFolder.exists()){
if(!dataFolder.exists()){
if(!oldDataFolder.renameTo(dataFolder)){
throw new RuntimeException("Could not rename folder: " + oldDataFolder.getPath());
}
} else {
throw new RuntimeException("Plugin folders for HideAndSeek & KenshinsHideAndSeek both exists. There can only be one!");
}
}
if (!dataFolder.exists()) {
if (!dataFolder.mkdirs()) {
throw new RuntimeException("Failed to make directory: " + file.getPath());
}
}
if(!file.exists()){
saveDefaultConfiguration();
}
this.config = YamlConfiguration.loadConfiguration(file);
InputStream input = Main.plugin.getResource(file.getName());
if(input == null){
throw new RuntimeException("Could not create input stream for "+file.getPath());
}
InputStreamReader reader = new InputStreamReader(input);
this.defaultConfig = YamlConfiguration.loadConfiguration(reader);
if (!file.exists()) {
try{
input.close();
reader.close();
} catch (IOException ignored){}
}
public ConfigManager(String filename, String defaultFilename){
this.defaultFilename = defaultFilename;
this.file = new File(Main.data, filename);
if(!file.exists()){
saveDefaultConfiguration();
}
this.config = YamlConfiguration.loadConfiguration(file);
InputStream input = Main.plugin.getResource(defaultFilename);
if(input == null){
throw new RuntimeException("Could not create input stream for "+defaultFilename);
}
InputStreamReader reader = new InputStreamReader(input);
this.defaultConfig = YamlConfiguration.loadConfiguration(reader);
try{
input.close();
reader.close();
} catch (IOException e){
Main.plugin.getLogger().severe("Couldn't find "+defaultFilename+" internally. Did you set an incorrect local?");
Main.plugin.getServer().getPluginManager().disablePlugin(Main.plugin);
throw new RuntimeException();
}
}
private void saveDefaultConfiguration(){
try{
InputStream input = Main.plugin.getResource(defaultFilename);
if(input == null){
InputStream input = Main.getInstance().getResource(defaultFilename);
if (input == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename);
}
java.nio.file.Files.copy(input, file.toPath());
input.close();
} catch(IOException e){
} catch(IOException e) {
e.printStackTrace();
}
}
public double getDouble(String path){
double value = config.getDouble(path);
if(value == 0.0D){
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException("Could not create input stream for "+file.getPath());
}
InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
this.config = new YamlConfiguration();
try {
this.config.load(reader);
} catch(InvalidConfigurationException e) {
throw new RuntimeException("Invalid configuration in config file: "+file.getPath());
} catch(IOException e) {
throw new RuntimeException("Could not access file: "+file.getPath());
}
InputStream input = this.getClass().getClassLoader().getResourceAsStream(defaultFilename);
if (input == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename);
}
InputStreamReader default_reader = new InputStreamReader(input, StandardCharsets.UTF_8);
this.defaultConfig = new YamlConfiguration();
try {
this.defaultConfig.load(default_reader);
} catch(InvalidConfigurationException e) {
throw new RuntimeException("Invalid configuration in config file: "+file.getPath());
} catch(IOException e) {
throw new RuntimeException("Could not access file: "+file.getPath());
}
try{
fileInputStream.close();
default_reader.close();
} catch (IOException e) {
throw new RuntimeException("Unable to finalize loading of config files.");
}
}
public boolean contains(String path) {
return config.contains(path);
}
public double getDouble(String path) {
if (!config.contains(path)) {
return defaultConfig.getDouble(path);
} else {
return value;
return config.getDouble(path);
}
}
public int getInt(String path){
int value = config.getInt(path);
if(value == 0){
public int getInt(String path) {
if (!config.contains(path)) {
return defaultConfig.getInt(path);
} else {
return value;
return config.getInt(path);
}
}
public int getDefaultInt(String path){
public int getDefaultInt(String path) {
return defaultConfig.getInt(path);
}
public String getString(String path){
public float getFloat(String path) {
if (!config.contains(path)) {
return (float) defaultConfig.getDouble(path);
} else {
return (float) config.getDouble(path);
}
}
public String getString(String path) {
String value = config.getString(path);
if(value == null){
if (value == null) {
return defaultConfig.getString(path);
} else {
return value;
}
}
public String getString(String path, String oldPath){
public String getString(String path, String oldPath) {
String value = config.getString(path);
if(value == null){
if (value == null) {
String oldValue = config.getString(oldPath);
if(oldValue == null){
if (oldValue == null) {
return defaultConfig.getString(path);
} else {
return oldValue;
@ -149,24 +175,24 @@ public class ConfigManager {
}
}
public List<String> getStringList(String path){
public List<String> getStringList(String path) {
List<String> value = config.getStringList(path);
if(value == null){
if (value == null) {
return defaultConfig.getStringList(path);
} else {
return value;
}
}
public void reset(String path){
public void reset(String path) {
config.set(path, defaultConfig.get(path));
}
public void resetFile(String newDefaultFilename){
public void resetFile(String newDefaultFilename) {
this.defaultFilename = newDefaultFilename;
InputStream input = Main.plugin.getResource(defaultFilename);
if(input == null){
InputStream input = Main.getInstance().getResource(defaultFilename);
if (input == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename);
}
InputStreamReader reader = new InputStreamReader(input);
@ -175,85 +201,94 @@ public class ConfigManager {
}
public boolean getBoolean(String path){
boolean value = config.getBoolean(path);
if(!value){
public boolean getBoolean(String path) {
if (!config.contains(path)) {
return defaultConfig.getBoolean(path);
} else {
return true;
return config.getBoolean(path);
}
}
public ConfigurationSection getConfigurationSection(String path){
public ConfigurationSection getConfigurationSection(String path) {
ConfigurationSection section = config.getConfigurationSection(path);
if(section == null){
if (section == null) {
return defaultConfig.getConfigurationSection(path);
} else {
return section;
}
}
public void set(String path, Object value){
public ConfigurationSection getDefaultConfigurationSection(String path) {
return defaultConfig.getConfigurationSection(path);
}
public void set(String path, Object value) {
config.set(path, value);
}
public void saveConfig(){
public void saveConfig() {
try {
InputStream is = Main.plugin.getResource(defaultFilename);
if(is == null){
InputStream is = Main.getInstance().getResource(defaultFilename);
if (is == null) {
throw new RuntimeException("Could not create input stream for "+defaultFilename);
}
StringBuilder textBuilder = new StringBuilder();
StringBuilder textBuilder = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8));
Reader reader = new BufferedReader(new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name())));
int c;
while((c = reader.read()) != -1){
while((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
String yamlString = textBuilder.toString();
String yamlString = new String(textBuilder.toString().getBytes(), StandardCharsets.UTF_8);
Map<String, Object> temp = config.getValues(true);
for(Map.Entry<String, Object> entry: temp.entrySet()){
if(entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List){
for(Map.Entry<String, Object> entry: temp.entrySet()) {
if (entry.getValue() instanceof Integer || entry.getValue() instanceof Double || entry.getValue() instanceof String || entry.getValue() instanceof Boolean || entry.getValue() instanceof List) {
String[] parts = entry.getKey().split("\\.");
int index = 0;
int i = 0;
for(String part : parts) {
if(i == 0) {
if (i == 0) {
index = yamlString.indexOf(part+":", index);
} else {
index = yamlString.indexOf(" " + part+":", index);
index++;
}
i++;
if(index == -1) break;
if (index == -1) break;
}
if(index < 10) continue;
if (index < 10) continue;
int start = yamlString.indexOf(' ', index);
int end = yamlString.indexOf('\n', index);
if(end == -1) end = yamlString.length();
String replace;
if(entry.getValue() instanceof List){
if(((List<?>) entry.getValue()).isEmpty()) continue;
replace = "[";
for(Object o : (List<Object>)entry.getValue()){
replace = replace + o.toString() + ", ";
}
replace = replace.substring(0, replace.length()-2);
replace = replace + "]";
if (end == -1) end = yamlString.length();
StringBuilder replace = new StringBuilder(new String("".getBytes(), StandardCharsets.UTF_8));
if (entry.getValue() instanceof List) {
if (((List<?>) entry.getValue()).isEmpty()) {
replace.append("[]");
} else {
replace = entry.getValue().toString();
replace.append("[");
for (Object o : (List<?>) entry.getValue()) {
replace.append(o.toString()).append(", ");
}
if(entry.getValue() instanceof String){
replace = "\"" + replace + "\"";
replace = new StringBuilder(replace.substring(0, replace.length() - 2));
replace.append("]");
}
} else {
replace.append(entry.getValue());
}
if (entry.getValue() instanceof String) {
replace.append("\"");
replace.reverse();
replace.append("\"");
replace.reverse();
}
StringBuilder builder = new StringBuilder(yamlString);
builder.replace(start+1, end, replace);
builder.replace(start+1, end, replace.toString());
yamlString = builder.toString();
}
}
PrintWriter out = new PrintWriter(file);
out.print(yamlString);
out.close();
} catch (IOException e){
Writer fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
fileWriter.write(yamlString);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}

View file

@ -20,16 +20,16 @@
package net.tylermurphy.hideAndSeek.configuration;
import com.cryptomorin.xseries.XItemStack;
import net.tylermurphy.hideAndSeek.util.Version;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.*;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Items {
@ -38,16 +38,16 @@ public class Items {
public static void loadItems() {
ConfigManager manager = new ConfigManager("items.yml");
ConfigManager manager = ConfigManager.create("items.yml");
SEEKER_ITEMS = new ArrayList<>();
ConfigurationSection SeekerItems = manager.getConfigurationSection("items.seeker");
int i = 1;
while (true) {
ConfigurationSection section = SeekerItems.getConfigurationSection(String.valueOf(i));
if(section == null) break;
if (section == null) break;
ItemStack item = createItem(section);
if(item != null) SEEKER_ITEMS.add(item);
if (item != null) SEEKER_ITEMS.add(item);
i++;
}
@ -56,9 +56,9 @@ public class Items {
i = 1;
while (true) {
ConfigurationSection section = HiderItems.getConfigurationSection(String.valueOf(i));
if(section == null) break;
if (section == null) break;
ItemStack item = createItem(section);
if(item != null) HIDER_ITEMS.add(item);
if (item != null) HIDER_ITEMS.add(item);
i++;
}
SEEKER_EFFECTS = new ArrayList<>();
@ -66,9 +66,9 @@ public class Items {
i = 1;
while (true) {
ConfigurationSection section = SeekerEffects.getConfigurationSection(String.valueOf(i));
if(section == null) break;
if (section == null) break;
PotionEffect effect = getPotionEffect(section);
if(effect != null) SEEKER_EFFECTS.add(effect);
if (effect != null) SEEKER_EFFECTS.add(effect);
i++;
}
@ -77,9 +77,9 @@ public class Items {
i = 1;
while (true) {
ConfigurationSection section = HiderEffects.getConfigurationSection(String.valueOf(i));
if(section == null) break;
if (section == null) break;
PotionEffect effect = getPotionEffect(section);
if(effect != null) HIDER_EFFECTS.add(effect);
if (effect != null) HIDER_EFFECTS.add(effect);
i++;
}
@ -89,11 +89,11 @@ public class Items {
ConfigurationSection config = new YamlConfiguration().createSection("temp");
String material = item.getString("material").toUpperCase();
boolean splash = false;
if(!Version.atLeast("1.9")){
if(material.contains("POTION")){
if (!Main.getInstance().supports(9)) {
if (material.contains("POTION")) {
config.set("level", 1);
}
if(material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")){
if (material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION")) {
material = "POTION";
splash = true;
}
@ -102,22 +102,27 @@ public class Items {
config.set("material", material);
config.set("enchants", item.getConfigurationSection("enchantments"));
config.set("unbreakable", item.getBoolean("unbreakable"));
if(item.isSet("lore"))
if (Main.getInstance().supports(14)) {
if (item.contains("model-data")) {
config.set("model-data", item.getInt("model-data"));
}
}
if (item.isSet("lore"))
config.set("lore", item.getStringList("lore"));
if (material.equalsIgnoreCase("POTION") || material.equalsIgnoreCase("SPLASH_POTION") || material.equalsIgnoreCase("LINGERING_POTION"))
config.set("base-effect", String.format("%s,%s,%s", item.getString("type"), false, splash));
ItemStack stack = XItemStack.deserialize(config);
stack.setAmount(item.getInt("amount"));
if(stack.getData().getItemType() == Material.AIR) return null;
if (stack.getData().getItemType() == Material.AIR) return null;
return stack;
}
private static PotionEffect getPotionEffect(ConfigurationSection item){
private static PotionEffect getPotionEffect(ConfigurationSection item) {
String type = item.getString("type");
if(type == null) return null;
if(PotionEffectType.getByName(type.toUpperCase()) == null) return null;
if (type == null) return null;
if (PotionEffectType.getByName(type.toUpperCase()) == null) return null;
return new PotionEffect(
Objects.requireNonNull(PotionEffectType.getByName(type.toUpperCase())),
PotionEffectType.getByName(type.toUpperCase()),
item.getInt("duration"),
item.getInt("amplifier"),
item.getBoolean("ambient"),

View file

@ -19,30 +19,31 @@
package net.tylermurphy.hideAndSeek.configuration;
import net.md_5.bungee.api.ChatColor;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.md_5.bungee.api.ChatColor;
public class Localization {
public static final Map<String,LocalizationString> LOCAL = new HashMap<>();
public static final Map<String,LocalizationString> DEFAULT_LOCAL = new HashMap<>();
private static final Map<String,String[][]> CHANGES = new HashMap<String,String[][]>() {{
put("en-US", new String[][]{{"WORLDBORDER_DECREASING"},{"START","TAUNTED"}});
put("de-DE", new String[][]{{}});
put("de-DE", new String[][]{{},{"TAUNTED"}});
}};
public static void loadLocalization() {
ConfigManager manager = new ConfigManager("localization.yml", "lang/localization_"+Config.locale +".yml");
ConfigManager manager = ConfigManager.create("localization.yml", "lang/localization_"+Config.locale +".yml");
int PLUGIN_VERSION = manager.getDefaultInt("version");
int VERSION = manager.getInt("version");
if(VERSION < PLUGIN_VERSION){
for(int i = VERSION; i < PLUGIN_VERSION; i++){
if(i < 1) continue;
if (VERSION < PLUGIN_VERSION) {
for(int i = VERSION; i < PLUGIN_VERSION; i++) {
if (i < 1) continue;
String[] changeList = CHANGES.get(Config.locale)[i-1];
for(String change : changeList)
manager.reset("Localization." + change);
@ -51,9 +52,9 @@ public class Localization {
}
String SELECTED_LOCAL = manager.getString("type");
if(SELECTED_LOCAL == null){
if (SELECTED_LOCAL == null) {
manager.reset("type");
} else if(!SELECTED_LOCAL.equals(Config.locale)){
} else if (!SELECTED_LOCAL.equals(Config.locale)) {
manager.resetFile("lang"+File.separator+"localization_"+Config.locale +".yml");
}
@ -65,13 +66,24 @@ public class Localization {
new LocalizationString( ChatColor.translateAlternateColorCodes('&', manager.getString("Localization."+key) ) )
);
}
for(String key : manager.getDefaultConfigurationSection("Localization").getKeys(false)) {
DEFAULT_LOCAL.put(
key,
new LocalizationString( ChatColor.translateAlternateColorCodes('&', manager.getString("Localization."+key) ) )
);
}
}
public static LocalizationString message(String key) {
LocalizationString temp = LOCAL.get(key);
if(temp == null) {
LocalizationString message = LOCAL.get(key);
if (message == null) {
LocalizationString defaultMessage = DEFAULT_LOCAL.get(key);
if(defaultMessage == null) {
return new LocalizationString(ChatColor.RED + "" + ChatColor.ITALIC + key + " is not found in localization.yml. This is a plugin issue, please report it.");
}
return new LocalizationString(temp.toString());
return new LocalizationString(defaultMessage.toString());
}
return new LocalizationString(message.toString());
}
}

View file

@ -21,70 +21,95 @@ package net.tylermurphy.hideAndSeek.database;
import com.google.common.io.ByteStreams;
import net.tylermurphy.hideAndSeek.Main;
import org.sqlite.SQLiteConfig;
import sun.font.ScriptRun;
import net.tylermurphy.hideAndSeek.database.connections.DatabaseConnection;
import net.tylermurphy.hideAndSeek.database.connections.MySQLConnection;
import net.tylermurphy.hideAndSeek.database.connections.SQLiteConnection;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Config.databaseType;
public class Database {
private static final File databaseFile = new File(Main.data, "database.db");
private final GameDataTable playerInfo;
private final NameDataTable nameInfo;
private final DatabaseConnection connection;
public static PlayerInfoTable playerInfo;
private static SQLiteConfig config;
public Database(){
protected static Connection connect() {
if(databaseType.equals("SQLITE")) {
connection = new SQLiteConnection();
} else {
connection = new MySQLConnection();
}
playerInfo = new GameDataTable(this);
nameInfo = new NameDataTable(this);
LegacyTable legacyTable = new LegacyTable(this);
if(legacyTable.exists()){
if(legacyTable.copyData()){
if(!legacyTable.drop()){
Main.getInstance().getLogger().severe("Failed to drop old legacy table: player_info. Some data may be duplicated!");
}
}
}
}
public GameDataTable getGameData(){
return playerInfo;
}
public NameDataTable getNameData() { return nameInfo; }
protected Connection connect() {
Connection conn = null;
try {
String url = "jdbc:sqlite:"+databaseFile;
conn = DriverManager.getConnection(url, config.toProperties());
conn = connection.connect();
} catch (SQLException e) {
Main.plugin.getLogger().severe(e.getMessage());
Main.getInstance().getLogger().severe(e.getMessage());
e.printStackTrace();
}
return conn;
}
protected static InputStream convertUniqueId(UUID uuid) {
protected byte[] encodeUUID(UUID uuid) {
try {
byte[] bytes = new byte[16];
ByteBuffer.wrap(bytes)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
return new ByteArrayInputStream(bytes);
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 static UUID convertBinaryStream(InputStream stream) {
protected UUID decodeUUID(byte[] bytes) {
InputStream is = new ByteArrayInputStream(bytes);
ByteBuffer buffer = ByteBuffer.allocate(16);
try {
buffer.put(ByteStreams.toByteArray(stream));
buffer.put(ByteStreams.toByteArray(is));
buffer.flip();
return new UUID(buffer.getLong(), buffer.getLong());
} catch (IOException ignored) {}
} catch (IOException e) {
Main.getInstance().getLogger().severe("IO Error: " + e.getMessage());
}
return null;
}
public static void init(){
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Main.plugin.getLogger().severe(e.getMessage());
throw new RuntimeException(e.getMessage());
}
config = new SQLiteConfig();
config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL);
config.setTempStore(SQLiteConfig.TempStore.MEMORY);
playerInfo = new PlayerInfoTable();
}
}

View file

@ -0,0 +1,219 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021-2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.database.util.PlayerInfo;
import net.tylermurphy.hideAndSeek.game.Board;
import net.tylermurphy.hideAndSeek.game.util.WinType;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import java.util.*;
public class GameDataTable {
private final Map<UUID, PlayerInfo> CACHE = new HashMap<>();
private final Database database;
protected GameDataTable(Database database) {
String sql = "CREATE TABLE IF NOT EXISTS hs_data (\n"
+ " uuid BINARY(16) PRIMARY KEY,\n"
+ " hider_wins int NOT NULL,\n"
+ " seeker_wins int NOT NULL,\n"
+ " hider_games int NOT NULL,\n"
+ " seeker_games int NOT NULL,\n"
+ " hider_kills int NOT NULL,\n"
+ " seeker_kills int NOT NULL,\n"
+ " hider_deaths int NOT NULL,\n"
+ " seeker_deaths int NOT NULL\n"
+ ");";
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
this.database = database;
}
@Nullable
public PlayerInfo getInfo(@Nullable UUID uuid) {
if (uuid == null) return null;
if(CACHE.containsKey(uuid)) return CACHE.get(uuid);
String sql = "SELECT * FROM hs_data WHERE uuid = ?;";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setBytes(1, database.encodeUUID(uuid));
ResultSet rs = statement.executeQuery();
if (rs.next()) {
PlayerInfo info = new PlayerInfo(
uuid,
rs.getInt("hider_wins"),
rs.getInt("seeker_wins"),
rs.getInt("hider_games"),
rs.getInt("seeker_games"),
rs.getInt("hider_kills"),
rs.getInt("seeker_kills"),
rs.getInt("hider_deaths"),
rs.getInt("seeker_deaths")
);
rs.close();
connection.close();
CACHE.put(uuid, info);
return info;
}
rs.close();
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
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)) {
statement.setInt(1, place-1);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
UUID uuid = database.decodeUUID(rs.getBytes("uuid"));
PlayerInfo info = new PlayerInfo(
uuid,
rs.getInt("hider_wins"),
rs.getInt("seeker_wins"),
rs.getInt("hider_games"),
rs.getInt("seeker_games"),
rs.getInt("hider_kills"),
rs.getInt("seeker_kills"),
rs.getInt("hider_deaths"),
rs.getInt("seeker_deaths")
);
rs.close();
connection.close();
CACHE.put(uuid, info);
return info;
}
rs.close();
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
return null;
}
@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)) {
statement.setInt(1, (page-1)*10);
ResultSet rs = statement.executeQuery();
List<PlayerInfo> infoList = new ArrayList<>();
while(rs.next()) {
PlayerInfo info = new PlayerInfo(
database.decodeUUID(rs.getBytes("uuid")),
rs.getInt("hider_wins"),
rs.getInt("seeker_wins"),
rs.getInt("hider_games"),
rs.getInt("seeker_games"),
rs.getInt("hider_kills"),
rs.getInt("seeker_kills"),
rs.getInt("hider_deaths"),
rs.getInt("seeker_deaths")
);
infoList.add(info);
}
rs.close();
connection.close();
return infoList;
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
return null;
}
@Nullable
public Integer getRanking(String order, UUID uuid) {
String sql = "SELECT count(*) AS total FROM hs_data WHERE "+order+" >= (SELECT "+order+" FROM hs_data WHERE uuid = ?) AND "+order+" > 0;";
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.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
return null;
}
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) {
PlayerInfo info = getInfo(uuid);
if(info == null){
info = new PlayerInfo(uuid, 0, 0, 0, 0, 0, 0, 0, 0);
}
updateInfo(
database.encodeUUID(info.getUniqueId()),
info.getHiderWins() + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0),
info.getSeekerWins() + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0),
info.getHiderGames() + (board.isHider(uuid) || (board.isSeeker(uuid) && !board.getFirstSeeker().getUniqueId().equals(uuid)) ? 1 : 0),
info.getSeekerGames() + (board.getFirstSeeker().getUniqueId().equals(uuid) ? 1 : 0),
info.getHiderKills() + hider_kills.getOrDefault(uuid.toString(), 0),
info.getSeekerKills() + seeker_kills.getOrDefault(uuid.toString(), 0),
info.getHiderDeaths() + hider_deaths.getOrDefault(uuid.toString(), 0),
info.getSeekerDeaths() + seeker_deaths.getOrDefault(uuid.toString(), 0)
);
}
}
protected boolean updateInfo(byte[] uuid, int hider_wins, int seeker_wins, int hider_games, int seeker_games, int hider_kills, int seeker_kills, int hider_deaths, int seeker_deaths){
boolean success;
String sql = "INSERT OR REPLACE INTO hs_data (uuid, hider_wins, seeker_wins, hider_games, seeker_games, hider_kills, seeker_kills, hider_deaths, seeker_deaths) VALUES (?,?,?,?,?,?,?,?,?)";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setBytes(1, uuid);
statement.setInt(2, hider_wins);
statement.setInt(3, seeker_wins);
statement.setInt(4, hider_games);
statement.setInt(5, seeker_games);
statement.setInt(6, hider_kills);
statement.setInt(7, seeker_kills);
statement.setInt(8, hider_deaths);
statement.setInt(9, seeker_deaths);
statement.execute();
statement.close();
success = true;
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
success = false;
} finally {
CACHE.remove(uuid);
}
return success;
}
}

View file

@ -0,0 +1,104 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.database.util.LegacyPlayerInfo;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class LegacyTable {
private final Database database;
private final boolean exists;
protected LegacyTable(Database database) {
String sql = "SELECT * FROM player_info LIMIT 1;";
boolean check;
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql);
check = resultSet.next();
} catch (SQLException e) {
check = false;
}
this.exists = check;
this.database = database;
}
public boolean exists(){
return exists;
}
public boolean copyData(){
String sql = "SELECT * FROM player_info;";
List<LegacyPlayerInfo> legacyPlayerInfoList = new ArrayList<>();
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
legacyPlayerInfoList.add(new LegacyPlayerInfo(
resultSet.getBytes("uuid"),
resultSet.getInt("wins"),
resultSet.getInt("hider_wins"),
resultSet.getInt("seeker_wins"),
resultSet.getInt("games_played")
));
}
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
for(LegacyPlayerInfo legacyInfo : legacyPlayerInfoList){
database.getGameData().updateInfo(
legacyInfo.getUniqueId(),
legacyInfo.getHiderWins(),
legacyInfo.getSeekerWins(),
legacyInfo.getGamesPlayer() - legacyInfo.getSeekerWins(),
legacyInfo.getSeekerWins(),
0,
0,
0,
0
);
}
return true;
}
public boolean drop(){
String sql = "DROP table player_info";
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
statement.execute(sql);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}

View file

@ -0,0 +1,112 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.Nullable;
import java.lang.management.BufferPoolMXBean;
import java.sql.*;
import java.util.UUID;
public class NameDataTable {
private final Database database;
protected NameDataTable(Database database) {
String sql = "CREATE TABLE IF NOT EXISTS hs_names (\n"
+ " uuid BINARY(16) NOT NULL,\n"
+ " name VARCHAR(48) NOT NULL,\n"
+ " PRIMARY KEY (uuid,name)\n"
+ ");";
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
this.database = database;
}
@Nullable
public String getName(UUID uuid) {
String sql = "SELECT * FROM hs_names WHERE uuid = ?;";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setBytes(1, database.encodeUUID(uuid));
ResultSet rs = statement.executeQuery();
if (rs.next()) {
return rs.getString("name");
}
rs.close();
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
OfflinePlayer retry = Bukkit.getOfflinePlayer(uuid);
if(retry != null){
this.update(uuid, retry.getName());
return retry.getName();
}
return null;
}
@Nullable
public UUID getUUID(String name) {
String sql = "SELECT * FROM hs_names WHERE name = ?;";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, name);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
return database.decodeUUID(rs.getBytes("uuid"));
}
rs.close();
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
}
OfflinePlayer retry = Bukkit.getOfflinePlayer(name);
if(retry != null){
this.update(retry.getUniqueId(), name);
return retry.getUniqueId();
}
return null;
}
public boolean update(UUID uuid, String name){
String sql = "INSERT OR REPLACE INTO hs_names (uuid, name) VALUES (?,?)";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setBytes(1, database.encodeUUID(uuid));
statement.setString(2, name);
statement.execute();
statement.close();
return true;
} catch (SQLException e) {
Main.getInstance().getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
return false;
}
}
}

View file

@ -1,136 +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.database;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.configuration.Config;
import net.tylermurphy.hideAndSeek.util.WinType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class PlayerInfoTable {
protected PlayerInfoTable(){
String sql = "CREATE TABLE IF NOT EXISTS player_info (\n"
+ " uuid BINARY(16) PRIMARY KEY,\n"
+ " wins int NOT NULL,\n"
+ " seeker_wins int NOT NULL,\n"
+ " hider_wins int NOT NULL,\n"
+ " games_played int NOT NULL\n"
+ ");";
try(Connection connection = Database.connect(); Statement statement = connection.createStatement()){
statement.executeUpdate(sql);
} catch (SQLException e){
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage());
}
}
public PlayerInfo getInfo(UUID uuid){
String sql = "SELECT * FROM player_info WHERE uuid = ?;";
try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){
InputStream is = Database.convertUniqueId(uuid);
byte[] bytes = new byte[is.available()];
if(is.read(bytes) == -1){
throw new IOException("Failed to read bytes from input stream");
}
statement.setBytes(1, bytes);
ResultSet rs = statement.executeQuery();
if(rs.next()){
rs.close();
connection.close();
return new PlayerInfo(
uuid,
rs.getInt("wins"),
rs.getInt("seeker_wins"),
rs.getInt("hider_wins"),
rs.getInt("games_played")
);
}
rs.close();
} catch (SQLException e){
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage());
} catch (IOException e) {
Main.plugin.getLogger().severe("IO Error: " + e.getMessage());
e.printStackTrace();
}
return new PlayerInfo(uuid, 0, 0, 0, 0);
}
public List<PlayerInfo> getInfoPage(int page){
String sql = "SELECT * FROM player_info ORDER BY wins DESC LIMIT 10 OFFSET ?;";
try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){
statement.setInt(1, (page-1)*10);
ResultSet rs = statement.executeQuery();
List<PlayerInfo> infoList = new ArrayList<>();
while(rs.next()){
PlayerInfo info = new PlayerInfo(
Database.convertBinaryStream(new ByteArrayInputStream(rs.getBytes("uuid"))),
rs.getInt("wins"),
rs.getInt("seeker_wins"),
rs.getInt("hider_wins"),
rs.getInt("games_played")
);
infoList.add(info);
}
rs.close();
connection.close();
return infoList;
} catch (SQLException e){
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage());
}
return null;
}
public void addWins(List<UUID> uuids, List<UUID> winners, WinType type){
for(UUID uuid : uuids){
String sql = "INSERT OR REPLACE INTO player_info (uuid, wins, seeker_wins, hider_wins, games_played) VALUES (?,?,?,?,?)";
PlayerInfo info = getInfo(uuid);
try(Connection connection = Database.connect(); PreparedStatement statement = connection.prepareStatement(sql)){
InputStream is = Database.convertUniqueId(uuid);
byte[] bytes = new byte[is.available()];
if(is.read(bytes) == -1){
throw new IOException("Failed to read bytes from input stream");
}
statement.setBytes(1, bytes);
statement.setInt(2, info.wins + (winners.contains(uuid) ? 1 : 0));
statement.setInt(3, info.seeker_wins + (winners.contains(uuid) && type == WinType.SEEKER_WIN ? 1 : 0));
statement.setInt(4, info.hider_wins + (winners.contains(uuid) && type == WinType.HIDER_WIN ? 1 : 0));
statement.setInt(5, info.games_played + 1);
statement.execute();
} catch (SQLException e){
Main.plugin.getLogger().severe("SQL Error: " + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
Main.plugin.getLogger().severe("IO Error: " + e.getMessage());
e.printStackTrace();
}
}
}
}

View file

@ -1,7 +1,7 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021 Tyler Murphy.
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -17,21 +17,13 @@
*
*/
package net.tylermurphy.hideAndSeek.database;
package net.tylermurphy.hideAndSeek.database.connections;
import java.util.UUID;
import java.sql.Connection;
import java.sql.SQLException;
public class PlayerInfo {
public interface DatabaseConnection {
public UUID uuid;
public int wins, hider_wins, seeker_wins, games_played;
public PlayerInfo(UUID uuid, int wins, int hider_wins, int seeker_wins, int games_played){
this.uuid = uuid;
this.wins = wins;
this.hider_wins = hider_wins;
this.seeker_wins = seeker_wins;
this.games_played = games_played;
}
Connection connect() throws SQLException;
}

View file

@ -0,0 +1,57 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database.connections;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class MySQLConnection implements DatabaseConnection {
private final HikariDataSource ds;
public MySQLConnection(){
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mariadb://"+databaseHost+":"+databasePort+"/"+databaseName);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("user", databaseUser);
config.addDataSourceProperty("password",databasePass);
config.addDataSourceProperty("autoCommit", "true");
config.setAutoCommit(true);
config.setMaximumPoolSize(20);
ds = new HikariDataSource(config);
}
@Override
public Connection connect() throws SQLException {
return ds.getConnection();
}
}

View file

@ -0,0 +1,64 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database.connections;
import net.tylermurphy.hideAndSeek.Main;
import org.sqlite.SQLiteConfig;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteConnection implements DatabaseConnection {
private final File databaseFile;
private final SQLiteConfig config;
public SQLiteConnection(){
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Main.getInstance().getLogger().severe(e.getMessage());
throw new RuntimeException(e.getMessage());
}
databaseFile = new File(Main.getInstance().getDataFolder(), "database.db");
config = new SQLiteConfig();
config.setSynchronous(SQLiteConfig.SynchronousMode.NORMAL);
config.setTempStore(SQLiteConfig.TempStore.MEMORY);
}
@Override
public Connection connect() {
Connection conn = null;
try {
String url = "jdbc:sqlite:"+databaseFile;
conn = DriverManager.getConnection(url, config.toProperties());
} catch (SQLException e) {
Main.getInstance().getLogger().severe(e.getMessage());
e.printStackTrace();
}
return conn;
}
}

View file

@ -0,0 +1,56 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021-2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database.util;
import java.util.UUID;
public class LegacyPlayerInfo {
private final byte[] uniqueId;
private final int totalWins;
private final int hiderWins;
private final int seekerWins;
private final int gamesPlayed;
public LegacyPlayerInfo(byte[] uniqueId, int totalWins, int hiderWins, int seekerWins, int gamesPlayed) {
this.uniqueId = uniqueId;
this.totalWins = totalWins;
this.hiderWins = hiderWins;
this.seekerWins = seekerWins;
this.gamesPlayed = gamesPlayed;
}
public byte[] getUniqueId() {
return uniqueId;
}
public int getTotalWins() { return totalWins; }
public int getHiderWins() {
return hiderWins;
}
public int getSeekerWins() {
return seekerWins;
}
public int getGamesPlayer() { return gamesPlayed; }
}

View file

@ -0,0 +1,84 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2021-2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.database.util;
import java.util.UUID;
public class PlayerInfo {
private final UUID uniqueId;
private final int hiderWins;
private final int seekerWins;
private final int hiderGames;
private final int seekerGames;
private final int hiderKills;
private final int seekerKills;
private final int hiderDeaths;
private final int seekerDeaths;
public PlayerInfo(UUID uniqueId, int hiderWins, int seekerWins, int hiderGames, int seekerGames, int hiderKills, int seekerKills, int hiderDeaths, int seekerDeaths) {
this.uniqueId = uniqueId;
this.hiderWins = hiderWins;
this.seekerWins = seekerWins;
this.hiderGames = hiderGames;
this.seekerGames = seekerGames;
this.hiderKills = hiderKills;
this.seekerKills = seekerKills;
this.hiderDeaths = hiderDeaths;
this.seekerDeaths = seekerDeaths;
}
public UUID getUniqueId() {
return uniqueId;
}
public int getHiderWins() {
return hiderWins;
}
public int getSeekerWins() {
return seekerWins;
}
public int getHiderGames() {
return hiderGames;
}
public int getSeekerGames() {
return seekerGames;
}
public int getHiderKills() {
return hiderKills;
}
public int getSeekerKills() {
return seekerKills;
}
public int getHiderDeaths() {
return hiderDeaths;
}
public int getSeekerDeaths() {
return seekerDeaths;
}
}

View file

@ -19,148 +19,205 @@
package net.tylermurphy.hideAndSeek.game;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
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 org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.*;
import java.util.*;
import java.util.stream.Collectors;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.util.Version;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
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 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 isPlayer(Player player) {
public boolean contains(Player player) {
return playerList.containsKey(player.getUniqueId().toString());
}
public static boolean isPlayer(CommandSender sender) {
return playerList.containsKey(Bukkit.getPlayer(sender.getName()).getUniqueId().toString());
}
public static boolean isHider(Player player) {
public boolean isHider(Player player) {
return Hider.contains(player.getUniqueId().toString());
}
public static boolean isSeeker(Player player) {
public boolean isHider(UUID uuid) {
return Hider.contains(uuid.toString());
}
public boolean isSeeker(Player player) {
return Seeker.contains(player.getUniqueId().toString());
}
public static boolean isSpectator(Player player) {
public boolean isSeeker(UUID uuid) {
return Seeker.contains(uuid.toString());
}
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(){
return Hider.stream().map(playerList::get).collect(Collectors.toList());
public List<Player> getHiders() {
return Hider.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList());
}
public static List<Player> getSeekers(){
return Seeker.stream().map(playerList::get).collect(Collectors.toList());
public List<Player> getSeekers() {
return Seeker.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList());
}
public static Player getFirstSeeker(){
public Player getFirstSeeker() {
return playerList.get(Seeker.get(0));
}
public static List<Player> getSpectators(){
return Spectator.stream().map(playerList::get).collect(Collectors.toList());
public List<Player> getSpectators() {
return Spectator.stream().filter(Objects::nonNull).map(playerList::get).collect(Collectors.toList());
}
public static List<Player> getPlayers(){
return new ArrayList<>(playerList.values());
public List<Player> getPlayers() {
return playerList.values().stream().filter(Objects::nonNull).collect(Collectors.toList());
}
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) {
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;
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();
hider_kills.clear();
seeker_kills.clear();
hider_deaths.clear();
seeker_deaths.clear();
}
public static void createLobbyBoard(Player player) {
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);
} else {
hider_kills.put(uuid.toString(), 1);
}
} else if (Seeker.contains(uuid.toString())) {
if (seeker_kills.containsKey(uuid.toString())) {
seeker_kills.put(uuid.toString(), seeker_kills.get(uuid.toString())+1);
} else {
seeker_kills.put(uuid.toString(), 1);
}
}
}
public void addDeath(UUID uuid) {
if (Hider.contains(uuid.toString())) {
if (hider_deaths.containsKey(uuid.toString())) {
hider_deaths.put(uuid.toString(), hider_deaths.get(uuid.toString())+1);
} else {
hider_deaths.put(uuid.toString(), 1);
}
} else if (Seeker.contains(uuid.toString())) {
if (seeker_deaths.containsKey(uuid.toString())) {
seeker_deaths.put(uuid.toString(), seeker_deaths.get(uuid.toString())+1);
} else {
seeker_deaths.put(uuid.toString(), 1);
}
}
}
public Map<String, Integer> getHiderKills() {
return new HashMap<>(hider_kills);
}
public Map<String, Integer> getSeekerKills() {
return new HashMap<>(seeker_kills);
}
public Map<String, Integer> getHiderDeaths() {
return new HashMap<>(hider_deaths);
}
public Map<String, Integer> getSeekerDeaths() {
return new HashMap<>(seeker_deaths);
}
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, "&l&eHIDE AND SEEK");
if (recreate || board == null) {
board = new CustomBoard(player, LOBBY_TITLE);
board.updateTeams();
}
int i=0;
for(String line : LOBBY_CONTENTS){
if(line.equalsIgnoreCase("")){
for(String line : LOBBY_CONTENTS) {
if (line.equalsIgnoreCase("")) {
board.addBlank();
} else if(line.contains("{COUNTDOWN}")){
if(!lobbyCountdownEnabled){
} else if (line.contains("{COUNTDOWN}")) {
if (!lobbyCountdownEnabled) {
board.setLine(String.valueOf(i), line.replace("{COUNTDOWN}", COUNTDOWN_ADMINSTART));
} else if(Game.countdownTime == -1){
} else if (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}")){
} else if (line.contains("{COUNT}")) {
board.setLine(String.valueOf(i), line.replace("{COUNT}", getPlayers().size()+""));
} else if(line.contains("{SEEKER%}")){
} else if (line.contains("{SEEKER%}")) {
board.setLine(String.valueOf(i), line.replace("{SEEKER%}", getSeekerPercent()+""));
} else if(line.contains("{HIDER%}")){
} else if (line.contains("{HIDER%}")) {
board.setLine(String.valueOf(i), line.replace("{HIDER%}", getHiderPercent()+""));
} else {
board.setLine(String.valueOf(i), line);
@ -171,58 +228,65 @@ 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) {
if (recreate || board == null) {
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("")){
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";
if (line.contains("{TIME}")) {
String value = timeLeft/60 + "m" + timeLeft%60 + "s";
board.setLine(String.valueOf(i), line.replace("{TIME}", value));
} else if(line.contains("{TEAM}")) {
} else if (line.contains("{TEAM}")) {
String value = getTeam(player);
board.setLine(String.valueOf(i), line.replace("{TEAM}", value));
} else if(line.contains("{BORDER}")) {
if(!worldborderEnabled) continue;
if(Game.worldBorder == null || Game.status == Status.STARTING){
} else if (line.contains("{BORDER}")) {
if (!worldBorderEnabled) continue;
if (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) {
} else if (line.contains("{TAUNT}")) {
if (!tauntEnabled) continue;
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){
} 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()) {
} else if (line.contains("{GLOW}")) {
if (!glowEnabled) continue;
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));
}
} else if(line.contains("{#SEEKER}")) {
} else if (line.contains("{#SEEKER}")) {
board.setLine(String.valueOf(i), line.replace("{#SEEKER}", getSeekers().size()+""));
} else if(line.contains("{#HIDER}")) {
} else if (line.contains("{#HIDER}")) {
board.setLine(String.valueOf(i), line.replace("{#HIDER}", getHiders().size()+""));
} else {
board.setLine(String.valueOf(i), line);
@ -234,50 +298,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() {
if(playerList.values().size() < 2)
private String getSeekerPercent() {
if (playerList.values().size() < 2)
return " --";
else
return " "+(int)(100*(1.0/playerList.size()));
}
private static String getHiderPercent() {
if(playerList.size() < 2)
private String getHiderPercent() {
if (playerList.size() < 2)
return " --";
else
return " "+(int)(100-100*(1.0/playerList.size()));
}
private static String getTeam(Player player) {
if(isHider(player)) return ChatColor.GOLD + "HIDER";
else if(isSeeker(player)) return ChatColor.RED + "SEEKER";
else if(isSpectator(player)) return ChatColor.GRAY + "SPECTATOR";
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();
@ -296,13 +360,13 @@ class CustomBoard {
private int blanks;
private boolean displayed;
public CustomBoard(Player player, String title){
public CustomBoard(Player player, String title) {
ScoreboardManager manager = Bukkit.getScoreboardManager();
assert manager != null;
this.board = manager.getNewScoreboard();
this.LINES = new HashMap<>();
this.player = player;
if(Version.atLeast("1.13")){
if (Main.getInstance().supports(13)) {
this.obj = board.registerNewObjective(
"Scoreboard", "dummy", ChatColor.translateAlternateColorCodes('&', title));
} else {
@ -315,22 +379,22 @@ class CustomBoard {
}
public void updateTeams() {
try{ board.registerNewTeam("Hider"); } catch (Exception ignored){}
try{ board.registerNewTeam("Seeker"); } catch (Exception ignored){}
try{ board.registerNewTeam("Hider"); } catch (Exception ignored) {}
try{ board.registerNewTeam("Seeker"); } catch (Exception ignored) {}
Team hiderTeam = board.getTeam("Hider");
assert hiderTeam != null;
for(String entry : hiderTeam.getEntries())
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) {
if (Main.getInstance().supports(9)) {
if (nameTagsVisible) {
hiderTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OWN_TEAM);
seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.FOR_OTHER_TEAMS);
} else {
@ -338,7 +402,7 @@ class CustomBoard {
seekerTeam.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.NEVER);
}
} else {
if(nametagsVisible) {
if (nameTagsVisible) {
hiderTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OTHER_TEAMS);
seekerTeam.setNameTagVisibility(NameTagVisibility.HIDE_FOR_OWN_TEAM);
} else {
@ -346,7 +410,7 @@ class CustomBoard {
seekerTeam.setNameTagVisibility(NameTagVisibility.NEVER);
}
}
if(Version.atLeast("1.12")){
if (Main.getInstance().supports(12)) {
hiderTeam.setColor(ChatColor.GOLD);
seekerTeam.setColor(ChatColor.RED);
} else {
@ -355,23 +419,23 @@ class CustomBoard {
}
}
public void setLine(String key, String message){
public void setLine(String key, String message) {
Line line = LINES.get(key);
if(line == null)
if (line == null)
addLine(key, ChatColor.translateAlternateColorCodes('&',message));
else
updateLine(key, ChatColor.translateAlternateColorCodes('&',message));
}
private void addLine(String key, String message){
private void addLine(String key, String message) {
Score score = obj.getScore(message);
score.setScore(LINES.values().size()+1);
Line line = new Line(LINES.values().size()+1, message);
LINES.put(key, line);
}
public void addBlank(){
if(displayed) return;
public void addBlank() {
if (displayed) return;
StringBuilder temp = new StringBuilder();
for(int i = 0; i <= blanks; i ++)
temp.append(ChatColor.RESET);
@ -379,7 +443,7 @@ class CustomBoard {
addLine("blank"+blanks, temp.toString());
}
private void updateLine(String key, String message){
private void updateLine(String key, String message) {
Line line = LINES.get(key);
board.resetScores(line.getMessage());
line.setMessage(message);
@ -401,7 +465,7 @@ class Line {
private final int score;
private String message;
public Line(int score, String message){
public Line(int score, String message) {
this.score = score;
this.message = message;
}

View file

@ -1,337 +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.game;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.util.Version;
import org.bukkit.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeInstance;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.projectiles.ProjectileSource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
public class EventListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(PlayerJoinEvent event) {
Board.remove(event.getPlayer());
Game.removeItems(event.getPlayer());
if(Game.isNotSetup()) return;
if(autoJoin){
Game.join(event.getPlayer());
} else if(teleportToExit) {
if (event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld) || event.getPlayer().getWorld().getName().equals(lobbyWorld)) {
event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
event.getPlayer().setGameMode(GameMode.ADVENTURE);
}
} else {
if (event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld)) {
if(Game.status != Status.STANDBY){
Game.join(event.getPlayer());
} else {
event.getPlayer().teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ()));
event.getPlayer().setGameMode(GameMode.ADVENTURE);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
Board.remove(event.getPlayer());
if(Game.status == Status.STANDBY) {
Board.reloadLobbyBoards();
} else {
Board.reloadGameBoards();
}
for(PotionEffect effect : event.getPlayer().getActivePotionEffects()){
event.getPlayer().removePotionEffect(effect.getType());
}
Game.removeItems(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onKick(PlayerKickEvent event) {
Board.remove(event.getPlayer());
if(Game.status == Status.STANDBY) {
Board.reloadLobbyBoards();
} else {
Board.reloadGameBoards();
}
for(PotionEffect effect : event.getPlayer().getActivePotionEffects()){
event.getPlayer().removePotionEffect(effect.getType());
}
Game.removeItems(event.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event){
if(Board.isSeeker(event.getPlayer())){
event.setCancelled(true);
Board.getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage()));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onMove(PlayerMoveEvent event){
if(!event.getPlayer().getWorld().getName().equals("hideandseek_" + spawnWorld)) return;
if(event.getPlayer().hasPermission("hideandseek.leavebounds")) return;
if(event.getTo() == null || event.getTo().getWorld() == null) return;
if(!event.getTo().getWorld().getName().equals("hideandseek_" + spawnWorld)) return;
if(event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ){
event.setCancelled(true);
}
}
public static final Map<UUID, Location> temp_loc = new HashMap<>();
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent event){
Player player = event.getEntity();
if(!Board.isPlayer(player)) return;
event.setKeepInventory(true);
event.setDeathMessage("");
temp_loc.put(player.getUniqueId(), player.getLocation());
Main.plugin.getLogger().severe("Player "+player.getName() + " died when not supposed to. Attempting to roll back death.");
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(PlayerRespawnEvent event){
Player player = event.getPlayer();
if(!Board.isPlayer(player)) return;
if(temp_loc.containsKey(player.getUniqueId())){
player.teleport(temp_loc.get(player.getUniqueId()));
temp_loc.remove(player.getUniqueId());
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamage(EntityDamageEvent event) {
try {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (!Board.isPlayer(player)) {
if (event instanceof EntityDamageByEntityEvent) {
Entity damager = ((EntityDamageByEntityEvent) event).getDamager();
if (damager instanceof Player) {
if(Board.isPlayer(damager)){
event.setCancelled(true);
return;
}
}
}
return;
}
if (Game.status != Status.PLAYING) {
event.setCancelled(true);
return;
}
Player attacker = null;
if (event instanceof EntityDamageByEntityEvent) {
Entity damager = ((EntityDamageByEntityEvent) event).getDamager();
if (damager instanceof Player) {
attacker = (Player) damager;
if (!Board.isPlayer(attacker)) event.setCancelled(true);
if (Board.onSameTeam(player, attacker)) event.setCancelled(true);
if (Board.isSpectator(player)) event.setCancelled(true);
} else if(damager instanceof Arrow){
ProjectileSource source = ((Arrow) damager).getShooter();
if(source instanceof Player){
attacker = (Player) source;
if (!Board.isPlayer(attacker)) event.setCancelled(true);
if (Board.onSameTeam(player, attacker)) event.setCancelled(true);
if (Board.isSpectator(player)) event.setCancelled(true);
}
}
}
if(event.isCancelled()) return;
if (player.getHealth() - event.getFinalDamage() < 0.5 || !pvpEnabled) {
if (spawnPosition == null) return;
event.setCancelled(true);
if(Version.atLeast("1.9")) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
} else {
player.setHealth(player.getMaxHealth());
}
player.teleport(new Location(Bukkit.getWorld("hideandseek_" + spawnWorld), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ()));
if(Version.atLeast("1.9")){
XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1);
} else {
XSound.ENTITY_PLAYER_HURT.play(player, 1, 1);
}
if (Board.isSeeker(player)) {
Game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString());
}
if (Board.isHider(player)) {
if (attacker == null) {
Game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString());
} else {
Game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString());
}
Board.addSeeker(player);
}
Game.resetPlayer(player);
Board.reloadBoardTeams();
}
}
} catch (Exception e){
Main.plugin.getLogger().severe("Entity Damage Event Error: " + e.getMessage());
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onProjectile(ProjectileLaunchEvent event) {
if(Game.status != Status.PLAYING) return;
if(event.getEntity() instanceof Snowball) {
if(!glowEnabled) return;
Snowball snowball = (Snowball) event.getEntity();
if(snowball.getShooter() instanceof Player) {
Player player = (Player) snowball.getShooter();
if(Board.isHider(player)) {
Game.glow.onProjectile();
snowball.remove();
assert XMaterial.SNOWBALL.parseMaterial() != null;
player.getInventory().remove(XMaterial.SNOWBALL.parseMaterial());
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if(event.getEntity() instanceof Player) {
if(!Board.isPlayer((Player) event.getEntity())) return;
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRegainHealth(EntityRegainHealthEvent event) {
if(event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) {
if(event.getEntity() instanceof Player) {
if(!Board.isPlayer((Player) event.getEntity())) return;
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String message = event.getMessage();
String[] array = message.split(" ");
String[] temp = array[0].split(":");
for(String handle : blockedCommands){
if(
array[0].substring(1).equalsIgnoreCase(handle) && Board.isPlayer(player) ||
temp[temp.length-1].equalsIgnoreCase(handle) && Board.isPlayer(player)
) {
if(Game.status == Status.STANDBY) return;
player.sendMessage(errorPrefix + message("BLOCKED_COMMAND"));
event.setCancelled(true);
break;
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if(!Board.isPlayer(event.getPlayer())) return;
if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null && blockedInteracts.contains(event.getClickedBlock().getType().name())){
event.setCancelled(true);
return;
}
if(Game.status != Status.STANDBY) return;
ItemStack temp = event.getItem();
if(temp == null) return;
if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyLeaveItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyLeaveItem.getType()) {
event.setCancelled(true);
Game.leave(event.getPlayer());
}
if (temp.getItemMeta().getDisplayName().equalsIgnoreCase(lobbyStartItem.getItemMeta().getDisplayName()) && temp.getType() == lobbyStartItem.getType() && event.getPlayer().hasPermission("hideandseek.start")) {
event.setCancelled(true);
if (Game.isNotSetup()) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP"));
return;
}
if (Game.status != Status.STANDBY) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
if (Board.size() < minPlayers) {
event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers));
return;
}
Game.start();
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
if(event.getWhoClicked() instanceof Player){
Player player = (Player) event.getWhoClicked();
if(Board.isPlayer(player) && Game.status == Status.STANDBY){
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemDrop(PlayerDropItemEvent event)
{
if(Board.isPlayer(event.getPlayer()) && Game.status == Status.STANDBY){
event.setCancelled(true);
}
}
}

View file

@ -19,586 +19,342 @@
package net.tylermurphy.hideAndSeek.game;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.messages.ActionBar;
import com.cryptomorin.xseries.messages.Titles;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.configuration.Items;
import net.tylermurphy.hideAndSeek.database.Database;
import net.tylermurphy.hideAndSeek.util.Status;
import net.tylermurphy.hideAndSeek.util.Version;
import net.tylermurphy.hideAndSeek.util.WinType;
import net.tylermurphy.hideAndSeek.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.listener.RespawnHandler;
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 net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.util.Packet;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
import static net.tylermurphy.hideAndSeek.game.Game.broadcastMessage;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
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;
static {
worldLoader = new WorldLoader(spawnWorld);
private final Board board;
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;
public Status getStatus(){
return status;
}
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);
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;
}
Player seeker = board.getPlayer(temp.getUniqueId());
start(seeker);
} catch (Exception e){
Main.getInstance().getLogger().warning("Failed to select random seeker.");
}
}
public static void start(Player seeker){
if(status == Status.STARTING || status == Status.PLAYING) return;
if(worldLoader.getWorld() != null) {
worldLoader.rollback();
} else {
worldLoader.loadMap();
}
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("hideandseek_"+spawnWorld), 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.RED + "" + ChatColor.BOLD + "SEEKER", ChatColor.WHITE + message("SEEKERS_SUBTITLE").toString());
}
for(Player player : Board.getHiders()) {
player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,1000000,5,false,false));
Titles.sendTitle(player, 10, 70, 20, ChatColor.GOLD + "" + ChatColor.BOLD + "HIDER", ChatColor.WHITE + message("HIDERS_SUBTITLE").toString());
}
if(tauntEnabled)
taunt = new Taunt();
if (glowEnabled)
glow = new Glow();
worldBorder = new Border();
worldBorder.resetWorldborder("hideandseek_"+spawnWorld);
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);
PlayerLoader.loadSeeker(seeker, getGameWorld());
board.getPlayers().forEach(player -> {
if(board.isSeeker(player)) return;
board.addHider(player);
PlayerLoader.loadHider(player, getGameWorld());
});
board.getPlayers().forEach(board::createGameBoard);
worldBorder.resetWorldBorder(getGameWorld());
if (gameLength > 0) gameTimer = gameLength;
status = Status.STARTING;
int temp = gameId;
broadcastMessage(messagePrefix + message("START_COUNTDOWN").addAmount(30));
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(20), gameId, 20 * 10);
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(10), gameId, 20 * 20);
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(5), gameId, 20 * 25);
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(3), gameId, 20 * 27);
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(2), gameId, 20 * 28);
sendDelayedMessage(messagePrefix + message("START_COUNTDOWN").addAmount(1), gameId, 20 * 29);
Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, () -> {
if(temp != gameId) return;
broadcastMessage(messagePrefix + message("START"));
for(Player player : Board.getPlayers()) resetPlayer(player);
status = Status.PLAYING;
}, 20 * 30);
startingTimer = 30;
}
public static void stop(WinType type){
if(status == Status.STANDBY) return;
tick = 0;
countdownTime = -1;
status = Status.STANDBY;
gameId++;
timeLeft = 0;
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, type);
} else if(type == WinType.SEEKER_WIN){
private void stop(WinType type) {
status = Status.ENDING;
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());
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, type);
winners.add(board.getFirstSeeker().getUniqueId());
Main.getInstance().getDatabase().getGameData().addWins(board, players, winners, board.getHiderKills(), board.getHiderDeaths(), board.getSeekerKills(), board.getSeekerDeaths(), type);
}
worldBorder.resetWorldborder("hideandseek_"+spawnWorld);
for(Player player : Board.getPlayers()) {
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);
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ()));
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);
}
}
}
EventListener.temp_loc.clear();
worldLoader.unloadMap();
Board.reloadLobbyBoards();
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), this::end, 5*20);
}
public static boolean isNotSetup() {
if(spawnPosition.getBlockX() == 0 && spawnPosition.getBlockY() == 0 && spawnPosition.getBlockZ() == 0) return true;
if(lobbyPosition.getBlockX() == 0 && lobbyPosition.getBlockY() == 0 && lobbyPosition.getBlockZ() == 0) return true;
if(exitPosition.getBlockX() == 0 && exitPosition.getBlockY() == 0 && exitPosition.getBlockZ() == 0) return true;
File destenation = new File(Main.root+File.separator+"hideandseek_"+spawnWorld);
if(!destenation.exists()) return true;
return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0;
}
public static void onTick() {
if(isNotSetup()) return;
if(status == Status.STANDBY) whileWaiting();
else if(status == Status.STARTING) whileStarting();
else if(status == Status.PLAYING) whilePlaying();
tick++;
}
public static void resetWorldborder(String worldName){
worldBorder = new Border();
worldBorder.resetWorldborder(worldName);
}
public static void broadcastMessage(String message) {
for(Player player : Board.getPlayers()) {
player.sendMessage(message);
}
}
public static void resetPlayer(Player player) {
player.getInventory().clear();
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
if (Board.isSeeker(player)) {
if(pvpEnabled)
for(ItemStack item : Items.SEEKER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.SEEKER_EFFECTS)
player.addPotionEffect(effect);
} else if (Board.isHider(player)) {
if(pvpEnabled)
for(ItemStack item : Items.HIDER_ITEMS)
player.getInventory().addItem(item);
for(PotionEffect effect : Items.HIDER_EFFECTS)
player.addPotionEffect(effect);
if(glowEnabled) {
assert XMaterial.SNOWBALL.parseMaterial() != null;
ItemStack snowball = new ItemStack(XMaterial.SNOWBALL.parseMaterial(), 1);
ItemMeta snowballMeta = snowball.getItemMeta();
assert snowballMeta != null;
snowballMeta.setDisplayName("Glow Powerup");
List<String> snowballLore = new ArrayList<>();
snowballLore.add("Throw to make all seekers glow");
snowballLore.add("Last 30s, all hiders can see it");
snowballLore.add("Time stacks on multi use");
snowballMeta.setLore(snowballLore);
snowball.setItemMeta(snowballMeta);
player.getInventory().addItem(snowball);
}
}
}
public static void join(Player player){
if(Game.status == Status.STANDBY) {
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);
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player));
else Game.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player));
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ()));
player.setGameMode(GameMode.ADVENTURE);
Board.createLobbyBoard(player);
Board.reloadLobbyBoards();
public void end() {
board.getPlayers().forEach(PlayerLoader::unloadPlayer);
worldBorder.resetWorldBorder(getGameWorld());
board.getPlayers().forEach(player -> {
if (leaveOnEnd) {
board.removeBoard(player);
board.remove(player);
handleBungeeLeave(player);
} else {
Board.addSpectator(player);
player.teleport(new Location(Bukkit.getWorld(lobbyWorld), lobbyPosition.getX(),lobbyPosition.getY(),lobbyPosition.getZ()));
board.createLobbyBoard(player);
board.addHider(player);
PlayerLoader.joinPlayer(player);
}
});
RespawnHandler.temp_loc.clear();
if (mapSaveEnabled) worldLoader.unloadMap();
board.reloadLobbyBoards();
status = Status.ENDED;
}
public void join(Player player) {
if (status != Status.STARTING && status != Status.PLAYING) {
PlayerLoader.joinPlayer(player);
board.addHider(player);
board.createLobbyBoard(player);
board.reloadLobbyBoards();
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player));
else broadcastMessage(messagePrefix + message("GAME_JOIN").addPlayer(player));
} else {
PlayerLoader.loadSpectator(player, getGameWorld());
board.addSpectator(player);
board.createGameBoard(player);
player.sendMessage(messagePrefix + message("GAME_JOIN_SPECTATOR"));
player.setGameMode(GameMode.SPECTATOR);
Board.createGameBoard(player);
player.teleport(new Location(Bukkit.getWorld("hideandseek_"+spawnWorld), spawnPosition.getX(),spawnPosition.getY(),spawnPosition.getZ()));
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){
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player));
else Game.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player));
Board.removeBoard(player);
Board.remove(player);
player.getInventory().clear();
if(Game.status == Status.STANDBY) {
Board.reloadLobbyBoards();
} else {
Board.reloadGameBoards();
Board.reloadBoardTeams();
public void leave(Player player) {
PlayerLoader.unloadPlayer(player);
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player));
else broadcastMessage(messagePrefix + message("GAME_LEAVE").addPlayer(player));
if (board.isHider(player) && status != Status.ENDING && status != Status.STANDBY) {
hiderLeft = true;
}
if(bungeeLeave) {
board.removeBoard(player);
board.remove(player);
if (status == Status.STANDBY) {
board.reloadLobbyBoards();
} else {
board.reloadGameBoards();
board.reloadBoardTeams();
}
handleBungeeLeave(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 removeItems(Player player){
for(ItemStack si : Items.SEEKER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if(si.isSimilar(i)) player.getInventory().remove(i);
for(ItemStack hi : Items.HIDER_ITEMS)
for(ItemStack i : player.getInventory().getContents())
if(hi.isSimilar(i)) player.getInventory().remove(i);
public void onTick() {
if (isNotSetup()) return;
if (status == Status.STANDBY) whileWaiting();
else if (status == Status.STARTING) whileStarting();
else if (status == Status.PLAYING) whilePlaying();
gameTick++;
}
private static void whileWaiting() {
if(lobbyCountdownEnabled){
if(lobbyMin <= Board.size()){
if(countdownTime == -1)
countdownTime = countdown;
if(Board.size() >= changeCountdown)
countdownTime = Math.min(countdownTime, 10);
if(tick % 20 == 0) {
countdownTime--;
Board.reloadLobbyBoards();
private void whileWaiting() {
if (!lobbyCountdownEnabled) return;
if (lobbyMin <= board.size()) {
if (lobbyTimer < 0)
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(){
private void whileStarting() {
if(gameTick % 20 == 0) {
if (startingTimer % 5 == 0 || startingTimer < 5) {
String message;
if (startingTimer == 0) {
message = message("START").toString();
status = Status.PLAYING;
board.getPlayers().forEach(player -> PlayerLoader.resetPlayer(player, board));
} else if (startingTimer == 1){
message = message("START_COUNTDOWN_LAST").addAmount(startingTimer).toString();
} else {
message = message("START_COUNTDOWN").addAmount(startingTimer).toString();
}
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 && startingTimer != 30) {
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){
} catch (Exception e) {
//Players in different worlds, NOT OK!!!
}
if(distance > temp) {
if (distance > temp) {
distance = temp;
}
}
if(seekerPing) switch(tick%10) {
if (seekerPing) switch(gameTick %10) {
case 0:
if(distance < seekerPingLevel1) XSound.BLOCK_NOTE_BLOCK_BASEDRUM.play(hider, .5f, 1f);
if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f);
if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingLeadingVolume, seekerPingPitch);
if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch);
break;
case 3:
if(distance < seekerPingLevel1) XSound.BLOCK_NOTE_BLOCK_BASEDRUM.play(hider, .3f, 1f);
if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f);
if (distance < seekerPingLevel1) heartbeatSound.play(hider, seekerPingVolume, seekerPingPitch);
if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch);
break;
case 6:
if(distance < seekerPingLevel3) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f);
if (distance < seekerPingLevel3) ringingSound.play(hider, seekerPingVolume, seekerPingPitch);
break;
case 9:
if(distance < seekerPingLevel2) XSound.BLOCK_NOTE_BLOCK_PLING.play(hider, .3f, 1f);
if (distance < seekerPingLevel2) ringingSound.play(hider, seekerPingVolume, seekerPingPitch);
break;
}
}
if(tick%20 == 0) {
if(gameLength > 0) {
Board.reloadGameBoards();
timeLeft--;
if (gameTick %20 == 0) {
if (gameLength > 0) {
board.reloadGameBoards();
gameTimer--;
}
if(worldborderEnabled) worldBorder.update();
if(tauntEnabled) taunt.update();
if (glowEnabled) glow.update();
if (worldBorderEnabled) worldBorder.update();
if (tauntEnabled) taunt.update();
if (glowEnabled || alwaysGlow) glow.update();
}
board.getSpectators().forEach(spectator -> spectator.setFlying(spectator.getAllowFlight()));
checkWinConditions();
}
private static void checkWinConditions(){
if(Board.sizeHider() < 1) {
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND"));
else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND"));
public void broadcastMessage(String message) {
for(Player player : board.getPlayers()) {
player.sendMessage(message);
}
}
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.getInstance().getWorldContainer() + File.separator + getGameWorld());
if (!destination.exists()) return true;
}
return saveMinX == 0 || saveMinZ == 0 || saveMaxX == 0 || saveMaxZ == 0;
}
public String getGameWorld() {
if (mapSaveEnabled) return "hideandseek_"+spawnWorld;
else return spawnWorld;
}
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);
} else {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND"));
else broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_HIDERS_FOUND"));
stop(WinType.SEEKER_WIN);
} else if(Board.sizeSeeker() < 1) {
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT"));
}
} else if (board.sizeSeeker() < 1) {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT"));
else broadcastMessage(abortPrefix + message("GAME_GAMEOVER_SEEKERS_QUIT"));
stop(WinType.NONE);
} else if(timeLeft < 1) {
if(announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME"));
else broadcastMessage(gameoverPrefix + message("GAME_GAMEOVER_TIME"));
} else if (gameTimer < 1) {
if (announceMessagesToNonPlayers) Bukkit.broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_TIME"));
else broadcastMessage(gameOverPrefix + message("GAME_GAMEOVER_TIME"));
stop(WinType.HIDER_WIN);
}
}
private static void sendDelayedMessage(String message, int gameId, int delay) {
Bukkit.getScheduler().runTaskLaterAsynchronously(Main.plugin, () -> {
if(gameId == Game.gameId)
broadcastMessage(message);
}, delay);
}
}
class Glow {
private int glowTime;
private boolean running;
public Glow() {
this.glowTime = 0;
}
public void onProjectile() {
if(glowStackable) glowTime += glowLength;
else glowTime = glowLength;
running = true;
}
private void sendPackets(){
for(Player hider : Board.getHiders())
for(Player seeker : Board.getSeekers())
Packet.setGlow(hider, seeker, true);
}
protected void update() {
if(running) {
sendPackets();
glowTime--;
glowTime = Math.max(glowTime, 0);
if (glowTime == 0) {
stopGlow();
}
}
}
private void stopGlow() {
running = false;
for(Player hider : Board.getHiders()) {
for (Player seeker : Board.getSeekers()) {
Packet.setGlow(hider, seeker, false);
}
}
}
public boolean isRunning() {
return running;
}
}
class Taunt {
private UUID tauntPlayer;
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("hideandseek_"+spawnWorld);
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,143 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.game;
import com.cryptomorin.xseries.messages.Titles;
import net.md_5.bungee.api.ChatColor;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.configuration.Items;
import 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 PlayerLoader {
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);
player.getInventory().setItem(flightToggleItemPosition, flightToggleItem);
player.getInventory().setItem(teleportItemPosition, teleportItem);
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){
if(board.isSpectator(player)) return;
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 (Main.getInstance().supports(9)) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
for(Player temp : Main.getInstance().getBoard().getPlayers()) {
Main.getInstance().getGame().getGlow().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.setFlying(false);
player.setAllowFlight(false);
player.setGameMode(GameMode.ADVENTURE);
player.getInventory().clear();
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
player.setFoodLevel(20);
if (Main.getInstance().supports(9)) {
AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);
if (attribute != null) player.setHealth(attribute.getValue());
} else {
player.setHealth(player.getMaxHealth());
}
}
}

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 decreaseWorldBorder();
}
delay--;
}
private void decreaseWorldBorder() {
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

@ -0,0 +1,85 @@
package net.tylermurphy.hideAndSeek.game.events;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
public class Glow {
private static final ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
private int glowTime;
private boolean running;
public Glow() {
this.glowTime = 0;
}
public void onProjectile() {
if (glowStackable) glowTime += glowLength;
else glowTime = glowLength;
running = true;
}
private void sendPackets() {
for (Player hider : Main.getInstance().getBoard().getHiders())
for (Player seeker : Main.getInstance().getBoard().getSeekers())
setGlow(hider, seeker, true);
}
public void update() {
if(alwaysGlow){
sendPackets();
return;
}
if (running) {
sendPackets();
glowTime--;
glowTime = Math.max(glowTime, 0);
if (glowTime == 0) {
stopGlow();
}
}
}
private void stopGlow() {
running = false;
for (Player hider : Main.getInstance().getBoard().getHiders()) {
for (Player seeker : Main.getInstance().getBoard().getSeekers()) {
setGlow(hider, seeker, false);
}
}
}
public boolean isRunning() {
return running;
}
public void setGlow(Player player, Player target, boolean glowing) {
PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, target.getEntityId());
WrappedDataWatcher watcher = new WrappedDataWatcher();
WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class);
watcher.setEntity(target);
if (glowing) {
watcher.setObject(0, serializer, (byte) (0x40));
} else {
watcher.setObject(0, serializer, (byte) (0x0));
}
packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects());
try {
protocolManager.sendServerPacket(player, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

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

@ -0,0 +1,36 @@
package net.tylermurphy.hideAndSeek.game.listener;
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;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import static net.tylermurphy.hideAndSeek.configuration.Config.blockedCommands;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class BlockedCommandHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String message = event.getMessage();
String[] array = message.split(" ");
String[] temp = array[0].split(":");
for(String handle : blockedCommands) {
if (
array[0].substring(1).equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player) ||
temp[temp.length-1].equalsIgnoreCase(handle) && Main.getInstance().getBoard().contains(player)
) {
if (Main.getInstance().getGame().getStatus() == Status.STANDBY) return;
player.sendMessage(errorPrefix + message("BLOCKED_COMMAND"));
event.setCancelled(true);
break;
}
}
}
}

View file

@ -0,0 +1,20 @@
package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event) {
if (Main.getInstance().getBoard().isSeeker(event.getPlayer())) {
event.setCancelled(true);
Main.getInstance().getBoard().getSpectators().forEach(spectator -> spectator.sendMessage(ChatColor.GRAY + "[SPECTATOR] " + event.getPlayer().getName() + ": " + event.getMessage()));
}
}
}

View file

@ -0,0 +1,118 @@
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.game.PlayerLoader;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.spawnPosition;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class DamageHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamage(EntityDamageEvent event) {
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
Player player = (Player) event.getEntity();
Player attacker = null;
// If no spawn position, we won't be able to manage their death :o
if (spawnPosition == null) { return; }
// If there is an attacker, find them
if (event instanceof EntityDamageByEntityEvent) {
if (((EntityDamageByEntityEvent) event).getDamager() instanceof Player)
attacker = (Player) ((EntityDamageByEntityEvent) event).getDamager();
else if (((EntityDamageByEntityEvent) event).getDamager() instanceof Projectile)
if (((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter() instanceof Player)
attacker = (Player) ((Projectile) ((EntityDamageByEntityEvent) event).getDamager()).getShooter();
}
// Makes sure that if there was an attacking player, that the event is allowed for the game
if (attacker != null) {
// Cancel if one player is in the game but other isn't
if ((board.contains(player) && !board.contains(attacker)) || (!board.contains(player) && board.contains(attacker))) {
event.setCancelled(true);
return;
// Ignore event if neither player are in the game
} else if (!board.contains(player) && !board.contains(attacker)) {
return;
// Ignore event if players are on the same team, or one of them is a spectator
} else if (board.onSameTeam(player, attacker) || board.isSpectator(player) || board.isSpectator(attacker)) {
event.setCancelled(true);
return;
// Ignore the event if pvp is disabled, and a hider is trying to attack a seeker
} else if (!pvpEnabled && board.isHider(attacker) && board.isSeeker(player)) {
event.setCancelled(true);
return;
}
// If there was no attacker, if the damaged is not a player, ignore them.
} else if (!board.contains(player)) {
return;
// If there is no attacker, it most of been by natural causes. If pvp is disabled, and config doesn't allow natural causes, cancel event.
} else if (!pvpEnabled && !allowNaturalCauses && board.contains(player)) {
event.setCancelled(true);
return;
}
// Spectators and cannot take damage
if (board.isSpectator(player)) {
event.setCancelled(true);
if (Main.getInstance().supports(18) && player.getLocation().getBlockY() < -64) {
player.teleport(new Location(Bukkit.getWorld(game.getGameWorld()), spawnPosition.getX(), spawnPosition.getY(), spawnPosition.getZ()));
} else if (!Main.getInstance().supports(18) && player.getLocation().getY() < 0) {
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;
}
// Check if player dies (pvp mode)
if(pvpEnabled && player.getHealth() - event.getFinalDamage() >= 0.5) return;
// Handle death event
event.setCancelled(true);
// Play death effect
if (Main.getInstance().supports(9)) {
XSound.ENTITY_PLAYER_DEATH.play(player, 1, 1);
} else {
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()));
// Add leaderboard stats
board.addDeath(player.getUniqueId());
if (attacker != null) board.addKill(attacker.getUniqueId());
// Broadcast player death message
if (board.isSeeker(player)) {
game.broadcastMessage(message("GAME_PLAYER_DEATH").addPlayer(player).toString());
} else if (board.isHider(player)) {
if (attacker == null) {
game.broadcastMessage(message("GAME_PLAYER_FOUND").addPlayer(player).toString());
} else {
game.broadcastMessage(message("GAME_PLAYER_FOUND_BY").addPlayer(player).addPlayer(attacker).toString());
}
board.addSeeker(player);
}
//Reload player
PlayerLoader.resetPlayer(player, board);
board.reloadBoardTeams();
}
}

View file

@ -0,0 +1,120 @@
package net.tylermurphy.hideAndSeek.game.listener;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.messages.ActionBar;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.ArrayList;
import java.util.List;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.glowPowerupItem;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class InteractHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(PlayerInteractEvent event) {
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 (Main.getInstance().getGame().getStatus() == Status.STANDBY)
onPlayerInteractLobby(temp, event);
if (Main.getInstance().getGame().getStatus() == Status.PLAYING)
onPlayerInteractGame(temp, event);
if (Main.getInstance().getBoard().isSpectator(event.getPlayer()))
onSpectatorInteract(temp, event);
}
private void onPlayerInteractLobby(ItemStack temp, PlayerInteractEvent event) {
if (temp.isSimilar(lobbyLeaveItem)) {
event.setCancelled(true);
Main.getInstance().getGame().leave(event.getPlayer());
}
if (temp.isSimilar(lobbyStartItem) && event.getPlayer().hasPermission("hideandseek.start")) {
event.setCancelled(true);
if (Main.getInstance().getGame().isNotSetup()) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_SETUP"));
return;
}
if (Main.getInstance().getGame().getStatus() != Status.STANDBY) {
event.getPlayer().sendMessage(errorPrefix + message("GAME_INPROGRESS"));
return;
}
if (Main.getInstance().getBoard().size() < minPlayers) {
event.getPlayer().sendMessage(errorPrefix + message("START_MIN_PLAYERS").addAmount(minPlayers));
return;
}
Main.getInstance().getGame().start();
}
}
private void onPlayerInteractGame(ItemStack temp, PlayerInteractEvent event) {
if (temp.isSimilar(glowPowerupItem)) {
if (!glowEnabled) return;
Player player = event.getPlayer();
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());
event.setCancelled(true);
}
}
}
private void onSpectatorInteract(ItemStack temp, PlayerInteractEvent event){
if(temp.isSimilar(flightToggleItem)){
boolean isFlying = event.getPlayer().getAllowFlight();
event.getPlayer().setAllowFlight(!isFlying);
event.getPlayer().setFlying(!isFlying);
ActionBar.clearActionBar(event.getPlayer());
if(!isFlying){
ActionBar.sendActionBar(event.getPlayer(), message("FLYING_ENABLED").toString());
} else {
ActionBar.sendActionBar(event.getPlayer(), message("FLYING_DISABLED").toString());
}
return;
}
if(temp.isSimilar(teleportItem)){
int amount = Main.getInstance().getBoard().getHiders().size() + Main.getInstance().getBoard().getSeekers().size();
Inventory teleportMenu = Main.getInstance().getServer().createInventory(null, 9*(((amount-1)/9)+1), ChatColor.stripColor(teleportItem.getItemMeta().getDisplayName()));
List<String> hider_lore = new ArrayList<>(); hider_lore.add(message("HIDER_TEAM_NAME").toString());
Main.getInstance().getBoard().getHiders().forEach(hider -> {
teleportMenu.addItem(getSkull(hider, hider_lore));
});
List<String> seeker_lore = new ArrayList<>(); seeker_lore.add(message("SEEKER_TEAM_NAME").toString());
Main.getInstance().getBoard().getSeekers().forEach(seeker -> {
teleportMenu.addItem(getSkull(seeker, seeker_lore));
});
event.getPlayer().openInventory(teleportMenu);
}
}
private ItemStack getSkull(Player player, List<String> lore){
assert XMaterial.PLAYER_HEAD.parseMaterial() != null;
ItemStack playerhead = new ItemStack(XMaterial.PLAYER_HEAD.parseMaterial(), 1, (byte) 3);
SkullMeta playerheadmeta = (SkullMeta) playerhead.getItemMeta();
playerheadmeta.setOwner(player.getName());
playerheadmeta.setDisplayName(player.getName());
playerheadmeta.setLore(lore);
playerhead.setItemMeta(playerheadmeta);
return playerhead;
}
}

View file

@ -0,0 +1,77 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.game.listener;
import com.cryptomorin.xseries.XMaterial;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.command.Debug;
import net.tylermurphy.hideAndSeek.game.util.Status;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class InventoryHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
checkForInventoryMove(event);
checkForSpectatorTeleportMenu(event);
checkForDebugMenu(event);
}
private void checkForInventoryMove(InventoryClickEvent event){
if (Main.getInstance().getBoard().contains((Player) event.getWhoClicked()) && Main.getInstance().getGame().getStatus() == Status.STANDBY) {
event.setCancelled(true);
}
}
private void checkForSpectatorTeleportMenu(InventoryClickEvent event){
Player player = (Player) event.getWhoClicked();
if (Main.getInstance().getBoard().isSpectator(player) && event.getCurrentItem().getType() == XMaterial.PLAYER_HEAD.parseMaterial()) {
event.setCancelled(true);
player.closeInventory();
String name = event.getCurrentItem().getItemMeta().getDisplayName();
Player clicked = Main.getInstance().getServer().getPlayer(name);
if(clicked == null) return;
player.teleport(clicked);
}
}
private void checkForDebugMenu(InventoryClickEvent event){
Player player = (Player) event.getWhoClicked();
boolean debug;
if(Main.getInstance().supports(14)){
debug = event.getView().getTitle().equals("Debug Menu") && player.hasPermission("hideandseek.debug");
} else {
debug = event.getInventory().getName().equals("Debug Menu") && player.hasPermission("hideandseek.debug");
}
if (debug){
event.setCancelled(true);
player.closeInventory();
Debug.handleOption(player, event.getRawSlot());
}
}
}

View file

@ -0,0 +1,83 @@
package net.tylermurphy.hideAndSeek.game.listener;
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;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.exitPosition;
public class JoinLeaveHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(PlayerJoinEvent event) {
if(!Main.getInstance().getDatabase().getNameData().update(event.getPlayer().getUniqueId(), event.getPlayer().getName())){
Main.getInstance().getLogger().warning("Failed to save name data for user: " + event.getPlayer().getName());
}
Main.getInstance().getBoard().remove(event.getPlayer());
removeItems(event.getPlayer());
if (Main.getInstance().getGame().isNotSetup()) return;
if (autoJoin) {
Main.getInstance().getGame().join(event.getPlayer());
} else if (teleportToExit) {
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(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);
}
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
handleLeave(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onKick(PlayerKickEvent event) {
handleLeave(event.getPlayer());
}
private void handleLeave(Player player) {
Main.getInstance().getBoard().remove(player);
if (Main.getInstance().getGame().getStatus() == Status.STANDBY) {
Main.getInstance().getBoard().reloadLobbyBoards();
} else {
Main.getInstance().getBoard().reloadGameBoards();
}
for(PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
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

@ -0,0 +1,62 @@
package net.tylermurphy.hideAndSeek.game.listener;
import com.comphenix.protocol.PacketType;
import com.google.common.collect.Sets;
import net.tylermurphy.hideAndSeek.Main;
import net.tylermurphy.hideAndSeek.game.listener.events.PlayerJumpEvent;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import java.util.Set;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.saveMaxZ;
public class MovementHandler implements Listener {
private final Set<UUID> prevPlayersOnGround = Sets.newHashSet();
@EventHandler(priority = EventPriority.HIGHEST)
public void onMove(PlayerMoveEvent event) {
if (event.getTo() == null || event.getTo().getWorld() == null) return;
checkJumping(event);
checkBounds(event);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onJump(PlayerJumpEvent event) {
if(Main.getInstance().getBoard().isSpectator(event.getPlayer()) && event.getPlayer().getAllowFlight()) {
event.getPlayer().setFlying(true);
}
}
private void checkJumping(PlayerMoveEvent event){
if (event.getPlayer().getVelocity().getY() > 0) {
if (event.getPlayer().getLocation().getBlock().getType() != Material.LADDER && prevPlayersOnGround.contains(event.getPlayer().getUniqueId())) {
if (!event.getPlayer().isOnGround()) {
Main.getInstance().getServer().getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer()));
}
}
}
if (event.getPlayer().isOnGround()) {
prevPlayersOnGround.add(event.getPlayer().getUniqueId());
} else {
prevPlayersOnGround.remove(event.getPlayer().getUniqueId());
}
}
private void checkBounds(PlayerMoveEvent event){
if (!Main.getInstance().getBoard().contains(event.getPlayer())) return;
if (!event.getPlayer().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return;
if (!event.getTo().getWorld().getName().equals(Main.getInstance().getGame().getGameWorld())) return;
if (event.getPlayer().hasPermission("hideandseek.leavebounds")) return;
if (event.getTo().getBlockX() < saveMinX || event.getTo().getBlockX() > saveMaxX || event.getTo().getBlockZ() < saveMinZ || event.getTo().getBlockZ() > saveMaxZ) {
event.setCancelled(true);
}
}
}

View file

@ -0,0 +1,39 @@
package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
public class PlayerHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return;
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRegainHealth(EntityRegainHealthEvent event) {
if (event.getRegainReason() == EntityRegainHealthEvent.RegainReason.SATIATED || event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN) {
if (event.getEntity() instanceof Player) {
if (!Main.getInstance().getBoard().contains((Player) event.getEntity())) return;
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemDrop(PlayerDropItemEvent event) {
if (Main.getInstance().getBoard().contains(event.getPlayer())) {
event.setCancelled(true);
}
}
}

View file

@ -0,0 +1,40 @@
package net.tylermurphy.hideAndSeek.game.listener;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class RespawnHandler implements Listener {
public static final Map<UUID, Location> temp_loc = new HashMap<>();
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if (!Main.getInstance().getBoard().contains(player)) return;
event.setKeepInventory(true);
event.setDeathMessage("");
temp_loc.put(player.getUniqueId(), player.getLocation());
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 (!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

@ -0,0 +1,56 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.game.listener.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class PlayerJumpEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancel = false;
public PlayerJumpEvent(Player player) {
super(player);
}
@Override
public boolean isCancelled() {
return cancel;
}
@Override
public void setCancelled(boolean b) {
this.cancel = !b;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@SuppressWarnings("unused")
public static HandlerList getHandlerList() {
return handlers;
}
}

View file

@ -0,0 +1,26 @@
/*
* This file is part of Kenshins Hide and Seek
*
* Copyright (c) 2022 Tyler Murphy.
*
* Kenshins Hide and Seek free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* he Free Software Foundation version 3.
*
* Kenshins Hide and Seek is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.tylermurphy.hideAndSeek.game.util;
public enum CountdownDisplay {
CHAT,
ACTIONBAR,
TITLE
}

View file

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

View file

@ -17,10 +17,10 @@
*
*/
package net.tylermurphy.hideAndSeek.util;
package net.tylermurphy.hideAndSeek.game.util;
public enum WinType {
HIDER_WIN,
SEEKER_WIN,
NONE
HIDER_WIN, SEEKER_WIN, NONE
}

View file

@ -17,26 +17,30 @@
*
*/
package net.tylermurphy.hideAndSeek.game;
package net.tylermurphy.hideAndSeek.util;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.*;
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;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.tylermurphy.hideAndSeek.command.*;
import static net.tylermurphy.hideAndSeek.configuration.Config.errorPrefix;
import static net.tylermurphy.hideAndSeek.configuration.Config.permissionsRequired;
import static net.tylermurphy.hideAndSeek.configuration.Localization.LOCAL;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class CommandHandler {
public static Map<String,ICommand> COMMAND_REGISTER = new LinkedHashMap<>();
public static final Map<String,ICommand> COMMAND_REGISTER = new LinkedHashMap<>();
private static void registerCommand(ICommand command) {
if(!COMMAND_REGISTER.containsKey(command.getLabel())) {
if (!COMMAND_REGISTER.containsKey(command.getLabel())) {
COMMAND_REGISTER.put(command.getLabel().toLowerCase(), command);
}
}
@ -58,27 +62,31 @@ public class CommandHandler {
registerCommand(new Leave());
registerCommand(new Top());
registerCommand(new Wins());
registerCommand(new Debug());
}
public static boolean handleCommand(CommandSender sender, String[] args) {
if(!(sender instanceof Player)) {
if (!(sender instanceof Player)) {
sender.sendMessage(errorPrefix + message("COMMAND_PLAYER_ONLY"));
} else if(args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) {
if(permissionsRequired && !sender.hasPermission("hideandseek.about")) {
return true;
}
Player player = (Player) sender;
if (args.length < 1 || !COMMAND_REGISTER.containsKey(args[0].toLowerCase()) ) {
if (permissionsRequired && !sender.hasPermission("hideandseek.about")) {
sender.sendMessage(errorPrefix + LOCAL.get(""));
} else {
COMMAND_REGISTER.get("about").execute(sender, null);
COMMAND_REGISTER.get("about").execute(player, null);
}
} else {
if(!args[0].equalsIgnoreCase("about") && !args[0].equalsIgnoreCase("help") && SaveMap.runningBackup) {
if (!args[0].equalsIgnoreCase("about") && !args[0].equalsIgnoreCase("help") && SaveMap.runningBackup) {
sender.sendMessage(errorPrefix + message("MAPSAVE_INPROGRESS"));
} else if(permissionsRequired && !sender.hasPermission("hideandseek."+args[0].toLowerCase())) {
} else if (permissionsRequired && !sender.hasPermission("hideandseek."+args[0].toLowerCase())) {
sender.sendMessage(errorPrefix + message("COMMAND_NOT_ALLOWED"));
} else {
try {
COMMAND_REGISTER.get(args[0].toLowerCase()).execute(sender,Arrays.copyOfRange(args, 1, args.length));
COMMAND_REGISTER.get(args[0].toLowerCase()).execute(player,Arrays.copyOfRange(args, 1, args.length));
} catch (Exception e) {
sender.sendMessage(errorPrefix + "An error has occured.");
sender.sendMessage(errorPrefix + "An error has occurred.");
e.printStackTrace();
}
}

View file

@ -0,0 +1,145 @@
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.util.PlayerInfo;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
import static net.tylermurphy.hideAndSeek.configuration.Config.placeholderError;
import static net.tylermurphy.hideAndSeek.configuration.Config.placeholderNoData;
public class PAPIExpansion extends PlaceholderExpansion {
@Override
public @NotNull String getIdentifier() {
return "hs";
}
@Override
public @NotNull String getAuthor() {
return "KenshinEto";
}
@Override
public @NotNull String getVersion() {
return "1.4.3";
}
@Override
public boolean persist() {
return true;
}
@Override
public String onRequest(OfflinePlayer player, @NotNull String params) {
Database database = Main.getInstance().getDatabase();
String[] args = params.split("_");
if (args.length < 1) return null;
if ((args.length == 2 || args.length == 3) && (args[0].equals("stats") || args[0].equals("rank-place"))) {
Optional<PlayerInfo> info = this.getPlayerInfo(args.length == 2 ? player.getUniqueId() : database.getNameData().getUUID(args[2]));
if (info.isPresent()) {
switch (args[0]) {
case "stats":
return getValue(info.get(), args[1]);
case "rank-place":
if (getRanking(args[1]) == null) return placeholderError;
Integer count = database.getGameData().getRanking(getRanking(args[1]), player.getUniqueId());
if (getValue(info.get(), args[1]).equals("0")) return "-";
if (count == null) return placeholderNoData;
return count.toString();
}
} else switch (args[0]) {
case "stats":
return placeholderNoData;
case "rank-place":
return "-";
}
}
if ((args[0].equals("rank-score") || args[0].equals("rank-name")) && args.length == 3) {
int place = Integer.parseInt(args[2]);
if (place < 1 || getRanking(args[1]) == null) return placeholderError;
PlayerInfo info = database.getGameData().getInfoRanking(getRanking(args[1]), place);
if (info == null) return placeholderNoData;
return args[0].equals("rank-score") ? getValue(info, args[1]) : Main.getInstance().getServer().getOfflinePlayer(info.getUniqueId()).getName();
}
return null;
}
private String getValue(PlayerInfo info, String query) {
if (query == null) return null;
switch (query) {
case "total-wins":
return String.valueOf(info.getHiderWins() + info.getSeekerWins());
case "hider-wins":
return String.valueOf(info.getHiderWins());
case "seeker-wins":
return String.valueOf(info.getSeekerWins());
case "total-games":
return String.valueOf(info.getHiderGames() + info.getSeekerGames());
case "hider-games":
return String.valueOf(info.getHiderGames());
case "seeker-games":
return String.valueOf(info.getSeekerGames());
case "total-kills":
return String.valueOf(info.getHiderKills() + info.getSeekerKills());
case "hider-kills":
return String.valueOf(info.getHiderKills());
case "seeker-kills":
return String.valueOf(info.getSeekerKills());
case "total-deaths":
return String.valueOf(info.getHiderDeaths() + info.getSeekerDeaths());
case "hider-deaths":
return String.valueOf(info.getHiderDeaths());
case "seeker-deaths":
return String.valueOf(info.getSeekerDeaths());
default:
return null;
}
}
private String getRanking(@NotNull String query) {
switch (query) {
case "total-wins":
return "(hider_wins + seeker_wins)";
case "hider-wins":
return "hider_wins";
case "seeker-wins":
return "seeker_wins";
case "total-games":
return "(hider_games + seeker_games)";
case "hider-games":
return "hider_games";
case "seeker-games":
return "seeker_games";
case "total-kills":
return "(hider_kills + seeker_kills)";
case "hider-kills":
return "hider_kills";
case "seeker-kills":
return "seeker_kills";
case "total-deaths":
return "(hider_deaths + seeker_deaths)";
case "hider-deaths":
return "hider_deaths";
case "seeker-deaths":
return "seeker_deaths";
default:
return null;
}
}
private Optional<PlayerInfo> getPlayerInfo(@Nullable UUID uniqueId) {
return Optional.ofNullable(Main.getInstance().getDatabase().getGameData().getInfo(uniqueId));
}
}

View file

@ -1,57 +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 java.lang.reflect.InvocationTargetException;
import org.bukkit.entity.Player;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry;
import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer;
public class Packet {
private static final ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
public static void setGlow(Player player, Player target, boolean glowing) {
PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.ENTITY_METADATA);
packet.getIntegers().write(0, target.getEntityId());
WrappedDataWatcher watcher = new WrappedDataWatcher();
Serializer serializer = Registry.get(Byte.class);
watcher.setEntity(target);
if(glowing) {
watcher.setObject(0, serializer, (byte) (0x40));
} else {
watcher.setObject(0, serializer, (byte) (0x0));
}
packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects());
try {
protocolManager.sendServerPacket(player, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

View file

@ -19,30 +19,29 @@
package net.tylermurphy.hideAndSeek.util;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import net.tylermurphy.hideAndSeek.game.CommandHandler;
import org.bukkit.command.CommandSender;
public class TabCompleter{
public class TabCompleter {
public static List<String> handleTabComplete(CommandSender sender, String[] args) {
if(args.length == 1) {
if (args.length == 1) {
return new ArrayList<>(CommandHandler.COMMAND_REGISTER.keySet())
.stream()
.filter(handle -> sender.hasPermission("hideandseek."+handle.toLowerCase()) && handle.toLowerCase().startsWith(args[0].toLowerCase(Locale.ROOT)))
.collect(Collectors.toList());
} else if(args.length > 1) {
if(!CommandHandler.COMMAND_REGISTER.containsKey(args[0].toLowerCase())) {
} else if (args.length > 1) {
if (!CommandHandler.COMMAND_REGISTER.containsKey(args[0].toLowerCase())) {
return null;
} else {
String[] usage = CommandHandler.COMMAND_REGISTER.get(args[0].toLowerCase()).getUsage().split(" ");
if(args.length - 2 < usage.length) {
if (args.length - 2 < usage.length) {
String parameter = usage[args.length-2];
if(parameter.equals("<player>")) {
if (parameter.equals("<player>")) {
return null;
} else {
List<String> temp = new ArrayList<>();

View file

@ -1,106 +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 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 String UUID_URL = "https://api.mojang.com/users/profiles/minecraft/";
private static int cacheTask;
public static void init(){
cacheTask = Main.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, CACHE::clear,600*20, 600*20);
}
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());
}
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

@ -1,45 +0,0 @@
package net.tylermurphy.hideAndSeek.util;
import org.bukkit.Bukkit;
import java.util.HashMap;
import java.util.Map;
public class Version {
private static final Map<String,Boolean> CACHE = new HashMap<>();
public static boolean atLeast(String testVersion){
if(CACHE.containsKey(testVersion)) return CACHE.get(testVersion);
String[] serverCheckTemp = Bukkit.getBukkitVersion().substring(2,Bukkit.getBukkitVersion().indexOf('-')).split("\\.");
int[] serverCheck = new int[serverCheckTemp.length];
for(int i=0; i<serverCheck.length; i++){
serverCheck[i] = Integer.parseInt(serverCheckTemp[i]);
}
String[] customCheckTemp = testVersion.substring(2).split("\\.");
int[] customCheck = new int[customCheckTemp.length];
for(int i=0; i<customCheck.length; i++){
customCheck[i] = Integer.parseInt(customCheckTemp[i]);
}
boolean result = getResult(customCheck, serverCheck);
CACHE.put(testVersion, result);
return result;
}
private static boolean getResult(int[] customCheck, int[] serverCheck){
if(customCheck[0] > serverCheck[0]) return false;
else if(customCheck[0] < serverCheck[0]) return true;
else {
if (customCheck.length == 1 && serverCheck.length == 1) return true;
else if(customCheck.length == 2 && serverCheck.length == 2){
return customCheck[1] <= serverCheck[1];
}
else return serverCheck.length == 2;
}
}
}

View file

@ -19,15 +19,15 @@
package net.tylermurphy.hideAndSeek.world;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class VoidGenerator extends ChunkGenerator{
public @NotNull List<BlockPopulator> getDefaultPopulators(@NotNull World world) {

View file

@ -19,85 +19,89 @@
package net.tylermurphy.hideAndSeek.world;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.tylermurphy.hideAndSeek.util.Version;
import net.tylermurphy.hideAndSeek.Main;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import net.tylermurphy.hideAndSeek.Main;
import java.io.*;
import java.nio.file.Files;
import static net.tylermurphy.hideAndSeek.configuration.Config.*;
import static net.tylermurphy.hideAndSeek.configuration.Localization.message;
public class WorldLoader {
String mapname;
String savename;
private String mapName;
private String saveName;
public WorldLoader(String mapname) {
this.mapname = mapname;
this.savename = "hideandseek_"+mapname;
public WorldLoader(String mapName) {
this.mapName = mapName;
this.saveName = "hideandseek_"+ mapName;
}
public World getWorld(){
return Bukkit.getServer().getWorld(savename);
public void setNewMap(String mapName){
this.mapName = mapName;
this.saveName = "hideandseek_"+ mapName;
}
public void unloadMap(){
World world = Bukkit.getServer().getWorld(savename);
if(world == null){
Main.plugin.getLogger().warning(savename + " already unloaded.");
public World getWorld() {
return Bukkit.getServer().getWorld(saveName);
}
public void unloadMap() {
World world = Bukkit.getServer().getWorld(saveName);
if (world == null) {
Main.getInstance().getLogger().warning(saveName + " already unloaded.");
return;
}
if(Bukkit.getServer().unloadWorld(world, false)){
Main.plugin.getLogger().info("Successfully unloaded " + savename);
world.getPlayers().forEach(player -> player.teleport(new Location(Bukkit.getWorld(exitWorld), exitPosition.getX(), exitPosition.getY(), exitPosition.getZ())));
if (Bukkit.getServer().unloadWorld(world, false)) {
Main.getInstance().getLogger().info("Successfully unloaded " + saveName);
}else{
Main.plugin.getLogger().severe("COULD NOT UNLOAD " + savename);
Main.getInstance().getLogger().severe("COULD NOT UNLOAD " + saveName);
}
}
public void loadMap(){
Bukkit.getServer().createWorld(new WorldCreator(savename).generator(new VoidGenerator()));
World world = Bukkit.getServer().getWorld(savename);
if(world == null){
Main.plugin.getLogger().severe("COULD NOT LOAD " + savename);
public void loadMap() {
Bukkit.getServer().createWorld(new WorldCreator(saveName).generator(new VoidGenerator()));
World world = Bukkit.getServer().getWorld(saveName);
if (world == null) {
Main.getInstance().getLogger().severe("COULD NOT LOAD " + saveName);
return;
}
world.setAutoSave(false);
}
public void rollback(){
public void rollback() {
unloadMap();
loadMap();
}
public String save() {
File current = new File(Main.root+File.separator+mapname);
if(current.exists()) {
World world = Bukkit.getServer().getWorld(mapName);
if(world == null){
throw new RuntimeException("Invalid world to save: " + mapName);
}
File current = new File(Main.getInstance().getWorldContainer()+File.separator+ mapName);
if (current.exists()) {
try {
File destenation = new File(Main.root+File.separator+savename);
File temp_destenation = new File(Main.root+File.separator+"temp_"+savename);
File destination = new File(Main.getInstance().getWorldContainer()+File.separator+ saveName);
File temp_destination = new File(Main.getInstance().getWorldContainer()+File.separator+"temp_"+ saveName);
copyFileFolder("region",true);
copyFileFolder("entities",true);
copyFileFolder("datapacks",false);
copyFileFolder("data",false);
File srcFile = new File(current, "level.dat");
File destFile = new File(temp_destenation, "level.dat");
File destFile = new File(temp_destination, "level.dat");
copyFile(srcFile,destFile);
if(destenation.exists()) {
deleteDirectory(destenation);
if(!destenation.mkdir()){
throw new RuntimeException("Failed to create directory: "+destenation.getPath());
if (destination.exists()) {
deleteDirectory(destination);
}
}
if(!temp_destenation.renameTo(destenation)){
throw new RuntimeException("Failed to rename directory: "+temp_destenation.getPath());
if (!temp_destination.renameTo(destination)) {
throw new RuntimeException("Failed to rename directory: "+temp_destination.getPath());
}
} catch(IOException e) {
e.printStackTrace();
@ -110,38 +114,34 @@ 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());
if(region.exists() && region.isDirectory()) {
System.out.println("passed");
if(!temp.exists())
if(!temp.mkdirs())
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()) {
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");
if (files == null) {
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) {
if (isMca) {
int minX = (int)Math.floor(saveMinX / 512.0);
int minZ = (int)Math.floor(saveMinZ / 512.0);
int maxX = (int)Math.floor(saveMaxX / 512.0);
int maxZ = (int)Math.floor(saveMaxZ / 512.0);
String[] parts = file.split("\\.");
if(parts.length > 1) {
Main.plugin.getLogger().info(file);
if( Integer.parseInt(parts[1]) < minX || Integer.parseInt(parts[1]) > maxX || Integer.parseInt(parts[2]) < minZ || Integer.parseInt(parts[2]) > maxZ )
if (parts.length > 1) {
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;
}
}
File srcFile = new File(region, file);
if(srcFile.isDirectory()) {
if (srcFile.isDirectory()) {
copyFileFolder(name+File.separator+file, false);
} else {
File destFile = new File(temp, file);
@ -152,8 +152,8 @@ public class WorldLoader {
}
private void copyFile(File source, File target) throws IOException {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
InputStream in = Files.newInputStream(source.toPath());
OutputStream out = Files.newOutputStream(target.toPath());
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
@ -169,7 +169,7 @@ public class WorldLoader {
deleteDirectory(file);
}
}
if(!directoryToBeDeleted.delete()){
if (!directoryToBeDeleted.delete()) {
throw new RuntimeException("Failed to delete directory: "+directoryToBeDeleted.getPath());
}
}

View file

@ -14,6 +14,19 @@ gameLength: 1200
# default: true
announceMessagesToNonPlayers: true
# When the game is starting, the plugin will state there is x seconds left to hide.
# You change where countdown messages to be displayed: in the chat, action bar, or a title.
# Below you can set CHAT, ACTIONBAR, or TITLE. Any invalid option will revert to CHAT.
#
# CHAT - Messages will be displayed in the chat
#
# ACTIONBAR - Messages will be displayed in the action bar (area above the hotbar)
#
# TITLE - Messages will be displayed as a title
#
# default: CHAT
hideCountdownDisplay: CHAT
# Allow Hiders to see their own teams nametags as well as seekers. Seekers can never see nametags regardless.
# default: false
nametagsVisible: false
@ -33,6 +46,13 @@ minPlayers: 2
# default: true
pvp: true
# !! Only effects the game at all if pvp is set to false !!
# By default, If you disable pvp, Hiders and Seekers can no longer take damage from natural causes such as
# falling or projectiles. If you want, you can keep pvp disabled so that Seekers only have to tag Hiders, but
# all players can still take fall damage or any other damage that's not from another player.
# deafult: false
allowNaturalCauses: false
# Players that join the server will automatically be placed into the lobby.
# default: false
autoJoin: false
@ -44,8 +64,15 @@ autoJoin: false
# default: false
teleportToExit: false
# Normally when the game ends, players are set back to the lobby to play another game.
# You can disable this, and empty the lobby after the game finishes. This is like everyone
# running /hs leave at the end of the game. Players will leave either to the exit position
# or another server depending on what you have `leaveType` set too.
# default: false
leaveOnEnd: false
# What do you want to happen when a player leaves the lobby. If you are running a single server, maybe you want to send
# them to the world hub. But if you are running a bungee-cord or velocity server, maybe you want to send them to the servers
# them to the world hub. But if you are running a bungee-cord or velocity server, maybe you want to send them to the servers'
# hub.
#
# EXIT - Sends the player to the specified exit position set by /hs setexit
@ -59,8 +86,36 @@ leaveType: EXIT
# players too.
leaveServer: hub
# The worldborder closes every interval, which is evey [delay] in minutes.
# Thw worldborder starts at [size], and decreases 100 blocks every interval.
# By default, the plugin forces you to use a map save to protect from changes to a map thought a game play though. It copies your
# hide-and-seek world to a separate world, and loads the game there to contain the game in an isolated and backed up map This allows you to
# not worry about your hide-and-seek map from changing, as all changes are made are in a separate world file that doesn't get saved. Once the game
# ends, it unloads the map and doesn't save. Then reloads the duplicate to the original state, rolling back the map for the next game.
# It is highly recommended that you keep this set to true unless you have other means of protecting your hide-and-seek map.
# default: true
mapSaveEnabled: true
# How you want to store game data. If you are running a single server, sqlite is fine, as no setup is necessary.
# But if you want the data to go across multiple servers, you can switch it to mysql.
# WARNING: Data is not saved across databases. You have to migrate the data yourself!
#
# SQLITE - A single database.db file in the plugin folder, good for a single server.
#
# MYSQL - Uses a mysql server to store data, good for multi-server setups or large servers.
#
# default: SQLITE
databaseType: SQLITE
# The following settings are used for MYSQL databases ONLY. If you are running SQLITE, these
# will be ignored. If you are running MYSQL, you need to provide the database host url, database
# host port (usually 3306), database username, and database password.
databaseHost: localhost
databasePort: 3306
databaseUser: root
databasePass:
databaseName: hideandseek
# The world border closes every interval, which is evey [delay] in minutes.
# Thw world border starts at [size], and decreases 100 blocks every interval.
# x & z are the center location. [enabled] is whenever the border is enabled.
# You can choose if Hiders are warned 30 seconds before the border moves.
worldBorder:
@ -92,6 +147,18 @@ glow:
time: 30
stackable: true
enabled: true
name: "Glow Powerup"
lore: [ "Throw to make all seekers glow", "Last 30s, all hiders can see it", "Time stacks on multi use" ]
material: SNOWBALL
model-data: 0
# This has the same glow effect as the glow powerup in that all seekers positions get
# shown to hiders. But enabling this force disables the powerup, and instead always shows
# the seekers positions to the hiders. Good for small maps. Since the glow effect wasn't added
# until Minecraft 1.9, any server running 1.8 will have this disabled regardless of the
# options below.
# default: false
alwaysGlow: false
# The message prefixes displayed before messages. The message contents themselves
# can be changed in localization.yml.
@ -104,6 +171,12 @@ prefix:
gameover: '&aGame Over > &f'
warning: '&cWarning > &f'
# This plugin has support for custom placeholders with PlaceholderAPI. If you make a mistake when creating a placeholder,
# the plugin may tell you an error. Below you can change what could appear as an error message.
placeholder:
incorrect: "{Error}"
noData: "{No Data}"
# This is the section if you want a standard "waiting for players" lobby. You can specify
# the standard countdown length under [countdown] (min 10 seconds). Then once the lobby gets to a size specified
# by [changeCountdown], the timer will automatically go to 10 seconds. [min] is the minimum players
@ -117,24 +190,44 @@ lobby:
# Below are the two items given to you when you join a lobby. A item to click to leave the lobby, and another
# to start the game. Each of these items can be toggled separately, but only these items are currently supported.
# You can customize the material, name, lore, and position of the item. And finally, the start item is marked as
# adminOnly be default since the /hs start command is also admin by default. If you set adminOnly to false, only
# the item will become non admin only, not the command.
# You can customize the material, name, lore, and position of the item. You can also change the model data if your
# server is running 1.14 or above. Any earlier version, the model-data tag will be ignored; Model-data 0 is also ignored.
# Finally, the start item is marked as adminOnly be default since the /hs start command is also admin by default.
# If you set adminOnly to false, only the item will become non admin only, not the command.
lobbyItems:
leave:
material: BED
name: "&cLeave Lobby"
lore: ["Go back to server hub"]
position: 8
model-data: 0
enabled: true
start:
material: CLOCK
name: "&bStart Game"
lore: []
position: 0
model-data: 0
enabled: true
adminOnly: true
# Below are the two items given to you when you join the game as a spectator. One toggles flight mode, and the other
# opens a gui to teleport to other players! Just like the lobby items, you can customize the material, name, lore,
# and position of the item. You can also change the model data if your server is running 1.14 or above.
spectatorItems:
flight:
material: FEATHER
name: "&bToggle Flight"
lore: [ "Turns flying on and off" ]
position: 3
model-data: 0
teleport:
material: COMPASS
name: "&bTeleport to Others"
lore: [ "Allows you to teleport to all other players in game" ]
position: 5
model-data: 0
# As a hider, the closer a seeker gets to you, the louder and faster a pining noise will play.
# There are 3 separate distances (in blocks) you can set to the 3 different levels for the noise.
# The higher the level, the closer the seeker.
@ -143,6 +236,12 @@ seekerPing:
level1: 30
level2: 20
level3: 10
sounds:
leadingVolume: 0.5
volume: 0.3
pitch: 1
heartbeatNoise: BLOCK_NOTE_BLOCK_BASEDRUM
ringingNoise: BLOCK_NOTE_BLOCK_PLING
enabled: true
# Changes the default plugin language. Currently, Supported localizations are:

View file

@ -15,6 +15,7 @@ Localization:
GAME_PLAYER_FOUND_BY: "&e{PLAYER}&f wurde von &c{PLAYER}&f gefunden und ist nun ein Seeker."
GAME_GAMEOVER_HIDERS_FOUND: "Alle Hider wurden gefunden."
GAME_GAMEOVER_SEEKERS_QUIT: "All Seeker haben das Spiel verlassen."
GAME_GAMEOVER_HIDERS_QUIT: "All Hider haben das Spiel verlassen."
GAME_GAMEOVER_TIME: "Seekers haben keine Spielzeit mehr. Die Hiders haben gewonnen!"
GAME_SETUP: "Spiel wurde noch nicht eingerichtet. Führe &c/hs setup&f aus, um die Einrichtungsschritte zu sehen."
GAME_INGAME: "Du bist bereits in der Lobby oder im Spiel."
@ -30,6 +31,7 @@ Localization:
MAPSAVE_WARNING: "All commands will be disabled whenthe save is in progress. Do not turn off the server."
MAPSAVE_END: "Speichervorgang abgeschlossen."
MAPSAVE_ERROR: "Aktuelle Weltkarte konnte nicht gefunden werden."
MAPSAVE_DISABLED: "Mapsave ist in config.yml deaktiviert."
WORLDBORDER_DISABLE: "World Border ausgeschaltet."
WORLDBORDER_INVALID_INPUT: "Ungültiger Wert: {AMOUNT}"
WORLDBORDER_MIN_SIZE: "World Border darf nicht geringer als 100 Blöcke sein."
@ -37,7 +39,7 @@ Localization:
WORLDBORDER_ENABLE: "Setze World Border zentriert von dieser Position aus. Größe: {AMOUNT}. Verzögerung: {AMOUNT}."
WORLDBORDER_DECREASING: "World Norder schrumpoft 100 Blöcke über die nächsten 30 Sekunden!"
WORLDBORDER_WARN: "Die Weltgrenze wird in den nächsten 30er Jahren schrumpfen!"
TAUNTED: "$c$oOh nein! Du wurdest geärgert!"
TAUNTED: "&c&oOh nein! Du wurdest geärgert!"
TAUNT: "Ein zufälliger Hider wird in den nächsten 30 Sekunden geärgert."
TAUNT_ACTIVATE: "Ärgern wurde aktiviert"
ERROR_GAME_SPAWN: "Bitte erst die Spawn-Position für das Spiel festlegen."
@ -54,8 +56,12 @@ Localization:
START_MIN_PLAYERS: "Um das Spiel zu starten benötigst du mindestens {AMOUNT} Spieler."
START_INVALID_NAME: "Ungültiger Spieler: {PLAYER}."
START_COUNTDOWN: "Die Hider haben {AMOUNT} Sekunden Zeit sich zu verstecken!"
START_COUNTDOWN_LAST: "Die Hider haben {AMOUNT} Sekunde Zeit sich zu verstecken!"
START: "Los, Seeker! Es ist Zeit, die Hider zu finden."
STOP: "Das Spiel wurde gestoppt."
HIDER_TEAM_NAME: "&6&lHIDER"
SEEKER_TEAM_NAME: "&c&lSEEKER"
SPECTATOR_TEAM_NAME: "&8&lSPECTATOR"
HIDERS_SUBTITLE: "Verstecke dich gut vor den Seekern!"
SEEKERS_SUBTITLE: "Finde alle Hider!"
SPECTATOR_SUBTITLE: "Du bist mitten im spiel beigetreten."
@ -65,7 +71,9 @@ Localization:
NO_GAME_INFO: "Keine Informationen zum Gameplay für diesen Spieler vorhanden."
INFORMATION_FOR: "Gewinninformationen für {PLAYER}:"
BLOCKED_COMMAND: "Command blocked by Kenshin's Hide And Seek"
FLYING_ENABLED: "Fliegen aktiviert"
FLYING_DISABLED: "Fliegen deaktiviert"
# DO NOT EDIT IT OR IT MAY BREAK OR RESET FILE
version: 2
version: 3
type: "de-DE"

View file

@ -15,6 +15,7 @@ Localization:
GAME_PLAYER_FOUND_BY: "&e{PLAYER}&f was found by &c{PLAYER}&f and became a seeker."
GAME_GAMEOVER_HIDERS_FOUND: "All hiders have been found."
GAME_GAMEOVER_SEEKERS_QUIT: "All seekers have quit."
GAME_GAMEOVER_HIDERS_QUIT: "All hiders have quit."
GAME_GAMEOVER_TIME: "Seekers ran out of time. Hiders win!"
GAME_SETUP: "Game is not setup. Run /hs setup to see what you need to do."
GAME_INGAME: "You are already in the lobby/game."
@ -30,6 +31,7 @@ Localization:
MAPSAVE_WARNING: "All commands will be disabled when the save is in progress. Do not turn off the server."
MAPSAVE_END: "Map save complete."
MAPSAVE_ERROR: "Couldn't find current map."
MAPSAVE_DISABLED: "Mapsave is disabled in config.yml."
WORLDBORDER_DISABLE: "Disabled world border."
WORLDBORDER_INVALID_INPUT: "Invalid integer {AMOUNT}."
WORLDBORDER_MIN_SIZE: "World border cannot be smaller than 100 blocks."
@ -55,8 +57,12 @@ Localization:
START_MIN_PLAYERS: "You must have at least {AMOUNT} players to start."
START_INVALID_NAME: "Invalid player: {PLAYER}."
START_COUNTDOWN: "Hiders have {AMOUNT} seconds to hide!"
START_COUNTDOWN_LAST: "Hiders have {AMOUNT} second to hide!"
START: "Attention SEEKERS, its time to find the hiders!"
STOP: "Game has been force stopped."
HIDER_TEAM_NAME: "&6&lHIDER"
SEEKER_TEAM_NAME: "&c&lSEEKER"
SPECTATOR_TEAM_NAME: "&8&lSPECTATOR"
HIDERS_SUBTITLE: "Hide away from the seekers"
SEEKERS_SUBTITLE: "Eliminate all hiders"
SPECTATOR_SUBTITLE: "You joined mid-game."
@ -66,6 +72,8 @@ Localization:
NO_GAME_INFO: "Player has no gameplay information."
INFORMATION_FOR: "Win information for {PLAYER}:"
BLOCKED_COMMAND: "Command blocked by Hide And Seek plugin."
FLYING_ENABLED: "&l&bFlying Enabled"
FLYING_DISABLED: "&l&bFlying Disabled"
# DO NOT EDIT IT OR IT MAY BREAK OR RESET FILE
version: 3

View file

@ -1,10 +1,11 @@
name: HideAndSeek
name: KenshinsHideAndSeek
main: net.tylermurphy.hideAndSeek.Main
version: 1.4.2
version: 1.5.0
author: KenshinEto
load: STARTUP
api-version: 1.13
depend: [ProtocolLib]
softdepend: [PlaceholderAPI]
commands:
hideandseek:
description: Hide and Seek command
@ -30,7 +31,8 @@ permissions:
hideandseek.leave: true
hideandseek.leavebounds: true
hideandseek.wins: true
hideand.top: true
hideandseek.top: true
hideandseek.debug: true
hideandseek.about:
description: Allows you to run the about command
default: true
@ -41,7 +43,7 @@ permissions:
description: Allows you to reload the config
default: op
hideandseek.setborder:
description: Allows you to set the game worldborder
description: Allows you to set the game world border
default: op
hideandseek.setspawn:
description: Allows you to set the game spawn point
@ -82,3 +84,6 @@ permissions:
hideandseek.top:
description: Allows players to see the global wins leaderboard
default: true
hideandseek.debug:
description: Opens the debug menu
default: op