mirror of
https://github.com/darksaid98/AlathranWars.git
synced 2026-12-01 14:38:55 +00:00
refactor: wip update 5 (sieges working)
This commit is contained in:
70 files changed
+2359
-1077
No files matched your search
@@ -0,0 +1,61 @@
|
||||
package com.github.alathra.AlathranWars;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.io.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class AlathranWarsLogger {
|
||||
|
||||
final File logsFolder;
|
||||
final File log;
|
||||
PrintWriter output = null;
|
||||
|
||||
public AlathranWarsLogger() {
|
||||
logsFolder = new File("plugins" + File.separator + "AlathranWars" + File.separator + "logs");
|
||||
log = new File(
|
||||
"plugins" + File.separator + "AlathranWars" + File.separator + "logs" + File.separator + "log.txt");
|
||||
}
|
||||
|
||||
public boolean checkFiles() {
|
||||
if (!logsFolder.exists()) {
|
||||
Bukkit.getLogger().warning("[AlathranWars] Error in AlathranWarsLogger - could not find logs directory");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!log.exists()) {
|
||||
Bukkit.getLogger().warning("[AlathranWars] Error in AlathranWarsLogger - could not find log.txt");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void initFileWriter() {
|
||||
// init file writer
|
||||
try {
|
||||
FileWriter fw = new FileWriter(
|
||||
"plugins" + File.separator + "AlathranWars" + File.separator + "logs" + File.separator + "log.txt",
|
||||
true);
|
||||
BufferedWriter bw = new BufferedWriter(fw);
|
||||
output = new PrintWriter(bw);
|
||||
} catch (IOException e1) {
|
||||
Bukkit.getLogger().warning("[AlathranWars] Error in AlathranWarsLogger - could not initialize file writer");
|
||||
}
|
||||
}
|
||||
|
||||
public void log(String msg) {
|
||||
// check for null files
|
||||
if (!checkFiles()) {
|
||||
return;
|
||||
}
|
||||
|
||||
initFileWriter();
|
||||
Date date = new Date();
|
||||
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
|
||||
String logMsg = "[" + format.format(date) + "] " + msg;
|
||||
output.println(logMsg);
|
||||
output.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.github.alathra.AlathranWars;
|
||||
|
||||
import com.github.alathra.AlathranWars.commands.CommandManager;
|
||||
import com.github.alathra.AlathranWars.data.ConfigManager;
|
||||
import com.github.alathra.AlathranWars.data.DataManager;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.hooks.HookManager;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.listeners.ListenerHandler;
|
||||
import com.github.alathra.AlathranWars.utility.DB;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class Main extends JavaPlugin {
|
||||
public static Economy econ;
|
||||
public static AlathranWarsLogger warLogger;
|
||||
private static Main instance;
|
||||
|
||||
static {
|
||||
instance = null;
|
||||
econ = null;
|
||||
}
|
||||
|
||||
private ConfigManager configManager;
|
||||
private DataManager dataManager;
|
||||
private CommandManager commandManager;
|
||||
private ListenerHandler listenerHandler;
|
||||
private HookManager hookManager;
|
||||
|
||||
@NotNull
|
||||
public static Main getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dangerous if done at the wrong time!
|
||||
*/
|
||||
/*public static void initData() {
|
||||
File userDataFolder = new File("plugins" + File.separator + "AlathranWars" + File.separator + "userdata");
|
||||
if (!userDataFolder.exists()) {
|
||||
userDataFolder.mkdirs();
|
||||
}
|
||||
|
||||
WarData.setWars(WarData.createWars());
|
||||
}
|
||||
|
||||
public static void initLogs() {
|
||||
File logsFolder = new File("plugins" + File.separator + "AlathranWars" + File.separator + "logs");
|
||||
if (!logsFolder.exists()) {
|
||||
logsFolder.mkdirs();
|
||||
}
|
||||
File log = new File(
|
||||
"plugins" + File.separator + "AlathranWars" + File.separator + "logs" + File.separator + "log.txt");
|
||||
if (!log.exists()) {
|
||||
try {
|
||||
log.createNewFile();
|
||||
} catch (IOException e) {
|
||||
Bukkit.getLogger().warning("[AlathranWars] Encountered error when creating log file!");
|
||||
}
|
||||
}
|
||||
warLogger = new AlathranWarsLogger();
|
||||
}*/
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private boolean setupEconomy() {
|
||||
if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
|
||||
return false;
|
||||
}
|
||||
@SuppressWarnings("unchecked") final RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) this.getServer()
|
||||
.getServicesManager().getRegistration((Class) Economy.class);
|
||||
if (rsp == null) {
|
||||
return false;
|
||||
}
|
||||
econ = rsp.getProvider();
|
||||
return econ != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
Main.instance = this;
|
||||
WarManager.getInstance();
|
||||
configManager = new ConfigManager(getInstance());
|
||||
dataManager = new DataManager(getInstance());
|
||||
commandManager = new CommandManager(getInstance());
|
||||
listenerHandler = new ListenerHandler(getInstance());
|
||||
hookManager = new HookManager();
|
||||
|
||||
configManager.onLoad();
|
||||
dataManager.onLoad();
|
||||
commandManager.onLoad();
|
||||
listenerHandler.onLoad();
|
||||
hookManager.onLoad();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
this.saveDefaultConfig();
|
||||
// initLogs();
|
||||
|
||||
//new WarData(this);
|
||||
// new TimeoutData(this);
|
||||
|
||||
// //run first
|
||||
new WarItemRegistry();
|
||||
// //run second
|
||||
// new WarRecipeRegistry();
|
||||
|
||||
// initData();
|
||||
setupEconomy();
|
||||
// initLogs();
|
||||
|
||||
configManager.onEnable();
|
||||
dataManager.onEnable();
|
||||
commandManager.onEnable();
|
||||
listenerHandler.onEnable();
|
||||
hookManager.onEnable();
|
||||
WarManager.getInstance().loadAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
SQLQueries.saveAll();
|
||||
configManager.onDisable();
|
||||
commandManager.onDisable();
|
||||
listenerHandler.onDisable();
|
||||
hookManager.onDisable();
|
||||
dataManager.onDisable();
|
||||
}
|
||||
|
||||
public ConfigManager getConfigManager() {
|
||||
return configManager;
|
||||
}
|
||||
|
||||
public DataManager getDataManager() {
|
||||
return dataManager;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import dev.jorel.commandapi.CommandAPIBukkitConfig;
|
||||
|
||||
public class CommandManager {
|
||||
private final Main instance;
|
||||
|
||||
public CommandManager(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
CommandAPI.onLoad(new CommandAPIBukkitConfig(instance).shouldHookPaperReload(true).silentLogs(true));
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
CommandAPI.onEnable();
|
||||
|
||||
// Register commands
|
||||
new WarCommand();
|
||||
new SiegeCommand();
|
||||
// new RaidCommand();
|
||||
new AdminCommand();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
CommandAPI.onDisable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.hooks.TownyHook;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownyObject;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.CustomArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CommandUtil {
|
||||
|
||||
/*public Argument<World> customWorldArgument(String nodeName) {
|
||||
|
||||
// Construct our CustomArgument that takes in a String input and returns a World object
|
||||
return new CustomArgument<World, String>(new StringArgument(nodeName), info -> {
|
||||
// Parse the world from our input
|
||||
World world = Bukkit.getWorld(info.input());
|
||||
|
||||
if (world == null) {
|
||||
throw CustomArgumentException.fromMessageBuilder(new MessageBuilder("Unknown world: ").appendArgInput());
|
||||
} else {
|
||||
return world;
|
||||
}
|
||||
}).replaceSuggestions(ArgumentSuggestions.strings(info ->
|
||||
// List of world names on the server
|
||||
Bukkit.getWorlds().stream().map(World::getName).toArray(String[]::new))
|
||||
);
|
||||
}*/
|
||||
|
||||
static public Argument<Nation> customNationArgument(String nodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argNationName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getNation(argNationName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
return TownyAPI.getInstance().getNation(argNationName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> nationNames = TownyHook.getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownArgument(String nodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getTown(argTownName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
return TownyAPI.getInstance().getTown(argTownName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> townNames = TownyHook.getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Nation> customNationNotInWarArgument(String nodeName, String warNodeName, boolean hideNationsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argNationName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getNation(argNationName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
if (!hideNationsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return TownyAPI.getInstance().getNation(argNationName);
|
||||
|
||||
Nation nation = TownyAPI.getInstance().getNation(argNationName);
|
||||
|
||||
if (war.getNations().contains(nation) || war.getSurrenderedNations().contains(nation))
|
||||
return nation;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The nation is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> nationNames = TownyHook.getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final List<String> townNames = TownyHook.getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
nationNames.addAll(townNames);
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideNationsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return nationNames;
|
||||
|
||||
final List<String> removeNames = Stream.concat( // Create a list of all nations in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getSurrenderedNations().stream().map(Nation::getName)
|
||||
).toList();
|
||||
|
||||
nationNames.removeAll(removeNames);
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownNotInWarArgument(String nodeName, String warNodeName, boolean hideTownsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownName = info.input();
|
||||
|
||||
if (TownyAPI.getInstance().getTown(argTownName) == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return TownyAPI.getInstance().getTown(argTownName);
|
||||
|
||||
Town town = TownyAPI.getInstance().getTown(argTownName);
|
||||
|
||||
if (war.getTowns().contains(town) || war.getSurrenderedTowns().contains(town))
|
||||
return town;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> townNames = TownyHook.getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return townNames;
|
||||
|
||||
final List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
).toList();
|
||||
|
||||
townNames.removeAll(removeNames);
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Nation> customNationInWarArgument(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
Nation nation = TownyAPI.getInstance().getNation(info.input());
|
||||
|
||||
if (nation == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isNationInWar(nation))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The nation is not in that war!").parseLegacy().build());
|
||||
|
||||
return nation;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getSurrenderedNations().stream().map(Nation::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<Town> customTownInWarArgument(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
Town town = TownyAPI.getInstance().getTown(info.input());
|
||||
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isTownInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
return town;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Accepts all towns and nations as argument. Returns a string.
|
||||
*
|
||||
* @param nodeName the node name
|
||||
* @param warNodeName the war node name
|
||||
* @param hideTownsInWar the hide towns in war
|
||||
* @return the argument
|
||||
*/
|
||||
static public Argument<String> customTownAndNationsArgument(String nodeName, String warNodeName, boolean hideTownsInWar) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argTownOrNationName = info.input();
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(argTownOrNationName);
|
||||
|
||||
if (town != null)
|
||||
return town.getName();
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(argTownOrNationName);
|
||||
if (nation != null)
|
||||
return nation.getName();
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town or nation does not exist!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> nationNames = TownyHook.getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final List<String> townNames = TownyHook.getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
nationNames.addAll(townNames);
|
||||
|
||||
// Only proceed after this if we want to remove town already in the specified war
|
||||
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return nationNames;
|
||||
|
||||
final List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getSurrenderedNations().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
)
|
||||
)
|
||||
).toList();
|
||||
|
||||
nationNames.removeAll(removeNames);
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}
|
||||
|
||||
/*static public Argument<String> warSideCreateArgument(String nodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argSideName = info.input();
|
||||
|
||||
return argSideName;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<Nation> nations = TownyHook.getNations();
|
||||
final List<Town> towns = TownyHook.getTowns();
|
||||
|
||||
final List<String> nationNames = new ArrayList<>();
|
||||
final List<String> townNames = new ArrayList<>();
|
||||
|
||||
for (Nation nation : nations)
|
||||
nationNames.add(nation.getName());
|
||||
|
||||
for (Town town : towns)
|
||||
townNames.add(town.getName());
|
||||
|
||||
Collections.sort(nationNames);
|
||||
Collections.sort(townNames);
|
||||
nationNames.addAll(townNames);
|
||||
|
||||
return nationNames;
|
||||
}));
|
||||
}*/
|
||||
|
||||
public static Argument<Town> customSiegeAttackableTownArgument(String nodeName, String warNodeName, final boolean checkIfIn, final boolean checkIfSieged) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
|
||||
|
||||
Town town = TownyAPI.getInstance().getTown(info.input());
|
||||
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isTownInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
if (checkIfSieged) {
|
||||
for (War war2 : WarManager.getInstance().getWars()) {
|
||||
for (Siege siege : war2.getSieges()) {
|
||||
if (siege.getTown().getUUID() == town.getUUID())
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The town is already under siege!").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return town;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
final List<String> townNames = new ArrayList<>();
|
||||
|
||||
if (info.sender() instanceof Player p) {
|
||||
if (war.getSide1().isPlayerOnSide(p)) {
|
||||
townNames.addAll(war.getSide2().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
} else if (war.getSide2().isPlayerOnSide(p)) {
|
||||
townNames.addAll(war.getSide1().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return townNames;
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
public static Argument<War> warWarArgument(String nodeName, final boolean isAdmin, final boolean checkIfIn, final String playerNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argWarName = info.input();
|
||||
|
||||
final War war = WarManager.getInstance().getWar(argWarName);
|
||||
if (war == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The war <war> does not exist!").parseLegacy().parseMinimessagePlaceholder("war", argWarName).build());
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (war.isPlayerInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The player is already in that war.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (war.isPlayerInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You are already in this war.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
|
||||
return war;
|
||||
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final List<String> warNames = new ArrayList<>();
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
for (String name : WarManager.getInstance().getWarNames()) {
|
||||
if (WarManager.getInstance().getWar(name) != null && !WarManager.getInstance().getWar(name).isPlayerInWar(player))
|
||||
warNames.add(name);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
for (String name : WarManager.getInstance().getWarNames()) {
|
||||
if (WarManager.getInstance().getWar(name) != null && !WarManager.getInstance().getWar(name).isPlayerInWar(player))
|
||||
warNames.add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warNames.addAll(WarManager.getInstance().getWarNames());
|
||||
}
|
||||
|
||||
return warNames;
|
||||
}));
|
||||
}
|
||||
|
||||
public static Argument<Side> warSideCreateArgument(final String nodeName, final String warNodeName, final boolean isAdmin, final boolean checkIfIn, final String playerNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war.").parseLegacy().build());
|
||||
|
||||
final String argSideName = info.input();
|
||||
|
||||
if (!war.isSideValid(argSideName))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The side does not exist.").parseLegacy().build());
|
||||
|
||||
final Side side = war.getSide(argSideName);
|
||||
|
||||
if (side == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The side is invalid.").parseLegacy().build());
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayers().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>The player is already on that side.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayers().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You are already on that side.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
|
||||
return side;
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
return Collections.emptyList();
|
||||
|
||||
final List<String> sideNames = new ArrayList<>();
|
||||
|
||||
if (checkIfIn) {
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
for (Side side : war.getSides()) {
|
||||
if (!side.getPlayers().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
for (Side side : war.getSides()) {
|
||||
if (!side.getPlayers().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sideNames.add(war.getSide1().getName());
|
||||
sideNames.add(war.getSide2().getName());
|
||||
}
|
||||
|
||||
return sideNames;
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param player player to check
|
||||
* @return 0, 1, 2 (good to go, insufficient join, insufficient playtime)
|
||||
*/
|
||||
public static int isPlayerMinuteman(String player) {
|
||||
Resident res = TownyAPI.getInstance().getResident(player);
|
||||
if (res != null) {
|
||||
//getInstance registration time
|
||||
long regTime = res.getRegistered();
|
||||
int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE);
|
||||
int out = 0;
|
||||
if (Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
|
||||
//compare the join date, if they joined less that min age ago it is true
|
||||
if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge"))
|
||||
out = 1;
|
||||
}
|
||||
if (Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
|
||||
//check playtime, if its less than min its true
|
||||
if (playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
//if the player doesnt exist just return true
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* return list of all alathranwars items with namespace
|
||||
*
|
||||
* @return list of all alathranwars items namespaced
|
||||
*/
|
||||
public static List<String> getWarItems() {
|
||||
return new ArrayList<>(WarItemRegistry.getInstance().getItemRegistry().keySet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.data.DataManager;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class SiegeCommand {
|
||||
public SiegeCommand() {
|
||||
new CommandAPICommand("siege")
|
||||
.withSubcommands(
|
||||
commandStart(),
|
||||
commandStop(),
|
||||
commandAbandon(),
|
||||
commandList(),
|
||||
commandHelp()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "Invalid Arguments. /siege help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStart() {
|
||||
return new CommandAPICommand("start")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
true
|
||||
),
|
||||
new PlayerArgument("leader")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin"),
|
||||
new BooleanArgument("minutemen")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> siegeStart(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandStop() {
|
||||
return new CommandAPICommand("stop")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
false
|
||||
)
|
||||
)
|
||||
.executesPlayer(SiegeCommand::siegeStop);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandAbandon() {
|
||||
return new CommandAPICommand("abandon")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument(
|
||||
"war",
|
||||
false,
|
||||
false,
|
||||
""
|
||||
),
|
||||
CommandUtil.customSiegeAttackableTownArgument(
|
||||
"town",
|
||||
"war",
|
||||
false,
|
||||
false
|
||||
)
|
||||
)
|
||||
.executesPlayer(SiegeCommand::siegeAbandon);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(SiegeCommand::siegeList);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandHelp() {
|
||||
return new CommandAPICommand("help")
|
||||
.executesPlayer(SiegeCommand::siegeHelp);
|
||||
}
|
||||
|
||||
|
||||
protected static void siegeStart(Player sender, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
//if this is admin mode use the forth arg instad of sender.
|
||||
//if player is null after this then force end
|
||||
final Player siegeOwner = (Player) args.getOptional("leader").orElse(sender);
|
||||
|
||||
if (siegeOwner == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("You need to pick a valid leader.").build());
|
||||
|
||||
// Player participance check
|
||||
Town leaderTown = TownyAPI.getInstance().getResident(siegeOwner).getTownOrNull();
|
||||
Side side = war.getTownSide(leaderTown);
|
||||
|
||||
// TODO DEBUG PRINT
|
||||
// Main.warLogger.log("Leader Town: " + leaderTown.getName());
|
||||
// Main.warLogger.log("Siege Owner: " + siegeOwner.getName());
|
||||
// sender.sendMessage("Leader Town: " + leaderTown.getName());
|
||||
// sender.sendMessage("Siege Owner: " + siegeOwner.getName());
|
||||
|
||||
// TODO DEBUG PRINT
|
||||
/*for (String t : war.getSide1Towns()) {
|
||||
Main.warLogger.log("Side1 town: " + t);
|
||||
sender.sendMessage("Side1 town: " + t);
|
||||
}
|
||||
for (String t : war.getSide2Towns()) {
|
||||
Main.warLogger.log("Side2 town: " + t);
|
||||
sender.sendMessage("Side2 town: " + t);
|
||||
}*/
|
||||
|
||||
if (!war.isTownInWar(leaderTown)) {
|
||||
siegeOwner.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You are not in this war.").build());
|
||||
if (admin) sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You are not in this war.").build());
|
||||
return;
|
||||
} else if (side.isTownSurrendered(leaderTown)) {
|
||||
siegeOwner.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You are under occupation.").build());
|
||||
if (admin) sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You are under occupation.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
|
||||
//Minuteman countermeasures
|
||||
/*int minuteman = CommandHelper.isPlayerMinuteman(siegeOwner.getName());
|
||||
boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
|
||||
if (minuteManOverride) {
|
||||
sender.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
}
|
||||
|
||||
//override?
|
||||
if (!minuteManOverride) {
|
||||
if (minuteman != 0) {
|
||||
if (minuteman == 1) {
|
||||
//player has joined to recently
|
||||
if (admin)
|
||||
sender.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
siegeOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
return;
|
||||
} else if (minuteman == 2) {
|
||||
//player has played too little
|
||||
if (admin)
|
||||
sender.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
siegeOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
// Is being raided check
|
||||
/*for (OldRaid r : RaidData.getRaids()) {
|
||||
if (r.getRaidedTown().getName().equalsIgnoreCase(town.getName())) {
|
||||
siegeOwner.sendMessage(UtilsChat.getPrefix() + "That town is already currently being raided! Cannot siege at this time!");
|
||||
if (admin)
|
||||
sender.sendMessage(UtilsChat.getPrefix() + "That town is already currently being raided! Cannot siege at this time!");
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
|
||||
// Attacking own side
|
||||
if (side.isTownOnSide(town)) {
|
||||
siegeOwner.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You cannot attack your own towns.").build());
|
||||
if (admin) sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You cannot attack your own towns.").build());
|
||||
return;
|
||||
}
|
||||
|
||||
Siege siege = new Siege(war, town, siegeOwner);
|
||||
war.addSiege(siege);
|
||||
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + siege.getTown() + " has been put to siege by " + siege.getAttackerSide() + "!").build());
|
||||
|
||||
if (admin)
|
||||
sender.sendMessage(new ColorParser("<red>Forcefully started siege from the console.").build());
|
||||
|
||||
siege.start();
|
||||
// TODO Debug logs...
|
||||
// Main.warLogger.log("Attacked Town: " + town.getName().toLowerCase());
|
||||
// sender.sendMessage("Attacked Town: " + town.getName().toLowerCase());
|
||||
}
|
||||
|
||||
private static void siegeStop(Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
final Set<Siege> sieges = war.getSieges();
|
||||
if (sieges.isEmpty())
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>There are currently no sieges in progress!").build());
|
||||
|
||||
for (Siege siege : sieges) {
|
||||
if (siege.getTown().getUUID().equals(town.getUUID()) && siege.getWar().equals(war)) {
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "siege cancelled.").build());
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The siege at " + siege.getTown().getName() + " has been cancelled by an admin.").build());
|
||||
siege.stop();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "A siege could not be found with this town name! Type /siege list to view current sieges").build());
|
||||
}
|
||||
|
||||
private static void siegeAbandon(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war.").build());
|
||||
|
||||
if (!(args.get("town") instanceof final Town town))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a town.").build());
|
||||
|
||||
Siege siege = null;
|
||||
|
||||
for (Siege siegeVar : war.getSieges()) {
|
||||
if (siegeVar.getTown().getUUID().equals(town.getUUID())) {
|
||||
siege = siegeVar;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (siege == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "Invalid siege").build());
|
||||
|
||||
OfflinePlayer oPlayer = siege.getSiegeLeader();
|
||||
if (oPlayer != p) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You are not the leader of this siege.").build());
|
||||
}
|
||||
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The siege at " + siege.getTown().getName() + " has been abandoned.").build());
|
||||
// Main.warLogger.log(p.getName() + " abandoned the siege they started at " + siege.getTown().getName());
|
||||
siege.defendersWin();
|
||||
}
|
||||
|
||||
private static void siegeList(Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<War> wars = WarManager.getInstance().getWars();
|
||||
|
||||
Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
for (War war : wars) {
|
||||
sieges.addAll(war.getSieges());
|
||||
}
|
||||
|
||||
if (sieges.isEmpty())
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>There are currently no sieges in progress.").build());
|
||||
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Sieges currently in progress:").build());
|
||||
|
||||
for (Siege siege : sieges) {
|
||||
War war = siege.getWar();
|
||||
|
||||
final String color = (siege.getSide1AreAttackers() && (war.getTownSide(siege.getTown()).getTeam().equals(BattleTeam.SIDE_1))) ? "<red>" : "<blue>";
|
||||
|
||||
sender.sendMessage(
|
||||
new ColorParser(
|
||||
color + siege.getTown().getName() + " <gray>- Progress: <progress> - Time: <time>min"
|
||||
)
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(siege.getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now() , siege.getEndTime()).toMinutes()))
|
||||
.build()
|
||||
);
|
||||
// sender.sendMessage(new ColorParser(war.getName() + " - " + color + siege.getTown().getName().toLowerCase()).build()); // TODO Fix info
|
||||
// sender.sendMessage(new ColorParser(war.getSide1() + " - " + (siege.getSide1AreAttackers() ? siege.getAttackerPoints() : siege.getDefenderPoints())).build());
|
||||
// sender.sendMessage(new ColorParser(war.getSide2() + " - " + (siege.getSide1AreAttackers() ? siege.getDefenderPoints() : siege.getAttackerPoints())).build());
|
||||
// sender.sendMessage(new ColorParser("Time Left: " + (siege.getMaxSiegeTicks() - siege.getSiegeTicks()) / 1200 + " minutes").build());
|
||||
// sender.sendMessage(new ColorParser("-=-=-=-=-=-=-=-=-=-=-=-").build());
|
||||
}
|
||||
}
|
||||
|
||||
private static void siegeHelp(Player sender, CommandArguments args) {
|
||||
if (sender.hasPermission("AlathranWars.admin")) {
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/siege stop [war] [town]").build());
|
||||
}
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/siege start [war] [town]").build());
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/siege abandon [war] [town]").build());
|
||||
sender.sendMessage(new ColorParser(UtilsChat.getPrefix() + "/siege list").build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public class WarCommand {
|
||||
public WarCommand() {
|
||||
new CommandAPICommand("war")
|
||||
.withSubcommands(
|
||||
commandCreate(),
|
||||
commandDelete(),
|
||||
commandJoin(),
|
||||
commandSurrender(),
|
||||
commandList(),
|
||||
// commandInfo(),
|
||||
commandHelp()
|
||||
)
|
||||
.executesPlayer((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "Invalid Arguments. /war help").build());
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandCreate() {
|
||||
return new CommandAPICommand("create")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.customTownAndNationsArgument("side1", "war", false),
|
||||
CommandUtil.customTownAndNationsArgument("side2", "war", false),
|
||||
new GreedyStringArgument("warlabel")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> List.of(
|
||||
"Nations War of Conquest",
|
||||
"Nations War for Survival",
|
||||
"Nations War of Liberation"
|
||||
))
|
||||
)
|
||||
)
|
||||
.executesPlayer(WarCommand::warCreate);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandDelete() {
|
||||
return new CommandAPICommand("delete")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, false, "")
|
||||
)
|
||||
.executesPlayer(WarCommand::warDelete);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoin() {
|
||||
return new CommandAPICommand("join")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, true, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", false, true, ""),
|
||||
new PlayerArgument("player").setOptional(true).withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoinPlayer(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandSurrender() {
|
||||
return new CommandAPICommand("surrender")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", false, false, "player"),
|
||||
new PlayerArgument("player")
|
||||
.setOptional(true)
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warSurrender(p, args, false));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandList() {
|
||||
return new CommandAPICommand("list")
|
||||
.executesPlayer(WarCommand::warList);
|
||||
}
|
||||
|
||||
/*public static CommandAPICommand commandInfo() {
|
||||
return new CommandAPICommand("info")
|
||||
.withArguments(
|
||||
new PlayerArgument("player")
|
||||
)
|
||||
.executesPlayer(WarCommand::warInfo);
|
||||
}*/
|
||||
|
||||
public static CommandAPICommand commandHelp() {
|
||||
return new CommandAPICommand("help")
|
||||
.executesPlayer(WarCommand::warHelp);
|
||||
}
|
||||
|
||||
protected static void warCreate(CommandSender p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("warlabel") instanceof final String argLabel))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war label.").build());
|
||||
|
||||
if (Objects.equals(args.get("side1"), args.get("side2")))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Cannot declare war on oneself.").build());
|
||||
|
||||
String townName1 = (String) args.get("side1");
|
||||
String townName2 = (String) args.get("side2");
|
||||
|
||||
// Create new war depending on what argument was specified
|
||||
@Nullable Town town1 = TownyAPI.getInstance().getTown(townName1);
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(townName2);
|
||||
@Nullable Nation nation1 = TownyAPI.getInstance().getNation(townName1);
|
||||
@Nullable Nation nation2 = TownyAPI.getInstance().getNation(townName2);
|
||||
|
||||
// Automatically elevate town wars to nation level if possible (This may be undesirable in terms of allowing civil wars etc)
|
||||
if (town1 != null && town1.getNationOrNull() != null) {
|
||||
nation1 = town1.getNationOrNull();
|
||||
}
|
||||
|
||||
if (town2 != null && town2.getNationOrNull() != null) {
|
||||
nation2 = town2.getNationOrNull();
|
||||
}
|
||||
|
||||
// TODO Ensure side1 valid
|
||||
// TODO Ensure side2 valid
|
||||
// TODO Deep Check if war exists where the same sides are fighting???
|
||||
|
||||
// Create war depending on what args have been passed, attempt to create nation wars first
|
||||
if (nation1 != null) {
|
||||
if (nation2 != null) {
|
||||
new War(argLabel, nation1, nation2);
|
||||
} else if (town2 != null) {
|
||||
new War(argLabel, nation1, town2);
|
||||
}
|
||||
} else if (town1 != null) {
|
||||
if (town2 != null) {
|
||||
new War(argLabel, town1, town2);
|
||||
} else if (nation2 != null) {
|
||||
new War(argLabel, town1, nation2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*for (War war1 : WarManager.getInstance().getWars()) {
|
||||
war.
|
||||
}*/
|
||||
|
||||
|
||||
// Check if side1 is nation or town
|
||||
// Check if side2 is nation or town
|
||||
// Check if opposing factions are already at war?
|
||||
|
||||
/*Main.warLogger.log(p.getName() + " created a new war with the name " + argWarName + ", " + argSide1
|
||||
+ " vs. " + argSide2);*/
|
||||
|
||||
}
|
||||
|
||||
private static void warDelete(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
|
||||
war.draw();
|
||||
// Main.warLogger.log(p.getName() + " deleted " + argWarName);
|
||||
}
|
||||
|
||||
protected static void warJoinPlayer(Player p, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war name.").build());
|
||||
|
||||
if (!(args.get("side") instanceof final Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
if (war.isPlayerInWar(argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You are already in this war.").build());
|
||||
|
||||
argPlayer.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(argPlayer);
|
||||
PlayerJoinListener.checkPlayer(argPlayer);
|
||||
for (Siege siege : war.getSieges()) {
|
||||
if (siege.getAttackerSide().equals(side)) {
|
||||
siege.addPlayer(argPlayer, BattleSide.ATTACKER);
|
||||
} else {
|
||||
siege.addPlayer(argPlayer, BattleSide.DEFENDER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p - executor
|
||||
* @param args
|
||||
* @param admin - admin behavior
|
||||
*/
|
||||
protected static void warJoin(Player p, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("war") instanceof final War war))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a war name.").build());
|
||||
|
||||
if (!(args.get("side") instanceof final Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
// Towny Resident Object, if admin then dont use command runner, use declared player
|
||||
Resident res = TownyAPI.getInstance().getResident(argPlayer);
|
||||
|
||||
// Town check
|
||||
Town town = res.getTownOrNull();
|
||||
if (town == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(ChatColor.RED + "You are not in a town.").build());
|
||||
}
|
||||
|
||||
//Minuteman countermeasures
|
||||
// final int minuteman = CommandHelper.isPlayerMinuteman(argPlayer.getName());
|
||||
// final boolean minuteManOverride = (boolean) args.getOptional("minutemen").orElse(false);
|
||||
//
|
||||
// if (minuteManOverride) {
|
||||
// p.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
|
||||
// }
|
||||
//
|
||||
// //override?
|
||||
// if (!minuteManOverride) {
|
||||
// if (minuteman != 0) {
|
||||
// if (minuteman == 1) {
|
||||
// //player has joined to recently
|
||||
// if (admin)
|
||||
// p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
// argPlayer.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
|
||||
// return;
|
||||
// } else if (minuteman == 2) {
|
||||
// //player has played too little
|
||||
// if (admin)
|
||||
// p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
// argPlayer.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// Side checks
|
||||
if (war.getSurrenderedTowns().contains(town)) {
|
||||
argPlayer.sendMessage(UtilsChat.getPrefix() + "You've already surrendered!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.hasNation()) {
|
||||
if (res.getPlayer().hasPermission("AlathranWars.nationjoin") || res.isKing()) {
|
||||
// Has nation declaration permission
|
||||
side.addNation(res.getNationOrNull());
|
||||
res.getPlayer().sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getNationOrNull().getName());
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getNationOrNull().getName());
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The nation of " + res.getNationOrNull().getName() + " has joined the war on the side of " + side.getName() + "!");
|
||||
} else {
|
||||
// Cannot declare nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You cannot declare war for your nation.").build());
|
||||
}
|
||||
} else if (res.hasTown()) {
|
||||
if (res.getPlayer().hasPermission("AlathranWars.townjoin") || res.isMayor()) {
|
||||
// Is in indepdenent town & has declaration perms
|
||||
side.addTown(res.getTownOrNull());
|
||||
res.getPlayer().sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getTownOrNull().getName());
|
||||
p.sendMessage(UtilsChat.getPrefix() + "You have joined the war for " + res.getTownOrNull().getName());
|
||||
Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The town of " + res.getTownOrNull().getName() + " has joined the war on the side of " + side.getName() + "!");
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You cannot declare war for your town.").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warSurrender(Player p, CommandArguments args, boolean admin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
|
||||
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>Player not found.").build());
|
||||
|
||||
// Towny Resident Object
|
||||
Resident res = TownyAPI.getInstance().getResident(argPlayer);
|
||||
if (res == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("<red>Resident invalid.").build());
|
||||
|
||||
// Town check
|
||||
Town town = res.getTownOrNull();
|
||||
if (town == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("<red>You are not in a town.").build());
|
||||
|
||||
Side side = war.getTownSide(town);
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("<red>You are not in the war.").build());
|
||||
|
||||
final Nation resNation = res.getNationOrNull();
|
||||
final Town resTown = res.getTownOrNull();
|
||||
|
||||
if (resNation != null) {
|
||||
if (p.hasPermission("AlathranWars.nationsurrender") || res.isKing() || admin) {
|
||||
// Has nation surrender permission
|
||||
argPlayer.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
|
||||
side.surrenderNation(resNation);
|
||||
side.processSurrenders();
|
||||
} else {
|
||||
// Cannot surrender nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You cannot surrender war for your nation.").build());
|
||||
}
|
||||
} else if (resTown != null) {
|
||||
if (p.hasPermission("AlathranWars.townsurrender") || res.isMayor() || admin) {
|
||||
// Is in indepdenent town & has surrender perms
|
||||
argPlayer.sendMessage(new ColorParser(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
|
||||
side.surrenderTown(resTown);
|
||||
side.processSurrenders();
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "You cannot surrender war for your town.").build());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void warList(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<War> wars = WarManager.getInstance().getWars();
|
||||
|
||||
if (wars.isEmpty()) {
|
||||
p.sendMessage(new ColorParser("There are no wars at the moment, the world is at peace.").build());
|
||||
} else {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Wars:").build());
|
||||
|
||||
for (War war : wars) {
|
||||
p.sendMessage(new ColorParser(war.getName() + " - " + war.getSide1().getName() + " (" + war.getSide1().getScore() + ") vs. " + war.getSide2().getName() + " (" + war.getSide2().getScore() + ")").build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*private static void warInfo(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (args.count() < 1) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "/war info [Player]").build());
|
||||
}
|
||||
|
||||
if (!(args.get("player") instanceof Player argsPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser("Specify a player.").build());
|
||||
|
||||
Resident res = TownyAPI.getInstance().getResident(argsPlayer);
|
||||
if (res == null || res.getTownOrNull() == null) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "Invalid town resident.").build());
|
||||
}
|
||||
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + p.getName() + "'s wars:").build());
|
||||
for (War war : WarManager.getInstance().getWars()) {
|
||||
TownWarState side = war.getState(res.getTownOrNull());
|
||||
if (side != TownWarState.NOT_PARTICIPANT) {
|
||||
if (side == TownWarState.SURRENDERED) {
|
||||
p.sendMessage(war.getName() + " - Surrendered");
|
||||
} else if (side == TownWarState.SIDE1) {
|
||||
p.sendMessage(war.getName() + " - " + war.getSide1());
|
||||
} else if (side == TownWarState.SIDE2) {
|
||||
p.sendMessage(war.getName() + " - " + war.getSide2());
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
private static void warHelp(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
// TODO
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for console access
|
||||
*
|
||||
* @param sender
|
||||
* @param args
|
||||
*/
|
||||
// private static void consoleCommand(CommandSender sender, CommandArguments args) {
|
||||
// if (args.length < 1) return;
|
||||
// if (args[0].equalsIgnoreCase("list")) {
|
||||
// ArrayList<War> warList = WarManager.getInstance().getWars();
|
||||
// sender.sendMessage("Wars: " + warList.size());
|
||||
// for (War war : WarManager.getInstance().getWars()) {
|
||||
// if (war == null) continue;
|
||||
// sender.sendMessage(war.toString());
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
public class Conflict {
|
||||
private ConflictType conflictType;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
public enum ConflictType {
|
||||
WAR
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Side {
|
||||
private final UUID warUUID;
|
||||
private final UUID uuid;
|
||||
private final BattleSide side;
|
||||
private final BattleTeam team;
|
||||
private final String name; // A town name
|
||||
|
||||
// TODO Use Town & Nation UUID's when saving to config
|
||||
private final Town town; // The initiating town or capital of the nation
|
||||
private final Set<Town> towns; // A list of participating Towns
|
||||
private final Set<Nation> nations; // A list of participating Nations
|
||||
private final Set<UUID> playersIncludingOffline; // A list of all participating player UUID, (Online & Offline)
|
||||
private final Set<Player> players; // A list of the players who are currently online
|
||||
|
||||
private final Set<Town> surrenderedTowns;
|
||||
private final Set<Nation> surrenderedNations;
|
||||
private final Set<UUID> surrenderedPlayersIncludingOffline;
|
||||
|
||||
private static final Duration SIEGE_COOLDOWN = Duration.ofMinutes(120);
|
||||
private static final Duration RAID_COOLDOWN = Duration.ofMinutes(30);
|
||||
private Instant siegeGrace = Instant.now().minus(SIEGE_COOLDOWN); // The time after which this side can be besieged
|
||||
private Instant raidGrace = Instant.now().minus(RAID_COOLDOWN); // The time after which this side can be raided
|
||||
|
||||
private int score = 0;
|
||||
|
||||
// Create object from DB
|
||||
public Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Town town,
|
||||
BattleSide side,
|
||||
BattleTeam team,
|
||||
String name,
|
||||
Set<Town> towns,
|
||||
Set<Nation> nations,
|
||||
Set<UUID> playersIncludingOffline,
|
||||
Set<Town> surrenderedTowns,
|
||||
Set<Nation> surrenderedNations,
|
||||
Set<UUID> surrenderedPlayersIncludingOffline,
|
||||
Instant siegeGrace,
|
||||
Instant raidGrace
|
||||
) {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = town;
|
||||
this.name = name;
|
||||
|
||||
this.towns = towns;
|
||||
this.nations = nations;
|
||||
this.playersIncludingOffline = playersIncludingOffline;
|
||||
this.players = new HashSet<>();
|
||||
|
||||
this.surrenderedTowns = surrenderedTowns;
|
||||
this.surrenderedNations = surrenderedNations;
|
||||
this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
|
||||
|
||||
this.siegeGrace = siegeGrace;
|
||||
this.raidGrace = raidGrace;
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public Side(UUID warUUID, UUID uuid, Town town, BattleSide side, BattleTeam team) {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = town;
|
||||
this.name = this.town.getName();
|
||||
|
||||
this.towns = new HashSet<>();
|
||||
this.nations = new HashSet<>();
|
||||
this.playersIncludingOffline = new HashSet<>();
|
||||
this.players = new HashSet<>();
|
||||
|
||||
this.surrenderedTowns = new HashSet<>();
|
||||
this.surrenderedNations = new HashSet<>();
|
||||
this.surrenderedPlayersIncludingOffline = new HashSet<>();
|
||||
|
||||
addTown(this.town);
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public Side(UUID warUUID, UUID uuid, Nation nation, BattleSide side, BattleTeam team) {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = nation.getCapital();
|
||||
this.name = this.town.getName();
|
||||
|
||||
this.towns = new HashSet<>();
|
||||
this.nations = new HashSet<>();
|
||||
this.playersIncludingOffline = new HashSet<>();
|
||||
this.players = new HashSet<>();
|
||||
|
||||
this.surrenderedTowns = new HashSet<>();
|
||||
this.surrenderedNations = new HashSet<>();
|
||||
this.surrenderedPlayersIncludingOffline = new HashSet<>();
|
||||
|
||||
addNation(nation);
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public BattleSide getSide() {
|
||||
return side;
|
||||
}
|
||||
|
||||
public BattleTeam getTeam() {
|
||||
return team;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Set<Nation> getNations() {
|
||||
return nations;
|
||||
}
|
||||
|
||||
public Set<Town> getTowns() {
|
||||
return towns;
|
||||
}
|
||||
|
||||
public Set<UUID> getPlayersIncludingOffline() {
|
||||
return playersIncludingOffline;
|
||||
}
|
||||
|
||||
public Set<Player> getPlayers() {
|
||||
return players;
|
||||
}
|
||||
|
||||
public Set<Town> getSurrenderedTowns() {
|
||||
return surrenderedTowns;
|
||||
}
|
||||
|
||||
public Set<Nation> getSurrenderedNations() {
|
||||
return surrenderedNations;
|
||||
}
|
||||
|
||||
public Set<UUID> getSurrenderedPlayersIncludingOffline() {
|
||||
return surrenderedPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
// Participant management
|
||||
|
||||
public boolean isTownOnSide(Town town) {
|
||||
return towns.contains(town) || surrenderedTowns.contains(town);
|
||||
}
|
||||
|
||||
public boolean isNationOnSide(Nation nation) {
|
||||
return nations.contains(nation) || surrenderedNations.contains(nation);
|
||||
}
|
||||
|
||||
public boolean isTownSurrendered(Town town) {
|
||||
return surrenderedTowns.contains(town);
|
||||
}
|
||||
|
||||
public boolean isNationSurrendered(Nation nation) {
|
||||
return surrenderedNations.contains(nation);
|
||||
}
|
||||
|
||||
public void addTown(Town town) {
|
||||
if (isTownOnSide(town)) return;
|
||||
|
||||
towns.add(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> addPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void addNation(Nation nation) {
|
||||
if (isNationOnSide(nation)) return;
|
||||
|
||||
nations.add(nation);
|
||||
|
||||
nation.getTowns().forEach(this::addTown);
|
||||
}
|
||||
|
||||
public void removeTown(Town town) {
|
||||
if (!isTownOnSide(town)) return;
|
||||
|
||||
towns.remove(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> removePlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void removeNation(Nation nation) {
|
||||
if (!isNationOnSide(nation)) return;
|
||||
|
||||
nations.remove(nation);
|
||||
|
||||
nation.getTowns().forEach(this::removeTown);
|
||||
}
|
||||
|
||||
public void surrenderTown(Town town) {
|
||||
if (isTownSurrendered(town)) return;
|
||||
|
||||
removeTown(town);
|
||||
|
||||
surrenderedTowns.add(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> surrenderPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void surrenderNation(Nation nation) {
|
||||
if (isNationSurrendered(nation)) return;
|
||||
|
||||
removeNation(nation);
|
||||
|
||||
surrenderedNations.add(nation);
|
||||
|
||||
nation.getTowns().forEach(this::surrenderTown);
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(Player p) {
|
||||
return isPlayerOnSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(UUID uuid) {
|
||||
return playersIncludingOffline.contains(uuid) || surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerSurrendered(Player p) {
|
||||
return isPlayerSurrendered(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerSurrendered(UUID uuid) {
|
||||
return surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public void addPlayer(Player p) {
|
||||
addPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(UUID uuid) {
|
||||
if (isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.add(uuid);
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final Player p = Bukkit.getPlayer(uuid);
|
||||
addOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOnlinePlayer(Player p) {
|
||||
players.add(p);
|
||||
}
|
||||
|
||||
public void removePlayer(Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(UUID uuid) {
|
||||
if (!isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.remove(uuid);
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final Player p = Bukkit.getPlayer(uuid);
|
||||
removeOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p) {
|
||||
players.remove(p);
|
||||
}
|
||||
|
||||
public void surrenderPlayer(Player p) {
|
||||
surrenderPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void surrenderPlayer(UUID uuid) {
|
||||
if (isPlayerSurrendered(uuid)) return;
|
||||
|
||||
removePlayer(uuid);
|
||||
surrenderedPlayersIncludingOffline.add(uuid);
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final Set<Player> onlinePlayers = getPlayersIncludingOffline().stream()
|
||||
.filter(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
this.players.clear();
|
||||
this.players.addAll(onlinePlayers);
|
||||
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void applyNameTags() {
|
||||
players.forEach(PlayerJoinListener::checkPlayer);
|
||||
surrenderedPlayersIncludingOffline.stream()
|
||||
.filter((UUID uuid) -> Bukkit.getPlayer(uuid) != null)
|
||||
.map(Bukkit::getPlayer)
|
||||
.toList()
|
||||
.forEach(PlayerJoinListener::checkPlayer);
|
||||
}
|
||||
|
||||
// Graces
|
||||
|
||||
public Instant getSiegeGrace() {
|
||||
return this.siegeGrace;
|
||||
}
|
||||
|
||||
public void setSiegeGrace() {
|
||||
this.siegeGrace = Instant.now().plus(SIEGE_COOLDOWN);
|
||||
}
|
||||
|
||||
public boolean isSiegeGraceActive() {
|
||||
return this.siegeGrace.isAfter(Instant.now());
|
||||
}
|
||||
|
||||
public Duration getSiegeGraceCooldown() {
|
||||
return Duration.between(Instant.now(), this.siegeGrace);
|
||||
}
|
||||
|
||||
public Instant getRaidGrace() {
|
||||
return this.raidGrace;
|
||||
}
|
||||
|
||||
public void setRaidGrace() {
|
||||
this.raidGrace = Instant.now().plus(RAID_COOLDOWN);
|
||||
}
|
||||
|
||||
public boolean isRaidGraceActive() {
|
||||
return this.raidGrace.isAfter(Instant.now());
|
||||
}
|
||||
|
||||
public Duration getRaidGraceCooldown() {
|
||||
return Duration.between(Instant.now(), this.raidGrace);
|
||||
}
|
||||
|
||||
// Score
|
||||
|
||||
public int getScore() {
|
||||
return score;
|
||||
}
|
||||
|
||||
public void setScore(int score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public void addScore(int add) {
|
||||
this.score += add;
|
||||
}
|
||||
|
||||
// Comparators & UUID
|
||||
|
||||
public boolean equals(UUID uuid) {
|
||||
return this.uuid.equals(uuid);
|
||||
}
|
||||
|
||||
public boolean equals(War war) {
|
||||
return this.warUUID.equals(war.getUUID());
|
||||
}
|
||||
|
||||
public boolean equals(Side side) {
|
||||
return getUUID().equals(side.getUUID());
|
||||
}
|
||||
|
||||
public boolean equals(String sideName) {
|
||||
return this.name.equals(sideName);
|
||||
}
|
||||
|
||||
public UUID getUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@SuppressWarnings({"all"})
|
||||
public War getWar() {
|
||||
return WarManager.getInstance().getWar(warUUID); // The war must exist, or this object wouldn't
|
||||
}
|
||||
|
||||
public void processSurrenders() {
|
||||
if (shouldSurrender())
|
||||
surrenderWar();
|
||||
}
|
||||
|
||||
private void surrenderWar() {
|
||||
getWar().defeat(this);
|
||||
}
|
||||
|
||||
private boolean shouldSurrender() {
|
||||
return nations.isEmpty() && towns.isEmpty();
|
||||
}
|
||||
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
// TODO Make object serializable
|
||||
/*private void writeObject(ObjectOutputStream oos)
|
||||
throws IOException {
|
||||
oos.defaultWriteObject();
|
||||
oos.writeObject(address.getHouseNumber());
|
||||
}
|
||||
|
||||
private void readObject(ObjectInputStream ois)
|
||||
throws ClassNotFoundException, IOException {
|
||||
ois.defaultReadObject();
|
||||
Integer houseNumber = (Integer) ois.readObject();
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(houseNumber);
|
||||
this.setAddress(a);
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.github.alathra.AlathranWars.utility.UUIDUtil;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The type New war.
|
||||
*/
|
||||
public class War extends Conflict {
|
||||
private final UUID uuid;
|
||||
private final String name; // Used in commands and such, like "TidalHaven.vs.Meme"
|
||||
private final String label;
|
||||
private final ConflictType conflictType = ConflictType.WAR;
|
||||
|
||||
private final Side side1;
|
||||
private final Side side2;
|
||||
private final Side attacker; // Reference variable to side1 or side2
|
||||
private final Side defender; // Reference variable to side1 or side2
|
||||
|
||||
private Set<Siege> sieges = new HashSet<>();
|
||||
private Set<Raid> raids = new HashSet<>();
|
||||
|
||||
public War(
|
||||
UUID uuid,
|
||||
String name,
|
||||
String label,
|
||||
Side side1,
|
||||
Side side2,
|
||||
Set<Siege> sieges,
|
||||
Set<Raid> raids
|
||||
) {
|
||||
this.uuid = uuid;
|
||||
this.name = name;
|
||||
this.label = label;
|
||||
|
||||
this.side1 = side1;
|
||||
this.side2 = side2;
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
this.sieges = sieges;
|
||||
this.raids = raids;
|
||||
|
||||
resume();
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new New war.
|
||||
*
|
||||
* @param label the name
|
||||
* @param aggressor the side 1
|
||||
* @param victim the side 2
|
||||
*/
|
||||
public War(final String label, Town aggressor, Town victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, Nation aggressor, Nation victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, Town aggressor, Nation victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, Nation aggressor, Town victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(new ColorParser(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets uuid.
|
||||
*
|
||||
* @return the uuid
|
||||
*/
|
||||
public UUID getUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets name.
|
||||
*
|
||||
* @return the name
|
||||
*/
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(UUID uuid) {
|
||||
return this.uuid.equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param war the war
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(War war) {
|
||||
return this.uuid.equals(war.getUUID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param warName the war name
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(String warName) {
|
||||
return this.name.equals(warName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side 1.
|
||||
*
|
||||
* @return the side 1
|
||||
*/
|
||||
@NotNull
|
||||
public Side getSide1() {
|
||||
return side1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side 2.
|
||||
*
|
||||
* @return the side 2
|
||||
*/
|
||||
@NotNull
|
||||
public Side getSide2() {
|
||||
return side2;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Side> getSides() {
|
||||
final Set<Side> sides = new HashSet<>();
|
||||
sides.add(getSide1());
|
||||
sides.add(getSide2());
|
||||
return sides;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker.
|
||||
*
|
||||
* @return the attacker
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttacker() {
|
||||
return attacker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender.
|
||||
*
|
||||
* @return the defender
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefender() {
|
||||
return defender;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getSide(String name) {
|
||||
if (getSide1().equals(name))
|
||||
return getSide1();
|
||||
|
||||
if (getSide2().equals(name))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
if (getSide1().equals(uuid))
|
||||
return getSide1();
|
||||
|
||||
if (getSide2().equals(uuid))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sieges.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
return sieges;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
for (Siege siege : sieges) {
|
||||
if (siege.equals(uuid))
|
||||
return siege;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add siege.
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
public void addSiege(Siege siege) {
|
||||
sieges.add(siege);
|
||||
}
|
||||
|
||||
public void removeSiege(Siege siege) {
|
||||
sieges.remove(siege);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets raids.
|
||||
*
|
||||
* @return the raids
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
return raids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add raid.
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
public void addRaid(Raid raid) {
|
||||
raids.add(raid);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getPlayers() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayers().stream(),
|
||||
getSide2().getPlayers().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getPlayersIncludingOffline() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
|
||||
getSide2().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getSurrenderedPlayers() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
|
||||
getSide2().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public boolean isPlayerInWar(Player p) {
|
||||
return side1.isPlayerOnSide(p) || side2.isPlayerOnSide(p);
|
||||
}
|
||||
|
||||
public boolean isPlayerInWar(UUID uuid) {
|
||||
return side1.isPlayerOnSide(uuid) || side2.isPlayerOnSide(uuid);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getPlayerSide(Player p) {
|
||||
if (side1.isPlayerOnSide(p))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isPlayerOnSide(p))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getPlayerSide(UUID uuid) {
|
||||
if (side1.isPlayerOnSide(uuid))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isPlayerOnSide(uuid))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isTownInWar(Town town) {
|
||||
return side1.isTownOnSide(town) || side2.isTownOnSide(town);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getTownSide(Town town) {
|
||||
if (side1.isTownOnSide(town))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isTownOnSide(town))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isNationInWar(Nation nation) {
|
||||
return side1.isNationOnSide(nation) || side2.isNationOnSide(nation);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getNationSide(Nation nation) {
|
||||
if (side1.isNationOnSide(nation))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isNationOnSide(nation))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isSideValid(String sideName) {
|
||||
return getSide1().equals(sideName) || getSide2().equals(sideName);
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Town> getTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
getSide2().getTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Nation> getNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getNations().stream(),
|
||||
getSide2().getNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Town> getSurrenderedTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedTowns().stream(),
|
||||
getSide2().getSurrenderedTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Nation> getSurrenderedNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedNations().stream(),
|
||||
getSide2().getSurrenderedNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public void start() {
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The war of <war> has started between <attacker> and <defender>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.parseMinimessagePlaceholder("attacker", getAttacker().getName())
|
||||
.parseMinimessagePlaceholder("defender", getDefender().getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
side1.applyNameTags();
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
public void resume() {
|
||||
side1.applyNameTags();
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
public void end() {
|
||||
// TODO Stop battles
|
||||
getSieges().forEach(Siege::stop);
|
||||
// getRaids().forEach(Raid::stop);
|
||||
|
||||
SQLQueries.deleteWar(this);
|
||||
WarManager.getInstance().removeWar(this);
|
||||
|
||||
// Run check after war is removed to cleanup player tags
|
||||
this.getPlayers().forEach(PlayerJoinListener::checkPlayer);
|
||||
}
|
||||
|
||||
public void defeat(Side loserSide) {
|
||||
Side loser = loserSide.equals(getSide1()) ? getSide1() : getSide2();
|
||||
Side winner = loserSide.equals(getSide1()) ? getSide2() : getSide1();
|
||||
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The war of <war> has ended. <red><winner> <reset>has triumphed against <red><loser><reset>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.parseMinimessagePlaceholder("winner", winner.getName())
|
||||
.parseMinimessagePlaceholder("loser", loser.getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
end();
|
||||
}
|
||||
|
||||
// White defeat/force end war
|
||||
public void draw() {
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The war of <war> has ended with a white peace.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.build()
|
||||
);
|
||||
|
||||
end();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle;
|
||||
|
||||
public class Battle {
|
||||
/*private int attackerPoints;
|
||||
private int defenderPoints;
|
||||
|
||||
public int getAttackerPoints() {
|
||||
return this.attackerPoints;
|
||||
}
|
||||
|
||||
public void setAttackerPoints(int points) {
|
||||
this.attackerPoints = points;
|
||||
}
|
||||
|
||||
public int getDefenderPoints() {
|
||||
return this.defenderPoints;
|
||||
}
|
||||
|
||||
public void setDefenderPoints(int points) {
|
||||
this.defenderPoints = points;
|
||||
}
|
||||
|
||||
public void addPointsToAttackers(final int points) {
|
||||
this.attackerPoints += points;
|
||||
}
|
||||
|
||||
public void addPointsToDefenders(final int points) {
|
||||
this.defenderPoints += points;
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.Battle;
|
||||
|
||||
public class Raid extends Battle {
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.siege;
|
||||
|
||||
public enum CaptureProgressDirection {
|
||||
UP,
|
||||
NONE,
|
||||
UNCONTESTED,
|
||||
DOWN
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.Battle;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.github.alathra.AlathranWars.utility.UUIDUtil;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import net.kyori.adventure.bossbar.BossBar;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Siege extends Battle {
|
||||
public static final int MAX_SIEGE_TICKS = 72000; // 60 minute tick constant
|
||||
public static final Duration SIEGE_DURATION = Duration.ofMinutes(60);
|
||||
private static final int MAX_SIEGE_PROGRESS_MINUTES = 8;
|
||||
public static final int MAX_SIEGE_PROGRESS = 60 * MAX_SIEGE_PROGRESS_MINUTES; // On reaching this, the attackers win. 1 point is added per second
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofMinutes(2); // If point is not touched in this much time, siege progress reverts
|
||||
public static final int BATTLEFIELD_RANGE = 300;
|
||||
|
||||
private final UUID uuid;
|
||||
private final Set<Player> attackers = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> defenders = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> attackerPlayers = new HashSet<>();
|
||||
private final Set<Player> defenderPlayers = new HashSet<>();
|
||||
private final Set<UUID> attackerPlayersIncludingOffline = new HashSet<>();
|
||||
private final Set<UUID> defenderPlayersIncludingOffline = new HashSet<>();
|
||||
|
||||
private Instant endTime;
|
||||
private int siegeProgress = 0;
|
||||
private Instant lastTouched;
|
||||
|
||||
private SiegeRunnable siegeRunnable;
|
||||
|
||||
private War war; // War which siege belongs to
|
||||
private Town town; // Town of the siege
|
||||
private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
|
||||
private OfflinePlayer siegeLeader;
|
||||
private @Nullable TownBlock homeBlock = null;
|
||||
private @Nullable Location townSpawn = null;
|
||||
private @Nullable BossBar activeBossBar = null;
|
||||
|
||||
public Siege(final War war, final Town town, Player siegeLeader) {
|
||||
uuid = UUIDUtil.generateSiegeUUID();
|
||||
|
||||
endTime = Instant.now().plus(SIEGE_DURATION);
|
||||
lastTouched = Instant.now();
|
||||
|
||||
this.war = war;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
|
||||
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
if (getSide1AreAttackers()) {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
} else {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
}
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a siege
|
||||
*/
|
||||
public void start() {
|
||||
siegeRunnable = new SiegeRunnable(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a siege (after a server restart e.t.c.)
|
||||
*/
|
||||
public void resume(int resumeTick) {
|
||||
siegeRunnable = new SiegeRunnable(this, resumeTick);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a siege
|
||||
*/
|
||||
public void stop() {
|
||||
siegeRunnable.cancel();
|
||||
SQLQueries.deleteSiege(this);
|
||||
war.removeSiege(this);
|
||||
}
|
||||
|
||||
public void attackersWin(final OfflinePlayer siegeLeader) {
|
||||
final Resident resident = TownyAPI.getInstance().getResident(siegeLeader.getUniqueId());
|
||||
Nation nation = null;
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The attackers have won the siege of " + town.getName() + "!").build());
|
||||
|
||||
try {
|
||||
nation = resident.getTown().getNation();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
if (nation != null) {
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The town of " + town.getName()
|
||||
+ " has been placed under occupation by " + nation.getName() + "!").build());
|
||||
}
|
||||
|
||||
// Main.econ.depositPlayer(siegeLeader, 2500.0);
|
||||
// double amt = 0.0;
|
||||
// if (this.town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
// amt = Math.floor(this.town.getAccount().getHoldingBalance()) / 4.0;
|
||||
// this.town.getAccount().withdraw(amt, "war loot");
|
||||
// } else {
|
||||
// if (this.town.getAccount().getHoldingBalance() < 2500.0) {
|
||||
// amt = this.town.getAccount().getHoldingBalance();
|
||||
// Bukkit.broadcastMessage(UtilsChat.getPrefix() + "The town of " + this.town.getName()
|
||||
// + " has been destroyed by " + this.getAttackerSide() + "!");
|
||||
// TownyUniverse.getInstance().getDataSource().deleteTown(this.town);
|
||||
// Main.econ.depositPlayer(siegeLeader, amt);
|
||||
// return;
|
||||
// }
|
||||
// this.town.getAccount().withdraw(2500.0, "war loot");
|
||||
// amt = 2500.0;
|
||||
// }
|
||||
|
||||
/*Bukkit.broadcastMessage("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
|
||||
+ ", valuing $" + amt);*/
|
||||
Bukkit.broadcast(new ColorParser("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide().getName() + "!").build());
|
||||
// Main.warLogger.log("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
|
||||
// + ", valuing $" + amt);
|
||||
// Main.econ.depositPlayer(siegeLeader, amt);
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide1().addScore(50);
|
||||
} else {
|
||||
war.getSide2().addScore(50);
|
||||
}
|
||||
|
||||
stop();
|
||||
//clearBeacon();
|
||||
}
|
||||
|
||||
public void defendersWin() {
|
||||
// this.town.getAccount().deposit(2500.0, "War chest");
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The defenders have won the siege of " + this.town.getName() + "!").build());
|
||||
// Bukkit.broadcastMessage(UtilsChat.getPrefix() + this.town.getName()
|
||||
// + " has recovered the attackers' war chest, valued at $2,500");
|
||||
// Main.warLogger
|
||||
// .log(war.getName() + ": The defenders have won the siege of " + this.town.getName() + "!");
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide2().addScore(50);
|
||||
} else {
|
||||
war.getSide1().addScore(50);
|
||||
}
|
||||
|
||||
stop();
|
||||
//clearBeacon();
|
||||
}
|
||||
|
||||
/**
|
||||
* No winner declared
|
||||
*/
|
||||
public void noWinner() {
|
||||
Bukkit.broadcast(new ColorParser(UtilsChat.getPrefix() + "The siege of " + this.town.getName() + " has ended in a draw!").build());
|
||||
// Bukkit.broadcastMessage(UtilsChat.getPrefix() + "No money has been recovered.");
|
||||
// Main.warLogger
|
||||
// .log(war.getName() + ": No one won the siege of " + this.town.getName() + "!");
|
||||
stop();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Instant getLastTouched() {
|
||||
return lastTouched;
|
||||
}
|
||||
|
||||
public void setLastTouched(Instant lastTouched) {
|
||||
this.lastTouched = lastTouched;
|
||||
}
|
||||
|
||||
public int getSiegeProgress() {
|
||||
return siegeProgress;
|
||||
}
|
||||
|
||||
public float getSiegeProgressPercentage() {
|
||||
return (getSiegeProgress() * 1.0f) / MAX_SIEGE_PROGRESS;
|
||||
}
|
||||
|
||||
public void setSiegeProgress(int siegeProgress) {
|
||||
this.siegeProgress = siegeProgress;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public void setWar(final War war) {
|
||||
this.war = war;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
public void setTown(final Town town) {
|
||||
this.town = town;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttackerSide() {
|
||||
return side1AreAttackers ? war.getSide1() : war.getSide2();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefenderSide() {
|
||||
return side1AreAttackers ? war.getSide2() : war.getSide1();
|
||||
}
|
||||
|
||||
public void updateDisplayBar(CaptureProgressDirection progressDirection) {
|
||||
if (activeBossBar == null)
|
||||
createNewDisplayBar();
|
||||
|
||||
/*for (BossBarViewer viewer : activeBossBar.viewers()) { // TODO Better perf
|
||||
|
||||
}*/
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
activeBossBar.removeViewer(p);
|
||||
}
|
||||
|
||||
for (Player p : this.getAttackers()) {
|
||||
if (p != null)
|
||||
p.showBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
for (Player p : this.getDefenders()) {
|
||||
if (p != null)
|
||||
p.showBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
String color = "<yellow>";
|
||||
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
color = "<red>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
color = "<blue>";
|
||||
}
|
||||
}
|
||||
case NONE -> activeBossBar.color(BossBar.Color.YELLOW);
|
||||
case DOWN -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
color = "<blue>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
color = "<red>";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Instant.now().isBefore(getEndTime())) {
|
||||
activeBossBar.name(
|
||||
new ColorParser("<gray>Capture Progress: %s<progress> <gray>Time: %s<time>min".formatted(color, color))
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now() , getEndTime()).toMinutes()))
|
||||
.build()
|
||||
);
|
||||
} else {
|
||||
activeBossBar.name(
|
||||
new ColorParser("%sOVERTIME".formatted(color)).build()
|
||||
);
|
||||
}
|
||||
activeBossBar.progress(getSiegeProgressPercentage());
|
||||
}
|
||||
|
||||
public void createNewDisplayBar() {
|
||||
final Component text = new ColorParser("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now() , getEndTime()).toMinutesPart()))
|
||||
.build();
|
||||
|
||||
this.activeBossBar = BossBar.bossBar(text, 0, BossBar.Color.YELLOW, BossBar.Overlay.NOTCHED_10);
|
||||
}
|
||||
|
||||
public void deleteDisplayBar() {
|
||||
if (activeBossBar != null) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
activeBossBar.removeViewer(p);
|
||||
}
|
||||
|
||||
activeBossBar = null;
|
||||
}
|
||||
}
|
||||
|
||||
// SECTION UUID
|
||||
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param siege the siege
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(Siege siege) {
|
||||
return getUUID().equals(siege.getUUID());
|
||||
}
|
||||
|
||||
// Accessors & Getters
|
||||
|
||||
@Nullable
|
||||
public TownBlock getHomeBlock() {
|
||||
return homeBlock;
|
||||
}
|
||||
|
||||
public void setHomeBlock(TownBlock homeBlock) {
|
||||
this.homeBlock = homeBlock;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Location getTownSpawn() {
|
||||
return townSpawn;
|
||||
}
|
||||
|
||||
public void setTownSpawn(Location townSpawn) {
|
||||
this.townSpawn = townSpawn;
|
||||
}
|
||||
|
||||
public boolean getSide1AreAttackers() {
|
||||
return this.side1AreAttackers;
|
||||
}
|
||||
|
||||
public void setSide1AreAttackers(final boolean side1AreAttackers) {
|
||||
this.side1AreAttackers = side1AreAttackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackers() {
|
||||
return this.attackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenders() {
|
||||
return this.defenders;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackerPlayers() {
|
||||
return this.attackerPlayers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenderPlayers() {
|
||||
return this.defenderPlayers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public OfflinePlayer getSiegeLeader() {
|
||||
return siegeLeader;
|
||||
}
|
||||
|
||||
public void setSiegeLeader(OfflinePlayer siegeLeader) {
|
||||
this.siegeLeader = siegeLeader;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() {
|
||||
return this.getWar().getName() + "-" + this.getTown();
|
||||
}
|
||||
|
||||
// SECTION Time management
|
||||
|
||||
public void setEndTime(Instant time) {
|
||||
endTime = time;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Instant getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
// SECTION Player management
|
||||
|
||||
public boolean isPlayerInSiege(UUID uuid) {
|
||||
return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerInSiege(Player p) {
|
||||
return isPlayerInSiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public BattleSide getPlayerSideInSiege(UUID uuid) {
|
||||
if (attackerPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.ATTACKER;
|
||||
|
||||
if (defenderPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.DEFENDER;
|
||||
|
||||
return BattleSide.SPECTATOR;
|
||||
}
|
||||
|
||||
public BattleSide getPlayerSideInSiege(Player p) {
|
||||
return getPlayerSideInSiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(Player p, BattleSide side) {
|
||||
addPlayer(p.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(OfflinePlayer offlinePlayer, BattleSide side) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(UUID uuid, BattleSide side) {
|
||||
if (isPlayerInSiege(uuid)) return;
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final Player p = Bukkit.getPlayer(uuid);
|
||||
addOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOnlinePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.add(p);
|
||||
case DEFENDER -> defenderPlayers.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlayer(Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(UUID uuid) {
|
||||
if (!isPlayerInSiege(uuid)) return;
|
||||
|
||||
final BattleSide side = getPlayerSideInSiege(uuid);
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final Player p = Bukkit.getPlayer(uuid);
|
||||
removeOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.remove(p);
|
||||
case DEFENDER -> defenderPlayers.remove(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackerPlayers.clear();
|
||||
attackerPlayers.addAll(onlineAttackers);
|
||||
|
||||
final Set<Player> onlineDefenders = defenderPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenderPlayers.clear();
|
||||
defenderPlayers.addAll(onlineDefenders);
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(Location location) {
|
||||
final Set<Player> attackersOnBattlefield = attackerPlayers.stream()
|
||||
.filter(p -> p.isOnline() && location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackers.clear();
|
||||
attackers.addAll(attackersOnBattlefield);
|
||||
|
||||
final Set<Player> defendersOnBattlefield = defenderPlayers.stream()
|
||||
.filter(p -> p.isOnline() && location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenders.clear();
|
||||
defenders.addAll(defendersOnBattlefield);
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import fr.skytasul.guardianbeam.Laser;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.AlathranWars.conflict.battle.siege.Siege.*;
|
||||
|
||||
public class SiegeRunnable implements Runnable{
|
||||
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
|
||||
|
||||
private CaptureProgressDirection oldProgressDirection = CaptureProgressDirection.NONE;
|
||||
private Instant nextAnnouncement;
|
||||
private int taskId = -1;
|
||||
private final Siege siege;
|
||||
private Laser beam;
|
||||
|
||||
/**
|
||||
* Start a siege
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
public SiegeRunnable(Siege siege) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.setSiegeProgress(0);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
taskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CaptureProgressDirection.NONE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a siege at tick
|
||||
*
|
||||
* @param siege the siege
|
||||
* @param siegeProgress the siege ticks
|
||||
*/
|
||||
public SiegeRunnable(Siege siege, int siegeProgress) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.setSiegeProgress(siegeProgress);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
taskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CaptureProgressDirection.NONE);
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
stopBeam();
|
||||
if (taskId == -1) return;
|
||||
|
||||
try {
|
||||
Bukkit.getServer().getScheduler().cancelTask(taskId);
|
||||
siege.deleteDisplayBar();
|
||||
} finally {
|
||||
taskId = -1;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final Town town = siege.getTown();
|
||||
final TownBlock homeBlock = siege.getHomeBlock();
|
||||
final Location townSpawn = siege.getTownSpawn();
|
||||
|
||||
if (homeBlock != null && townSpawn != null) {
|
||||
town.setHomeBlock(homeBlock);
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
|
||||
// Render beam
|
||||
startBeam();
|
||||
|
||||
// Calculate battlefield players
|
||||
siege.calculateBattlefieldPlayers(townSpawn.toCenterLocation());
|
||||
|
||||
// Progress the siege
|
||||
final CaptureProgressDirection progressDirection = getSiegeProgressDirection(town, townSpawn);
|
||||
|
||||
// Siege is past max time or attackers haven't touched in time, defenders won
|
||||
if (
|
||||
!progressDirection.equals(CaptureProgressDirection.UP) &&
|
||||
(Instant.now().isAfter(siege.getEndTime()) ||
|
||||
Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
|
||||
) {
|
||||
cancel();
|
||||
siege.defendersWin();
|
||||
return;
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (siege.getSiegeProgress() >= MAX_SIEGE_PROGRESS) {
|
||||
cancel();
|
||||
siege.attackersWin(siege.getSiegeLeader());
|
||||
return;
|
||||
}
|
||||
|
||||
switch (progressDirection) {
|
||||
case UP -> siege.setSiegeProgress(siege.getSiegeProgress() + 1);
|
||||
case DOWN -> siege.setSiegeProgress(siege.getSiegeProgress() - 1);
|
||||
}
|
||||
|
||||
if (oldProgressDirection != progressDirection) {
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
siege.getAttackers().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The Attackers are capturing the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
siege.getDefenders().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The Attackers are capturing the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case NONE -> {
|
||||
/*if ()
|
||||
siege.getAttackers().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The home block is being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
siege.getDefenders().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The home block is being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));*/
|
||||
}
|
||||
case DOWN -> {
|
||||
siege.getAttackers().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The Defenders re-secured the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
siege.getDefenders().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>The Defenders re-secured the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
oldProgressDirection = progressDirection;
|
||||
|
||||
/*Bukkit.broadcast(
|
||||
new ColorParser("<prefix>Progress: <progress> <progress2> <test> <score>")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(siege.getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("progress2", String.valueOf(siege.getSiegeProgressPercentage()))
|
||||
.parseMinimessagePlaceholder("test", progressDirection.name())
|
||||
.parseMinimessagePlaceholder("score", String.valueOf(siege.getSiegeProgress()))
|
||||
.build()
|
||||
);*/
|
||||
|
||||
if (Instant.now().isAfter(nextAnnouncement)) {
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
siege.getAttackers().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>Siege time remaining: <time> minutes.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now() , siege.getEndTime()).toMinutesPart()))
|
||||
.build()
|
||||
));
|
||||
siege.getDefenders().forEach(p -> p.sendMessage(
|
||||
new ColorParser("<prefix>Siege time remaining: <time> minutes.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now() , siege.getEndTime()).toMinutesPart()))
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
siege.updateDisplayBar(progressDirection);
|
||||
}
|
||||
|
||||
private final static int CAPTURE_MAX_ELEVATION = 10;
|
||||
private final static int CAPTURE_RANGE = 10;
|
||||
|
||||
public int getPeopleOnPoint(Town town, Location townSpawn, BattleSide battleSide) {
|
||||
int onPoint = 0;
|
||||
|
||||
for (final Player p : (battleSide.equals(BattleSide.ATTACKER) ? siege.getAttackers() : siege.getDefenders())) {
|
||||
// WorldCoord wc = WorldCoord.parseWorldCoord(p);
|
||||
// if (!Objects.equals(wc.getTownOrNull(), town))
|
||||
// continue;
|
||||
|
||||
// @Nullable TownBlock homeBlock = town.getHomeBlockOrNull();
|
||||
// if (homeBlock == null)
|
||||
// continue;
|
||||
|
||||
if (/*!homeBlock.getWorldCoord().equals(wc) || */p.isDead())
|
||||
continue;
|
||||
|
||||
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
|
||||
onPoint += 1;
|
||||
}
|
||||
// if ((Math.abs(p.getLocation().getBlockY() - townSpawn.getBlockY())) < CAPTURE_MAX_ELEVATION) {
|
||||
// onPoint += 1;
|
||||
// }
|
||||
}
|
||||
|
||||
return onPoint;
|
||||
}
|
||||
|
||||
public CaptureProgressDirection getSiegeProgressDirection(Town town, Location townSpawn) {
|
||||
int attackersOnPoint = getPeopleOnPoint(town, townSpawn, BattleSide.ATTACKER);
|
||||
int defendersOnPoint = getPeopleOnPoint(town, townSpawn, BattleSide.DEFENDER);
|
||||
final boolean attackersAreOnPoint = attackersOnPoint > 0;
|
||||
final boolean defendersAreOnPoint = defendersOnPoint > 0;
|
||||
|
||||
if (attackersAreOnPoint)
|
||||
siege.setLastTouched(Instant.now());
|
||||
|
||||
if (attackersAreOnPoint && defendersAreOnPoint) {
|
||||
return CaptureProgressDirection.NONE;
|
||||
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
if (siege.getSiegeProgress() == MAX_SIEGE_PROGRESS)
|
||||
return CaptureProgressDirection.NONE;
|
||||
|
||||
return CaptureProgressDirection.UP;
|
||||
} /*else if (!attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
return CaptureProgressDirection.UNCONTESTED;
|
||||
}*/ else {
|
||||
if (siege.getSiegeProgress() == 0)
|
||||
return CaptureProgressDirection.NONE;
|
||||
|
||||
// If the attackers haven't touched in a while, begin reverting progress
|
||||
if (Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
|
||||
return CaptureProgressDirection.DOWN;
|
||||
} else {
|
||||
return CaptureProgressDirection.NONE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startBeam() {
|
||||
if (beam != null)
|
||||
return;
|
||||
|
||||
try {
|
||||
Location loc1 = siege.getTownSpawn();
|
||||
Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
|
||||
beam = new Laser.CrystalLaser(loc1, loc2, -1, BATTLEFIELD_RANGE);
|
||||
|
||||
if (beam != null)
|
||||
beam.start(Main.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private void stopBeam() {
|
||||
if (beam != null) {
|
||||
beam.stop();
|
||||
beam = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import de.leonhard.storage.Config;
|
||||
|
||||
public class ConfigManager {
|
||||
private Main instance;
|
||||
private Config cfg;
|
||||
|
||||
public ConfigManager(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
cfg = new Config("config", instance.getDataFolder().getPath(), instance.getResource("config.yml"));
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
|
||||
public Config getConfig() {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.utility.Config;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DataManager {
|
||||
private Main instance;
|
||||
// private static DataManager instance;
|
||||
private HikariConfig hikariConfig;
|
||||
private HikariDataSource hikariDataSource;
|
||||
|
||||
public DataManager(Main instance) {
|
||||
/*if (instance != null)
|
||||
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
|
||||
|
||||
main = Main.getInstance();*/
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
/*@NotNull
|
||||
public static DataManager getInstance() {
|
||||
if (instance == null)
|
||||
instance = new DataManager();
|
||||
|
||||
return instance;
|
||||
}*/
|
||||
|
||||
public void onLoad() {
|
||||
openConnection();
|
||||
SQLQueries.initDB();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
closeDatabaseConnection();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (hikariDataSource == null)
|
||||
throw new SQLException("Unable to get a connection from the pool. (hikariDataSource is null)");
|
||||
|
||||
Connection connection = hikariDataSource.getConnection();
|
||||
if (connection == null)
|
||||
throw new SQLException("Unable to get a connection from the pool. (HikariDataSource#getConnection returned null)");
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public HikariDataSource getDataSource() {
|
||||
return hikariDataSource;
|
||||
}
|
||||
|
||||
public void openConnection() {
|
||||
if (hikariDataSource != null)
|
||||
return;
|
||||
|
||||
hikariConfig = new HikariConfig();
|
||||
|
||||
final boolean mysqlEnabled = Config.get().getBoolean("mysql.enabled");
|
||||
|
||||
if (mysqlEnabled) {
|
||||
hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource");
|
||||
hikariConfig.setJdbcUrl("jdbc:mariadb://%s/%s".formatted(
|
||||
Config.get().get("mysql.host", "127.0.0.1:3306"),
|
||||
Config.get().get("mysql.database", "database")
|
||||
));
|
||||
hikariConfig.addDataSourceProperty("url", "jdbc:mariadb://%s/%s".formatted(
|
||||
Config.get().get("mysql.host", "127.0.0.1:3306"),
|
||||
Config.get().get("mysql.database", "database")
|
||||
));
|
||||
hikariConfig.setUsername(Config.get().get("mysql.user", "username"));
|
||||
hikariConfig.setPassword(Config.get().get("mysql.pass", "123"));
|
||||
hikariConfig.setConnectionTimeout(5000);
|
||||
hikariConfig.setKeepaliveTime(0);
|
||||
} else {
|
||||
File dataFolder = new File(instance.getDataFolder(), "database.db");
|
||||
|
||||
if (!dataFolder.exists()) {
|
||||
try {
|
||||
if (!dataFolder.createNewFile())
|
||||
instance.getLogger().severe("File write error: database.db (1)");
|
||||
} catch (IOException e) {
|
||||
instance.getLogger().severe("File write error: database.db (2) - " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
hikariConfig.setJdbcUrl("jdbc:sqlite:" + dataFolder);
|
||||
hikariConfig.setConnectionInitSql("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=30000");
|
||||
hikariConfig.setConnectionTimeout(30000);
|
||||
}
|
||||
|
||||
hikariConfig.setPoolName("althranwars-hikari");
|
||||
hikariConfig.setMaximumPoolSize(10);
|
||||
hikariConfig.setMinimumIdle(10);
|
||||
hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
|
||||
// hikariConfig.addDataSourceProperty("characterEncoding", "UTF-8");
|
||||
|
||||
// General optimizations (https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration)
|
||||
// hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
|
||||
// hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||
// hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||
// hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");
|
||||
// hikariConfig.addDataSourceProperty("useLocalSessionState", "true");
|
||||
// hikariConfig.addDataSourceProperty("rewriteBatchedStatements", "true");
|
||||
// hikariConfig.addDataSourceProperty("cacheServerConfiguration", "true");
|
||||
// hikariConfig.addDataSourceProperty("maintainTimeStats", "false");
|
||||
// hikariConfig.addDataSourceProperty("allowPublicKeyRetrieval", "true");
|
||||
// hikariConfig.addDataSourceProperty("useSSL", "false");
|
||||
|
||||
hikariDataSource = new HikariDataSource(hikariConfig);
|
||||
}
|
||||
|
||||
public void closeDatabaseConnection() {
|
||||
instance.getLogger().info("Closing database connection...");
|
||||
|
||||
if (hikariDataSource != null) {
|
||||
if (!hikariDataSource.isClosed()) {
|
||||
try {
|
||||
hikariDataSource.close();
|
||||
} catch (Exception e) {
|
||||
instance.getLogger().severe("Error closing database connections:");
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
instance.getLogger().info("Skipped closing database connection: connection is already closed.");
|
||||
}
|
||||
} else {
|
||||
instance.getLogger().severe("Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
|
||||
public enum RaidPhase {
|
||||
START(0, 0),
|
||||
GATHER(1, 0),
|
||||
TRAVEL(2, 18000),
|
||||
COMBAT(3, 24000),
|
||||
END(4, 72000);
|
||||
|
||||
//Start phase starts when the command to start a raid is ran, it allows the raiders to join, and for people to getInstance geared up
|
||||
//after 15 minutes travel phase begins, where the raiders start travelling and moving to the new town.
|
||||
//no killing can occur during these two phases.
|
||||
//Once at least one player has stepped into the defending town, or 5 min have passed during the travel phase,
|
||||
//the combat begins and lasts 40 minutes.
|
||||
|
||||
public final int id;
|
||||
public final int startTick;
|
||||
|
||||
RaidPhase(int id, int startTick) {
|
||||
this.id = id;
|
||||
this.startTick = startTick;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grabs the phase by name, ignores case
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static RaidPhase getByName(String name) {
|
||||
for (RaidPhase p : RaidPhase.values()) {
|
||||
if (p.name().equalsIgnoreCase(name)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grabs phase by id number for easy storage reading
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
public static RaidPhase getByID(int id) {
|
||||
for (RaidPhase p : RaidPhase.values()) {
|
||||
if (p.id == id) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static RaidPhase getNext(RaidPhase phase) {
|
||||
switch (phase) {
|
||||
case START -> {
|
||||
return GATHER;
|
||||
}
|
||||
case GATHER -> {
|
||||
return TRAVEL;
|
||||
}
|
||||
case TRAVEL -> {
|
||||
return COMBAT;
|
||||
}
|
||||
case COMBAT -> {
|
||||
return END;
|
||||
}
|
||||
default -> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum AdminCommandFailEnum {
|
||||
PERMISSIONS,
|
||||
SYNTAX,
|
||||
HELP
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum BattleSide {
|
||||
ATTACKER,
|
||||
DEFENDER,
|
||||
SPECTATOR,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum BattleTeam {
|
||||
SIDE_1,
|
||||
SIDE_2,
|
||||
SURRENDERED,
|
||||
NEUTRAL, // Not Participating
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum TownWarState {
|
||||
NOT_PARTICIPANT,
|
||||
SURRENDERED,
|
||||
SIDE1,
|
||||
SIDE2,
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PreWarCreateEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PreWarDeleteEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarCreateEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarDeleteEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class PreSiegeEndEvent {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class PreSiegeStartEvent {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class SiegeEndEvent {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class SiegeStartEvent {
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.github.alathra.AlathranWars.holder;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Singleton
|
||||
public class WarManager {
|
||||
private static WarManager instance;
|
||||
private Set<War> wars = new HashSet<>();
|
||||
|
||||
private WarManager() {
|
||||
if (instance != null)
|
||||
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static WarManager getInstance() {
|
||||
if (instance == null)
|
||||
instance = new WarManager();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void loadAll() {
|
||||
wars = SQLQueries.loadAll();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<War> getWars() {
|
||||
return wars;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public War getWar(String warName) {
|
||||
for (War war : wars)
|
||||
if (war.equals(warName)) return war;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public War getWar(UUID uuid) {
|
||||
for (War war : wars)
|
||||
if (war.equals(uuid)) return war;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
for (War war : wars)
|
||||
if (war.getSide(uuid) != null) return war.getSide(uuid);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
for (War war : wars)
|
||||
if (war.getSiege(uuid) != null) return war.getSiege(uuid);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void addWar(War war) {
|
||||
wars.add(war);
|
||||
}
|
||||
|
||||
public void removeWar(War war) {
|
||||
wars.remove(war);
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnyWars(UUID uuid) {
|
||||
for (War war : wars) {
|
||||
if (war.isPlayerInWar(uuid)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnyWars(Player p) {
|
||||
return isPlayerInAnyWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isTownInAnyWars(Town town) {
|
||||
for (War war : wars) {
|
||||
if (war.isTownInWar(town)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isNationInAnyWars(Nation nation) {
|
||||
for (War war : wars) {
|
||||
if (war.isNationInWar(nation)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWarNames() {
|
||||
return wars.stream()
|
||||
.map(War::getName)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWarLabels() {
|
||||
return wars.stream()
|
||||
.map(War::getLabel)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
final Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
wars.forEach((War war) -> sieges.addAll(war.getSieges()));
|
||||
|
||||
return sieges;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
final Set<Raid> raids = new HashSet<>();
|
||||
|
||||
wars.forEach((War war) -> raids.addAll(war.getRaids()));
|
||||
|
||||
return raids;
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnySiege(Player p) {
|
||||
return isPlayerInAnySiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnySiege(UUID uuid) {
|
||||
for (Siege siege : getSieges()) {
|
||||
if (siege.isPlayerInSiege(uuid)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public Set<Siege> getPlayerSieges(Player p) {
|
||||
return getPlayerSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
public Set<Siege> getPlayerSieges(UUID uuid) {
|
||||
if (!isPlayerInAnySiege(uuid))
|
||||
return Collections.emptySet();
|
||||
|
||||
Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
for (Siege siege : getSieges()) {
|
||||
if (siege.isPlayerInSiege(uuid))
|
||||
sieges.add(siege);
|
||||
}
|
||||
|
||||
return sieges;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.github.alathra.AlathranWars.hooks;
|
||||
|
||||
public class HookManager {
|
||||
public HookManager() {
|
||||
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
TABHook.init();
|
||||
TownyHook.init();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.github.alathra.AlathranWars.hooks;
|
||||
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import me.neznamy.tab.api.TabAPI;
|
||||
import me.neznamy.tab.api.TabPlayer;
|
||||
import me.neznamy.tab.api.event.EventBus;
|
||||
import me.neznamy.tab.api.event.player.PlayerLoadEvent;
|
||||
import me.neznamy.tab.api.nametag.UnlimitedNameTagManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class TABHook {
|
||||
private static boolean enabled = false;
|
||||
private static TabAPI tabAPI;
|
||||
|
||||
public static void init() {
|
||||
if (enabled) return;
|
||||
|
||||
tabAPI = TabAPI.getInstance();
|
||||
enabled = true;
|
||||
|
||||
registerPlayerLoadListener();
|
||||
}
|
||||
|
||||
private static void registerPlayerLoadListener() {
|
||||
if (!enabled) return;
|
||||
|
||||
EventBus eventBus = tabAPI.getEventBus();
|
||||
if (eventBus == null) return;
|
||||
|
||||
eventBus.register(PlayerLoadEvent.class, e -> {
|
||||
TabPlayer tabPlayer = e.getPlayer();
|
||||
if (tabPlayer.getPlayer() instanceof Player p)
|
||||
PlayerJoinListener.checkPlayer(p);
|
||||
});
|
||||
}
|
||||
|
||||
public static void assignSide1WarSuffix(Player p, War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" <red>[" + war.getSide1().getName() + "]<reset>")
|
||||
);
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, "<red>");
|
||||
}
|
||||
}
|
||||
|
||||
public static void assignSide2WarSuffix(Player p, War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, UtilsChat.color(" <blue>[") + war.getSide2().getName() + "]<reset>");
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, "<blue>");
|
||||
}
|
||||
}
|
||||
|
||||
public static void assignSide1WarSuffixMerc(Player p, War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" <green>[M]<red>[") + war.getSide1() + "]<reset>");
|
||||
}
|
||||
|
||||
public static void assignSide2WarSuffixMerc(Player p, War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" <green>[M]<blue>[") + war.getSide2() + "]<reset>");
|
||||
}
|
||||
|
||||
public static void resetSuffix(Player p) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
|
||||
public static void resetSuffix(String username) {
|
||||
if (!enabled) return;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username);
|
||||
|
||||
try {
|
||||
if (offlinePlayer.isOnline()) {
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(username);
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
} catch (NullPointerException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void resetPrefix(Player p) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void resetPrefix(String playername) {
|
||||
if (!enabled) return;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playername);
|
||||
try {
|
||||
if (offlinePlayer.isOnline()) {
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(playername);
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
} catch (NullPointerException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeColorPrefix(Player p, String prefix) {
|
||||
if (!enabled) return;
|
||||
|
||||
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (prefix.length() > 2) {
|
||||
prefix = prefix.substring(0, prefix.length() - 2);
|
||||
} else {
|
||||
Bukkit.getLogger().info("There is an error when removing a color prefix, prefix not long enough:");
|
||||
Bukkit.getLogger().info("Player: " + p.displayName());
|
||||
Bukkit.getLogger().info("Prefix: " + prefix);
|
||||
Bukkit.getLogger().info("------");
|
||||
}
|
||||
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setPrefix(tabPlayer, UtilsChat.color(prefix));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.github.alathra.AlathranWars.hooks;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TownyHook {
|
||||
private static boolean enabled = false;
|
||||
private static TownyAPI townyAPI;
|
||||
|
||||
public static void init() {
|
||||
if (enabled) return;
|
||||
|
||||
townyAPI = TownyAPI.getInstance();
|
||||
enabled = true;
|
||||
}
|
||||
|
||||
public static List<Town> getTowns() {
|
||||
return townyAPI.getTowns();
|
||||
}
|
||||
|
||||
public static List<Nation> getNations() {
|
||||
return townyAPI.getNations();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.items;
|
||||
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.Recipe;
|
||||
|
||||
public interface IWarItem {
|
||||
|
||||
ItemStack getItemStack();
|
||||
|
||||
Recipe getRecipe();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.github.alathra.AlathranWars.items;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.items.item.RamItem;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class WarItemRegistry {
|
||||
|
||||
public static final String namespace = Main.getInstance().getName().toLowerCase();
|
||||
private static final HashMap<String, IWarItem> itemRegistry = new HashMap<>();
|
||||
private static WarItemRegistry instance;
|
||||
|
||||
/**
|
||||
* loads all items into the plugin registry list
|
||||
*/
|
||||
public WarItemRegistry() {
|
||||
instance = this;
|
||||
|
||||
// Main.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars items.");
|
||||
|
||||
itemRegistry.put(registryName("ram"), new RamItem());
|
||||
//THIS BREAKS EVERYTHING???? TODO
|
||||
// Bukkit.getServer().addRecipe(new RamItem().getRecipe());
|
||||
|
||||
// Main.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars items.");
|
||||
}
|
||||
|
||||
public static WarItemRegistry getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* generate a registry name
|
||||
*
|
||||
* @param item
|
||||
* @return
|
||||
*/
|
||||
public static String registryName(String item) {
|
||||
return namespace + ":" + item;
|
||||
}
|
||||
|
||||
public Map<String, ItemStack> getItemRegistry() {
|
||||
return itemRegistry.entrySet()
|
||||
.stream()
|
||||
.filter(v -> v.getValue() != null)
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
v -> v.getValue().getItemStack()));
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the associated itemstack with the item key, use for finding without namespace
|
||||
*
|
||||
* @param registryName
|
||||
* @return
|
||||
*/
|
||||
public @Nullable ItemStack getOrNull(String registryName) {
|
||||
return itemRegistry.get(registryName(registryName)).getItemStack().clone();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the associated itemstack with the item key, use for finding with namespace
|
||||
*
|
||||
* @param registryName
|
||||
* @return
|
||||
*/
|
||||
public @Nullable ItemStack getOrNullNamespace(String registryName) {
|
||||
return itemRegistry.get(registryName).getItemStack().clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the associated IWarItem with the item key, use for finding with namespace
|
||||
*
|
||||
* @param registryName
|
||||
* @return
|
||||
*/
|
||||
public IWarItem getWarItem(String registryName) {
|
||||
return itemRegistry.get(registryName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.github.alathra.AlathranWars.items;
|
||||
|
||||
import org.bukkit.inventory.Recipe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
public class WarRecipeRegistry {
|
||||
|
||||
private static final HashMap<String, Recipe> recipeRegistry = new HashMap<>();
|
||||
private static WarRecipeRegistry instance;
|
||||
|
||||
public WarRecipeRegistry() {
|
||||
instance = this;
|
||||
|
||||
// Main.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars recipes.");
|
||||
|
||||
// register(WarItemRegistry.registryName("ram"), new RamItem().getRecipes());
|
||||
|
||||
// Main.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars recipes.");
|
||||
}
|
||||
|
||||
public static WarRecipeRegistry getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void register(String name, Set<Recipe> recipes) {
|
||||
for (Recipe recipe : recipes) {
|
||||
// Bukkit.getServer().addRecipe(recipe);
|
||||
recipeRegistry.put(name, recipe);
|
||||
}
|
||||
}
|
||||
|
||||
public HashMap<String, Recipe> getRecipeRegistry() {
|
||||
return recipeRegistry;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the associated itemstack with the item key, use for finding without namespace
|
||||
*
|
||||
* @param registryName recipe name without namespace
|
||||
* @return recipe
|
||||
*/
|
||||
public Recipe getOrNull(String registryName) {
|
||||
return recipeRegistry.get(WarItemRegistry.registryName(registryName));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the associated itemstack with the item key, use for finding with namespace
|
||||
*
|
||||
* @param registryName registry name including namespace
|
||||
* @return recipe
|
||||
*/
|
||||
public Recipe getOrNullNamespace(String registryName) {
|
||||
return recipeRegistry.get(registryName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.github.alathra.AlathranWars.items.item;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.items.IWarItem;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Tag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.Recipe;
|
||||
import org.bukkit.inventory.RecipeChoice;
|
||||
import org.bukkit.inventory.ShapedRecipe;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class RamItem implements IWarItem {
|
||||
|
||||
public ItemStack getItemStack() {
|
||||
|
||||
ItemStack ram = new ItemStack(Material.WOODEN_HOE);
|
||||
ItemMeta meta = ram.getItemMeta();
|
||||
|
||||
meta.setDisplayName("Door Ram");
|
||||
ArrayList<String> lore = new ArrayList<>();
|
||||
meta.setLore(lore);
|
||||
meta.setCustomModelData(14700);
|
||||
|
||||
ram.setItemMeta(meta);
|
||||
|
||||
return ram;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Recipe getRecipe() {
|
||||
ItemStack output = WarItemRegistry.getInstance().getOrNull("ram");
|
||||
NamespacedKey key = new NamespacedKey(Main.getInstance(), "ram");
|
||||
ShapedRecipe recipe = new ShapedRecipe(key, output);
|
||||
recipe.shape("$@$", "B##");
|
||||
recipe.setIngredient('@', Material.STICK);
|
||||
recipe.setIngredient('$', Material.IRON_INGOT);
|
||||
recipe.setIngredient('B', Material.IRON_BLOCK);
|
||||
recipe.setIngredient('%', new RecipeChoice.MaterialChoice(Tag.LOGS));
|
||||
return recipe;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class BlockBreakListener implements Listener {
|
||||
private final static Set<Material> allowedBlocks = Set.of(
|
||||
Material.TNT,
|
||||
// Mortar & Cannons
|
||||
Material.IRON_BLOCK,
|
||||
Material.HEAVY_WEIGHTED_PRESSURE_PLATE,
|
||||
Material.TORCH,
|
||||
Material.STONE_BUTTON,
|
||||
Material.BLACK_WOOL
|
||||
);
|
||||
|
||||
@EventHandler
|
||||
public void onBlockBreak(final BlockBreakEvent e) {
|
||||
final Block block = e.getBlock();
|
||||
/*if (SiegeData.getSieges().isEmpty() *//*&& RaidData.getRaids().isEmpty()*//*) {
|
||||
return;
|
||||
}*/
|
||||
|
||||
if (allowedBlocks.contains(block.getType())) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.getPlayer().hasPermission("AlathranWars.break")) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
if (siege.beaconLocations.contains(block.getLocation())) {
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
|
||||
if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) {
|
||||
/*for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
|
||||
e.getPlayer().sendMessage(new ColorParser("<red>You can not break blocks during sieges").parseLegacy().build());
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
|
||||
/*for (final OldRaid oldRaid : RaidData.getRaids()) {
|
||||
if (oldRaid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
|
||||
p.sendMessage(Helper.color("<red>You can not break blocks during raids"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onBlockPlace(final BlockPlaceEvent event) {
|
||||
final Block block = event.getBlock();
|
||||
/*if (SiegeData.getSieges().isEmpty() && RaidData.getRaids().isEmpty()) {
|
||||
return;
|
||||
}*/
|
||||
if (allowedBlocks.contains(block.getType())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Player p = event.getPlayer();
|
||||
if (p.hasPermission("AlathranWars.place")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) {
|
||||
/*for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
|
||||
p.sendMessage(new ColorParser("<red>You can not place blocks during sieges").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
|
||||
/*for (final OldRaid oldRaid : RaidData.getRaids()) {
|
||||
if (oldRaid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
|
||||
p.sendMessage(Helper.color("<red>You can not place blocks during raids"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class CommandsListener implements Listener {
|
||||
|
||||
final static String[] PREFIXES = new String[]{
|
||||
"", "towny", "essentials", "wild", "minecraft"
|
||||
};
|
||||
final static String[] PREFIXES_TOWNY = new String[]{
|
||||
"", "towny"
|
||||
};
|
||||
final static String[] BLACKLISTED_X_LONG = new String[]{
|
||||
"n set spawn", "nat set spawn", "nation set spawn",
|
||||
"t set spawn", "town set spawn",
|
||||
"t set homeblock", "town set homeblock",
|
||||
"t set name", "town set name",
|
||||
"n set name", "nat set name", "nation set name"
|
||||
};
|
||||
final static String[] BLACKLISTED_LONG = new String[]{
|
||||
"n spawn", "nat spawn", "nation spawn",
|
||||
"t spawn", "town spawn",
|
||||
"t outpost", "town outpost"
|
||||
};
|
||||
final static String[] PAYMENT = new String[]{
|
||||
"n withdraw", "nat withdraw", "nation withdraw",
|
||||
"t withdraw", "town withdraw"
|
||||
};
|
||||
final static String[] BLACKLISTED_SHORT = new String[]{
|
||||
"home", "homes", "warp", "warps",
|
||||
"wild", "rtp", "spawn", "wilderness", "wildtp",
|
||||
"tpa", "tpahere", "tpaccept", "tpacancel",
|
||||
"etpa", "etpahere", "etpaccept", "etpacancel",
|
||||
"ehome", "ehomes", "ewarp", "ewarps"
|
||||
|
||||
};
|
||||
|
||||
@EventHandler
|
||||
public void onCommandSend(final PlayerCommandPreprocessEvent event) {
|
||||
|
||||
Player p = event.getPlayer();
|
||||
|
||||
//if player is admin, ignore this behavior
|
||||
// if (p.hasPermission("!AlathranWars.admin")) return;
|
||||
|
||||
String[] args = event.getMessage().split(" ");
|
||||
|
||||
/*
|
||||
Prevent any teleport command events from occurring
|
||||
If using PlayerTeleportEvent, it breaks the death logic
|
||||
|
||||
allow n spawn and t spawn for defenders trapped in spawn
|
||||
*/
|
||||
/*for (OldRaid oldRaid : RaidData.getRaids()) {
|
||||
//Only do this during regular phases, start and end ignored in case something breaks
|
||||
if (oldRaid.getPhase() == RaidPhase.COMBAT || oldRaid.getPhase() == RaidPhase.TRAVEL || oldRaid.getPhase() == RaidPhase.GATHER) {
|
||||
//only do for active raiders and any defenders
|
||||
if (oldRaid.getActiveRaiders().contains(p.getName()) || oldRaid.getDefenderPlayers().contains(p.getName())) {
|
||||
//set spawn and properties
|
||||
if (args.length >= 3) {
|
||||
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1] + " " + args[2];
|
||||
for (String prefix : prefixesTowny) {
|
||||
//payment check
|
||||
for (String cmd : blacklistedXLong) {
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<red>You cannot modify this property during a oldRaid!"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//n spawn and t spawn
|
||||
if (args.length >= 2) {
|
||||
//parse what we have, remove the starting sslash
|
||||
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
|
||||
for (String prefix : prefixesTowny) {
|
||||
//payment check
|
||||
for (String cmd : payment) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<red>You cannot withdraw money whilst in a oldRaid!"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (String cmd : blacklistedLong) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
//check if in spawn
|
||||
if (p.getWorld().getName().equalsIgnoreCase("world")) {
|
||||
if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn")
|
||||
|| parse.equalsIgnoreCase("t spawn") || parse.equalsIgnoreCase("town spawn")
|
||||
|| parse.equalsIgnoreCase("towny:n spawn") || parse.equalsIgnoreCase("towny:nat spawn") || parse.equalsIgnoreCase("towny:nation spawn")
|
||||
|| parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<yellow>You are stuck in spawn and are allowed to teleport to your town or nation."));
|
||||
return;
|
||||
}
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<yellow>You are stuck in spawn and are allowed to teleport to your town or nation."));
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<yellow>Use /t spawn, or /n spawn"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
//else
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<red>You cannot teleport whilst in a oldRaid!"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//random tp commands
|
||||
if (args.length >= 1) {
|
||||
//parse what we have, remove the starting slash
|
||||
String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0];
|
||||
for (String prefix : prefixes) {
|
||||
for (String cmd : blacklistedShort) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
//spawn world check
|
||||
if (p.getWorld().getName().equalsIgnoreCase("world")) {
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<yellow>You are stuck in spawn and are allowed to teleport to your town or nation."));
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<yellow>Use /t spawn, or /n spawn"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
p.sendMessage(UtilsChat.getPrefix() + Helper.color("<red>You cannot teleport whilst in a oldRaid!"));
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
/*
|
||||
Prevent players from teleporting during a siege
|
||||
*/
|
||||
for (Siege siege : WarManager.getInstance().getSieges()) {
|
||||
//Only do this during regular phases, start and end ignored in case something breaks
|
||||
if (siege.getEndTime().isAfter(Instant.now())) {
|
||||
//only do for active raiders and any defenders
|
||||
if (siege.getAttackerPlayers().contains(p) || siege.getDefenderPlayers().contains(p)) {
|
||||
//set spawn and properties
|
||||
if (args.length >= 3) {
|
||||
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1] + " " + args[2];
|
||||
for (String prefix : PREFIXES_TOWNY) {
|
||||
//payment check
|
||||
for (String cmd : BLACKLISTED_X_LONG) {
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>You cannot modify this property during a oldSiege!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//n spawn and t spawn
|
||||
if (args.length >= 2) {
|
||||
//parse what we have, remove the starting sslash
|
||||
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
|
||||
for (String prefix : PREFIXES_TOWNY) {
|
||||
//payment check
|
||||
for (String cmd : PAYMENT) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>You cannot withdraw money whilst in a oldSiege!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (String cmd : BLACKLISTED_LONG) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
//check if in spawn
|
||||
if (p.getWorld().getName().equalsIgnoreCase("world")) {
|
||||
if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn")
|
||||
|| parse.equalsIgnoreCase("t spawn") || parse.equalsIgnoreCase("town spawn")
|
||||
|| parse.equalsIgnoreCase("towny:n spawn") || parse.equalsIgnoreCase("towny:nat spawn") || parse.equalsIgnoreCase("towny:nation spawn")
|
||||
|| parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
|
||||
return;
|
||||
}
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>Use /t spawn, or /n spawn").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
//else
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>You cannot teleport whilst in a oldSiege!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//random tp commands
|
||||
if (args.length >= 1) {
|
||||
//parse what we have, remove the starting slash
|
||||
String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0];
|
||||
for (String prefix : PREFIXES) {
|
||||
for (String cmd : BLACKLISTED_SHORT) {
|
||||
//check for each prefix
|
||||
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
|
||||
//spawn world check
|
||||
if (p.getWorld().getName().equalsIgnoreCase("world")) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>Use /t spawn, or /n spawn").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>You cannot teleport whilst in a oldSiege!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.github.alathra.AlathranWars.utility.Utils;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.exceptions.TownyException;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
|
||||
public final class KillsListener implements Listener {
|
||||
|
||||
// public static final HashMap<UUID, OldRaid> respawnQueue = new HashMap<>();
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerKilled(final PlayerDeathEvent event) {
|
||||
|
||||
final Player killed = event.getEntity();
|
||||
final Player killer = event.getEntity().getKiller();
|
||||
Town town = null;
|
||||
try {
|
||||
town = WorldCoord.parseWorldCoord(killed).getTownBlock().getTown();
|
||||
} catch (NotRegisteredException ex2) {
|
||||
ex2.printStackTrace();
|
||||
}
|
||||
boolean playerCloseToHomeBlockSiege = false;
|
||||
boolean playerCloseToHomeBlockRaid = false;
|
||||
|
||||
// try {
|
||||
//OldRaid logic
|
||||
/*for (final OldRaid oldRaid : RaidData.getRaids()) {
|
||||
final int homeBlockXCoordRaided = oldRaid.getRaidedTown().getHomeBlock().getCoord().getX() * 16;
|
||||
final int homeBlockZCoordRaided = oldRaid.getRaidedTown().getHomeBlock().getCoord().getZ() * 16;
|
||||
// final int homeBlockXCoordGather = oldRaid.getGatherTown().getHomeBlock().getCoord().getX() * 16;
|
||||
// final int homeBlockZCoordGather = oldRaid.getGatherTown().getHomeBlock().getCoord().getZ() * 16;
|
||||
//Carryover from sieges
|
||||
if (Math.abs(killed.getLocation().getBlockX() - homeBlockXCoordRaided) <= 200 && Math.abs(killed.getLocation().getBlockZ() - homeBlockZCoordRaided) <= 200) {
|
||||
playerCloseToHomeBlockRaid = true;
|
||||
}
|
||||
|
||||
if (oldRaid.getDefenderPlayers().contains(killed.getName()) && ((town != null && town.equals(oldRaid.getRaidedTown())) || playerCloseToHomeBlockRaid)) {
|
||||
//There is seperate behavior if combat hasnt started
|
||||
if (oldRaid.getPhase() == RaidPhase.COMBAT && killer != null) {
|
||||
if (oldRaid.getActiveRaiders().contains(killer.getName())) {
|
||||
this.raidKill(killed, event);
|
||||
oldRaid.defenderKilledInCombat(event);
|
||||
return;
|
||||
}
|
||||
}
|
||||
//teleport back to raided spawn, without damaged gear
|
||||
this.oocKill(killed, event);
|
||||
oldRaid.defenderKilledOutofCombat(event);
|
||||
return;
|
||||
}
|
||||
if (oldRaid.getActiveRaiders().contains(killed.getName()) && ((town != null && town.equals(oldRaid.getRaidedTown())) || playerCloseToHomeBlockRaid)) {
|
||||
//There is seperate behavior if combat hasnt started
|
||||
if (oldRaid.getPhase() == RaidPhase.COMBAT && killer != null) {
|
||||
if (oldRaid.getDefenderPlayers().contains(killer.getName())) {
|
||||
this.raidKill(killed, event);
|
||||
oldRaid.raiderKilledInCombat(event);
|
||||
respawnQueue.put(killed.getUniqueId(), oldRaid);
|
||||
return;
|
||||
}
|
||||
} else if (oldRaid.getPhase() != RaidPhase.COMBAT && killer != null) {
|
||||
this.oocKill(killed, event);
|
||||
oldRaid.raiderKilledOutofCombat(event);
|
||||
respawnQueue.put(killed.getUniqueId(), oldRaid);
|
||||
return;
|
||||
}
|
||||
//teleport back to gather town spawn, without damaged gear
|
||||
//this is to disincentive people prekilling
|
||||
this.oocKill(killed, event);
|
||||
oldRaid.raiderKilledOutofCombat(event);
|
||||
respawnQueue.put(killed.getUniqueId(), oldRaid);
|
||||
return;
|
||||
}
|
||||
if ((town != null && town.equals(oldRaid.getRaidedTown()) || playerCloseToHomeBlockRaid)) {
|
||||
this.raidKill(killed, event);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
/*if (killer == null) return;
|
||||
|
||||
for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
final int homeBlockXCoord = siege.getTown().getHomeBlock().getCoord().getX() * 16;
|
||||
final int homeBlockZCoord = siege.getTown().getHomeBlock().getCoord().getZ() * 16;
|
||||
if (Math.abs(killed.getLocation().getBlockX() - homeBlockXCoord) <= 300 && Math.abs(killed.getLocation().getBlockZ() - homeBlockZCoord) <= 300) {
|
||||
playerCloseToHomeBlockSiege = true;
|
||||
}
|
||||
if (siege.getAttackerPlayers().contains(killer) && ((town != null && town.equals(siege.getTown())) || playerCloseToHomeBlockSiege)) {
|
||||
if (siege.getDefenderPlayers().contains(killed)) {
|
||||
siege.addPointsToAttackers(20);
|
||||
for (final Player p : siege.getAttackerPlayers()) {
|
||||
try {
|
||||
if (p != null)
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Defender killed! + 20 Attacker Points").parseLegacy().build());
|
||||
} catch (NullPointerException ignored) {
|
||||
ignored.printStackTrace();
|
||||
}
|
||||
}
|
||||
for (final Player p : siege.getDefenderPlayers()) {
|
||||
try {
|
||||
if (p != null)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Defender killed! + 20 Attacker Points");
|
||||
} catch (NullPointerException ignored) {
|
||||
ignored.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
this.siegeKill(killed, event);
|
||||
return;
|
||||
}
|
||||
if (siege.getDefenderPlayers().contains(killer) && ((town != null && town.equals(siege.getTown())) || playerCloseToHomeBlockSiege)) {
|
||||
if (siege.getAttackerPlayers().contains(killed)) {
|
||||
siege.addPointsToDefenders(20);
|
||||
for (final Player p : siege.getAttackerPlayers()) {
|
||||
try {
|
||||
if (p != null)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Attacker killed! + 20 Defender Points");
|
||||
} catch (NullPointerException ex3) {
|
||||
ex3.printStackTrace();
|
||||
}
|
||||
}
|
||||
for (final Player p : siege.getDefenderPlayers()) {
|
||||
try {
|
||||
if (p != null)
|
||||
p.sendMessage(UtilsChat.getPrefix() + "Attacker killed! + 20 Defender Points");
|
||||
} catch (NullPointerException ex4) {
|
||||
ex4.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
this.siegeKill(killed, event);
|
||||
return;
|
||||
}
|
||||
if ((town != null && town.equals(siege.getTown()) || playerCloseToHomeBlockSiege)) {
|
||||
this.siegeKill(killed, event);
|
||||
}
|
||||
}
|
||||
} catch (NullPointerException | TownyException ignored) {
|
||||
ignored.printStackTrace();
|
||||
}*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs last so that it overrides everyone else!
|
||||
*
|
||||
* @param event
|
||||
*/
|
||||
/*@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onRespawn(PlayerRespawnEvent event) {
|
||||
if (respawnQueue.containsKey(event.getPlayer().getUniqueId())) {
|
||||
OldRaid oldRaid = respawnQueue.get(event.getPlayer().getUniqueId());
|
||||
if (oldRaid == null) return;
|
||||
if (oldRaid.getActiveRaiders().contains(event.getPlayer().getName())) {
|
||||
//do raider respawn
|
||||
try {
|
||||
event.setRespawnLocation(oldRaid.getGatherTown().getSpawn());
|
||||
event.getPlayer().sendMessage(UtilsChat.getPrefix() + "You died " + (oldRaid.getPhase().equals(RaidPhase.COMBAT) ? "raiding" : "before combat") + " and have been teleported back to the gather point.");
|
||||
} catch (TownyException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else if (oldRaid.getDefenderSide().contains(event.getPlayer().getName())) {
|
||||
//do defender respawn ?
|
||||
} else {
|
||||
//invalid code
|
||||
}
|
||||
respawnQueue.remove(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
/**
|
||||
* Damage all gear held by the player (and then send them to spawn?)
|
||||
* They don't lose items from death.
|
||||
*
|
||||
* @param killed killed player
|
||||
* @param event event
|
||||
*/
|
||||
private void siegeKill(final Player killed, final PlayerDeathEvent event) {
|
||||
//Helper
|
||||
Utils.damageAllGear(killed);
|
||||
|
||||
//Siege specific
|
||||
// Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + killed.getName()); // TODO Re enable?
|
||||
event.setKeepInventory(true);
|
||||
event.getDrops().clear();
|
||||
event.setKeepLevel(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Damage all gear held by the player (and then send them to spawn?)
|
||||
* They don't lose items from death.
|
||||
*
|
||||
* @param killed killed player
|
||||
* @param event event
|
||||
*/
|
||||
private void raidKill(final Player killed, final PlayerDeathEvent event) {
|
||||
//Helper
|
||||
Utils.damageAllGear(killed);
|
||||
|
||||
//Siege specific
|
||||
// Bukkit.dispatchCommand((CommandSender)Bukkit.getConsoleSender(), "spawn " + killed.getName());
|
||||
event.setKeepInventory(true);
|
||||
event.getDrops().clear();
|
||||
event.setKeepLevel(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dont damage items held by the player
|
||||
* They don't lose items from death.
|
||||
*
|
||||
* @param killed killed player
|
||||
* @param event event
|
||||
*/
|
||||
private void oocKill(final Player killed, final PlayerDeathEvent event) {
|
||||
//Siege specific
|
||||
// Bukkit.dispatchCommand((CommandSender)Bukkit.getConsoleSender(), "spawn " + killed.getName());
|
||||
event.setKeepInventory(true);
|
||||
event.getDrops().clear();
|
||||
event.setKeepLevel(true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.BlockBreakPlaceListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.PlayerDeathListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.PlayerQuitListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.NationListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.TownListener;
|
||||
|
||||
/**
|
||||
* A class to handle registration of event listeners.
|
||||
*/
|
||||
public class ListenerHandler {
|
||||
private final Main instance;
|
||||
|
||||
public ListenerHandler(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
// Sieges
|
||||
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.siege.PlayerJoinListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerQuitListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new BlockBreakPlaceListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerDeathListener(), instance);
|
||||
|
||||
// Wars
|
||||
instance.getServer().getPluginManager().registerEvents(new NationListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new TownListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new TownListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerJoinListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.war.PlayerQuitListener(), instance);
|
||||
|
||||
// instance.getServer().getPluginManager().registerEvents(new BlockBreakListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new CommandsListener(), instance);
|
||||
// instance.getServer().getPluginManager().registerEvents(new KillsListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance);
|
||||
//instance.getServer().getPluginManager().registerEvents(new PlayerJoinListener(instance), instance);
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.Bisected;
|
||||
import org.bukkit.block.data.type.Door;
|
||||
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.event.player.PlayerItemDamageEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PlayerInteractListener implements Listener {
|
||||
|
||||
//predefined foor materials
|
||||
private static final Set<Material> doors = new HashSet<>();
|
||||
|
||||
static {
|
||||
doors.add(Material.ACACIA_DOOR);
|
||||
doors.add(Material.BIRCH_DOOR);
|
||||
doors.add(Material.CRIMSON_DOOR);
|
||||
doors.add(Material.DARK_OAK_DOOR);
|
||||
doors.add(Material.IRON_DOOR);
|
||||
doors.add(Material.JUNGLE_DOOR);
|
||||
doors.add(Material.MANGROVE_DOOR);
|
||||
doors.add(Material.OAK_DOOR);
|
||||
doors.add(Material.SPRUCE_DOOR);
|
||||
doors.add(Material.WARPED_DOOR);
|
||||
}
|
||||
|
||||
//map of broken doors
|
||||
public Map<Location, Long> brokenDoors = new HashMap<>();
|
||||
|
||||
/**
|
||||
* @param event event
|
||||
* @author DunnoConz
|
||||
* @author AubriTheHuman
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerInteract(final PlayerInteractEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Action action = event.getAction();
|
||||
|
||||
if (action == Action.LEFT_CLICK_BLOCK) {
|
||||
Block clicked = event.getClickedBlock();
|
||||
ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (clicked != null) {
|
||||
if (doors.contains(clicked.getType())) { // left click + any door types
|
||||
Door door = (Door) clicked.getBlockData();
|
||||
// lock door in the opposite position
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
boolean inSiegeOrRaid = false;
|
||||
//siege check
|
||||
for (Siege s : WarManager.getInstance().getSieges()) {
|
||||
for (TownBlock townBlock : s.getTown().getTownBlocks()) {
|
||||
if (WorldCoord.parseWorldCoord(clicked).equals(townBlock.getWorldCoord())) {
|
||||
// if we find one, just end no need to continue
|
||||
inSiegeOrRaid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//if it wasnt in a siege, then
|
||||
/*if (!inSiegeOrRaid) {
|
||||
for (OldRaid r : RaidData.getRaids()) {
|
||||
for (TownBlock townBlock : r.getRaidedTown().getTownBlocks()) {
|
||||
if (WorldCoord.parseWorldCoord(clicked).equals(townBlock.getWorldCoord())) {
|
||||
// if we find one, just end no need to continue
|
||||
inSiegeOrRaid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
if (inSiegeOrRaid) {
|
||||
|
||||
// Returns if already broken.
|
||||
if (doorBroken(clicked, door)) {
|
||||
player.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>The door is already broken!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
player.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<yellow>Break it down alright!").parseLegacy().build());
|
||||
brokenDoors.put(getDoorPos(clicked, door), System.currentTimeMillis() + (1000L * Main.getInstance().getConfig().getInt("batteringRamEffectiveness")));
|
||||
door.setOpen(!door.isOpen());
|
||||
clicked.setBlockData(door);
|
||||
player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount() - 1);
|
||||
Main.warLogger.log("User " + player.getName() + " has broken down door" + clicked.getLocation());
|
||||
} else {
|
||||
player.sendMessage(new ColorParser(UtilsChat.getPrefix() + "<red>This item can only be used in a siege or raid!").parseLegacy().build());
|
||||
}
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerRClick(final PlayerItemDamageEvent event) {
|
||||
ItemStack item = event.getItem();
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param event event
|
||||
* @author DunnoConz
|
||||
* @author AubriTheHuman
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerRClick(final PlayerInteractEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Action action = event.getAction();
|
||||
Block clicked = event.getClickedBlock();
|
||||
ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (action == Action.RIGHT_CLICK_BLOCK) {
|
||||
if (clicked != null) {
|
||||
if (doors.contains(clicked.getType())) {
|
||||
Door door = (Door) clicked.getBlockData();
|
||||
if (doorBroken(clicked, door)) {
|
||||
player.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Door is broken!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
if (clicked != null) {
|
||||
if (clicked.getType().name().equals("GRASS_BLOCK")
|
||||
|| clicked.getType().name().equals("DIRT")
|
||||
|| clicked.getType().name().equals("COARSE_DIRT")
|
||||
|| clicked.getType().name().equals("ROOTED_DIRT")
|
||||
|| clicked.getType().name().equals("DIRT_PATH")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Location getDoorPos(Block clicked, Door door) {
|
||||
if (door.getHalf() == Bisected.Half.BOTTOM) {
|
||||
return clicked.getLocation().clone();
|
||||
} else if (door.getHalf() == Bisected.Half.TOP) {
|
||||
return clicked.getLocation().subtract(0.0, 1.0, 0.0).clone();
|
||||
}
|
||||
return clicked.getLocation().clone();
|
||||
}
|
||||
|
||||
private boolean doorBroken(@Nonnull Block clicked, Door door) {
|
||||
if (door.getHalf() == Bisected.Half.BOTTOM) {
|
||||
if (brokenDoors.get(clicked.getLocation()) != null) {
|
||||
return brokenDoors.get(clicked.getLocation()) > System.currentTimeMillis();
|
||||
}
|
||||
} else if (door.getHalf() == Bisected.Half.TOP) {
|
||||
if (brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) != null) {
|
||||
return brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) > System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.github.alathra.AlathranWars.listeners.siege;
|
||||
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class BlockBreakPlaceListener implements Listener {
|
||||
private final static Set<Material> allowedBlocks = Set.of(
|
||||
Material.TNT,
|
||||
// Mortar & Cannons
|
||||
Material.IRON_BLOCK,
|
||||
Material.HEAVY_WEIGHTED_PRESSURE_PLATE,
|
||||
Material.TORCH,
|
||||
Material.STONE_BUTTON,
|
||||
Material.BLACK_WOOL
|
||||
);
|
||||
|
||||
@EventHandler
|
||||
private void onBlockBreak(BlockBreakEvent e) {
|
||||
final Block block = e.getBlock();
|
||||
|
||||
if (allowedBlocks.contains(block.getType()))
|
||||
return;
|
||||
|
||||
if (e.getPlayer().hasPermission("AlathranWars.break"))
|
||||
return;
|
||||
|
||||
final @Nullable Town town = WorldCoord.parseWorldCoord(block).getTownOrNull();
|
||||
|
||||
if (town == null)
|
||||
return;
|
||||
|
||||
for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
if (siege.getTown().equals(town)) {
|
||||
e.getPlayer().sendMessage(new ColorParser("<red>You can not break blocks during sieges.").build());
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onBlockPlace(BlockPlaceEvent e) {
|
||||
final Block block = e.getBlock();
|
||||
|
||||
if (allowedBlocks.contains(block.getType()))
|
||||
return;
|
||||
|
||||
if (e.getPlayer().hasPermission("AlathranWars.place"))
|
||||
return;
|
||||
|
||||
final @Nullable Town town = WorldCoord.parseWorldCoord(block).getTownOrNull();
|
||||
|
||||
if (town == null)
|
||||
return;
|
||||
|
||||
for (final Siege siege : WarManager.getInstance().getSieges()) {
|
||||
if (siege.getTown().equals(town)) {
|
||||
e.getPlayer().sendMessage(new ColorParser("<red>You can not place blocks during sieges.").build());
|
||||
e.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.github.alathra.AlathranWars.listeners.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.utility.Utils;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.PlayerDeathEvent;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PlayerDeathListener implements Listener {
|
||||
private final static int BATTLE_RADIUS = 300;
|
||||
private final static int KILL_POINTS_OFF = 20; // Point for an offensive kill
|
||||
private final static int KILL_POINTS_DEF = 20; // Point for a defensive kill
|
||||
|
||||
/*@EventHandler
|
||||
private void onPlayerDeath(PlayerDeathEvent e) {
|
||||
final Player victim = e.getPlayer();
|
||||
final Player attacker = e.getPlayer().getKiller();
|
||||
|
||||
if (attacker == null)
|
||||
return;
|
||||
|
||||
final @Nullable Town town = WorldCoord.parseWorldCoord(victim).getTownOrNull();
|
||||
|
||||
for (Siege siege : WarManager.getInstance().getSieges()) {
|
||||
boolean isPlayerInCombatZone = false;
|
||||
|
||||
final TownBlock homeBlock = siege.getTown().getHomeBlockOrNull();
|
||||
if (homeBlock == null)
|
||||
continue;
|
||||
|
||||
final int homeBlockXCoord = homeBlock.getCoord().getX() * 16;
|
||||
final int homeBlockZCoord = homeBlock.getCoord().getZ() * 16;
|
||||
|
||||
if (victim.getLocation().distance(new Location(victim.getWorld(), homeBlockXCoord, victim.getLocation().getBlockY(), homeBlockZCoord)) <= BATTLE_RADIUS) {
|
||||
// if (Math.abs(killed.getLocation().getBlockX() - homeBlockXCoord) <= BATTLE_RADIUS && Math.abs(killed.getLocation().getBlockZ() - homeBlockZCoord) <= BATTLE_RADIUS) {
|
||||
isPlayerInCombatZone = true;
|
||||
}
|
||||
|
||||
if (siege.getAttackerPlayers().contains(attacker) && (siege.getTown().equals(town) || isPlayerInCombatZone)) {
|
||||
if (siege.getDefenderPlayers().contains(victim)) {
|
||||
siege.addPointsToAttackers(KILL_POINTS_OFF);
|
||||
|
||||
for (final Player p : siege.getAttackerPlayers()) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Defender killed! + "+KILL_POINTS_OFF+" Attacker Points.").build());
|
||||
}
|
||||
for (final Player p : siege.getDefenderPlayers()) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Defender killed! + "+KILL_POINTS_OFF+" Attacker Points.").build());
|
||||
}
|
||||
}
|
||||
|
||||
this.siegeKill(victim, e);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (siege.getDefenderPlayers().contains(attacker) && (siege.getTown().equals(town) || isPlayerInCombatZone)) {
|
||||
if (siege.getAttackerPlayers().contains(victim)) {
|
||||
siege.addPointsToDefenders(KILL_POINTS_DEF);
|
||||
|
||||
for (final Player p : siege.getAttackerPlayers()) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Attacker killed! + "+KILL_POINTS_DEF+" Defender Points.").build());
|
||||
}
|
||||
for (final Player p : siege.getDefenderPlayers()) {
|
||||
p.sendMessage(new ColorParser(UtilsChat.getPrefix() + "Attacker killed! + "+KILL_POINTS_DEF+" Defender Points.").build());
|
||||
}
|
||||
}
|
||||
|
||||
this.siegeKill(victim, e);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ((siege.getTown().equals(town) || isPlayerInCombatZone)) {
|
||||
this.oocKill(victim, e);
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
/**
|
||||
* Damage all gear held by the player (and then send them to spawn?)
|
||||
* They don't lose items from death.
|
||||
*
|
||||
* @param victim killed player
|
||||
* @param e event
|
||||
*/
|
||||
private void siegeKill(Player victim, PlayerDeathEvent e) {
|
||||
//Helper
|
||||
Utils.damageAllGear(victim);
|
||||
|
||||
//Siege specific
|
||||
// Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + victim.getName()); // TODO Re enable?
|
||||
e.setKeepInventory(true);
|
||||
e.getDrops().clear();
|
||||
e.setKeepLevel(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dont damage items held by the player
|
||||
* They don't lose items from death.
|
||||
*
|
||||
* @param victim killed player
|
||||
* @param e event
|
||||
*/
|
||||
private void oocKill(Player victim, PlayerDeathEvent e) {
|
||||
//Siege specific
|
||||
// Bukkit.dispatchCommand((CommandSender)Bukkit.getConsoleSender(), "spawn " + victim.getName()); // TODO Re enable?
|
||||
e.setKeepInventory(true);
|
||||
e.getDrops().clear();
|
||||
e.setKeepLevel(true);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.listeners.siege;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
public class PlayerExampleListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerJoin(PlayerJoinEvent e) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.github.alathra.AlathranWars.listeners.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerJoin(PlayerJoinEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
if (WarManager.getInstance().isPlayerInAnySiege(p)) {
|
||||
for (Siege siege : WarManager.getInstance().getPlayerSieges(p)) {
|
||||
final BattleSide side = siege.getPlayerSideInSiege(p);
|
||||
siege.addOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.github.alathra.AlathranWars.listeners.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class PlayerQuitListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerQuit(PlayerQuitEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
if (WarManager.getInstance().isPlayerInAnySiege(p)) {
|
||||
for (Siege siege : WarManager.getInstance().getPlayerSieges(p)) {
|
||||
final BattleSide side = siege.getPlayerSideInSiege(p);
|
||||
siege.removeOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.github.alathra.AlathranWars.listeners.war;
|
||||
|
||||
import com.palmergames.bukkit.towny.event.nation.NationKingChangeEvent;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class NationListener implements Listener {
|
||||
/*
|
||||
* NationPreTownLeaveEvent, NationPreTownKickEvent, NationPreMergeEvent
|
||||
*
|
||||
* NationKingChangeEvent
|
||||
* NationPreRenameEvent
|
||||
*
|
||||
*
|
||||
* NationTownJoin (add to war)
|
||||
* NationTownLeave (add to war)
|
||||
*
|
||||
* */
|
||||
// TODO Prevent nation rename during war, siege, raid
|
||||
|
||||
/*@EventHandler
|
||||
private void onNationKingChange(NationKingChangeEvent e) {
|
||||
e.setCancelMessage("");
|
||||
e.setCancelled(true);
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.github.alathra.AlathranWars.listeners.war;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.github.alathra.AlathranWars.hooks.TABHook;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
public static void checkPlayer(Player p) {
|
||||
final UUID uuid = p.getUniqueId();
|
||||
|
||||
if (WarManager.getInstance().isPlayerInAnyWars(uuid)) {
|
||||
for (final War war : WarManager.getInstance().getWars()) {
|
||||
if (war.getSide1().isPlayerOnSide(uuid) && !war.getSide1().isPlayerSurrendered(uuid)) {
|
||||
TABHook.assignSide1WarSuffix(p, war);
|
||||
} else if (war.getSide2().isPlayerOnSide(uuid) && !war.getSide2().isPlayerSurrendered(uuid)) {
|
||||
TABHook.assignSide2WarSuffix(p, war);
|
||||
} else if (war.getSide1().isPlayerSurrendered(uuid) || war.getSide2().isPlayerSurrendered(uuid)) {
|
||||
TABHook.resetPrefix(p);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
TABHook.resetPrefix(p);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
private void onPlayerJoin(PlayerJoinEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
if (WarManager.getInstance().isPlayerInAnyWars(p)) {
|
||||
for (War war : WarManager.getInstance().getWars()) {
|
||||
if (war.isPlayerInWar(p)) {
|
||||
Side side = war.getPlayerSide(p);
|
||||
if (side != null) {
|
||||
side.addOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.github.alathra.AlathranWars.listeners.war;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class PlayerQuitListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerQuit(PlayerQuitEvent e) {
|
||||
final Player p = e.getPlayer();
|
||||
if (WarManager.getInstance().isPlayerInAnyWars(p)) {
|
||||
for (War war : WarManager.getInstance().getWars()) {
|
||||
if (war.isPlayerInWar(p)) {
|
||||
Side side = war.getPlayerSide(p);
|
||||
if (side != null) {
|
||||
side.removeOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.github.alathra.AlathranWars.listeners.war;
|
||||
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public class TownListener implements Listener {
|
||||
// TODO On town ruin, bow town out of any active wars, if leader of war surrender
|
||||
// TODO On town ruin, leave or cancel sieges where the town is present
|
||||
// TODO On town ruin, leave or cancel raids where the town is present
|
||||
// TODO Prevent town rename during war, siege, raid
|
||||
|
||||
/*
|
||||
TownMayorChangeEvent
|
||||
TownLeaveEvent
|
||||
TownPreMergeEvent
|
||||
TownPreRuinedEvent
|
||||
TownPreRenameEvent
|
||||
TownRemoveResidentEvent
|
||||
|
||||
PlayerJoinTown (add to war)
|
||||
PlayerLeaveTown (add to war)
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
|
||||
public class Config {
|
||||
public static de.leonhard.storage.Config get() {
|
||||
return Main.getInstance().getConfigManager().getConfig();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public abstract class DB {
|
||||
public static Connection get() throws SQLException {
|
||||
return Main.getInstance().getDataManager().getConnection();
|
||||
}
|
||||
|
||||
public static HikariDataSource getDataSource() {
|
||||
return Main.getInstance().getDataManager().getDataSource();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class SQLQueries {
|
||||
public static void initDB() {
|
||||
try (final Statement statement = DB.get().createStatement()) {
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_list` (
|
||||
`uuid` uuid NOT NULL DEFAULT uuid(),
|
||||
`name` tinytext NOT NULL,
|
||||
`label` tinytext NOT NULL,
|
||||
`side1` uuid NOT NULL DEFAULT uuid(),
|
||||
`side2` uuid NOT NULL DEFAULT uuid(),
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `side2` (`side2`),
|
||||
KEY `side1` (`side1`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides` (
|
||||
`war` uuid NOT NULL,
|
||||
`uuid` uuid NOT NULL,
|
||||
`side` tinytext NOT NULL,
|
||||
`team` tinytext NOT NULL,
|
||||
`name` tinytext NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
`siegeGrace` timestamp NOT NULL,
|
||||
`raidGrace` timestamp NOT NULL,
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `town` (`town`),
|
||||
KEY `war` (`war`),
|
||||
CONSTRAINT `war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_nations` (
|
||||
`side` uuid NOT NULL,
|
||||
`nation` uuid NOT NULL,
|
||||
KEY `side_nations` (`side`),
|
||||
CONSTRAINT `side_nations` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_nations_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`nation` uuid NOT NULL,
|
||||
KEY `side_nations_surrendered` (`side`),
|
||||
CONSTRAINT `side_nations_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_players` (
|
||||
`side` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `side_players` (`side`),
|
||||
CONSTRAINT `side_players` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_players_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `side_players_surrendered` (`side`),
|
||||
CONSTRAINT `side_players_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_towns` (
|
||||
`side` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
KEY `side_towns` (`side`),
|
||||
CONSTRAINT `side_towns` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_towns_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
KEY `side_towns_surrendered` (`side`),
|
||||
CONSTRAINT `side_towns_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges` (
|
||||
`war` uuid NOT NULL,
|
||||
`uuid` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
`siegeLeader` uuid NOT NULL,
|
||||
`endTime` timestamp NOT NULL,
|
||||
`siegeProgress` int(11) NOT NULL,
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `siege_war` (`war`),
|
||||
CONSTRAINT `siege_war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges_players_attackers` (
|
||||
`siege` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `siege_players_attackers` (`siege`),
|
||||
CONSTRAINT `siege_players_attackers` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges_players_defenders` (
|
||||
`siege` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `siege_players_defenders` (`siege`),
|
||||
CONSTRAINT `siege_players_defenders` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.executeLargeBatch();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveAll() {
|
||||
try (
|
||||
Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("INSERT INTO `wars_list` (`uuid`, `name`, `label`, `side1`, `side2`) VALUES (?, ?, ?, ?, ?) "
|
||||
+ "ON DUPLICATE KEY UPDATE `name` = ?, `label` = ?, `side1` = ?, `side2` = ?")
|
||||
) {
|
||||
// Save wars
|
||||
for (War war : WarManager.getInstance().getWars()) {
|
||||
// Insert
|
||||
warStatement.setString(1, war.getUUID().toString());
|
||||
warStatement.setString(2, war.getName());
|
||||
warStatement.setString(3, war.getLabel());
|
||||
warStatement.setString(4, war.getSide1().getUUID().toString());
|
||||
warStatement.setString(5, war.getSide2().getUUID().toString());
|
||||
|
||||
// Update
|
||||
warStatement.setString(6, war.getName());
|
||||
warStatement.setString(7, war.getLabel());
|
||||
warStatement.setString(8, war.getSide1().getUUID().toString());
|
||||
warStatement.setString(9, war.getSide2().getUUID().toString());
|
||||
|
||||
warStatement.executeUpdate();
|
||||
|
||||
// Save sides
|
||||
for (Side side : war.getSides()) {
|
||||
saveSide(con, side);
|
||||
}
|
||||
|
||||
// TODO Save sieges
|
||||
// for (Siege siege : war.getSieges()) {
|
||||
//
|
||||
// }
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSide(Connection con, Side side) throws SQLException {
|
||||
try (
|
||||
PreparedStatement sideStatement = con.prepareStatement("INSERT INTO `wars_sides` (`war`, `uuid`, `side`, `team`, `name`, `town`, `siegeGrace`, `raidGrace`) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
|
||||
+ "ON DUPLICATE KEY UPDATE `side` = ?, `team` = ?, `name` = ?, `town` = ?, `siegeGrace` = ?, `raidGrace` = ?");
|
||||
)
|
||||
{
|
||||
// Insert
|
||||
sideStatement.setString(1, side.getWar().getUUID().toString());
|
||||
sideStatement.setString(2, side.getUUID().toString());
|
||||
sideStatement.setString(3, side.getSide().toString());
|
||||
sideStatement.setString(4, side.getTeam().toString());
|
||||
sideStatement.setString(5, side.getName());
|
||||
sideStatement.setString(6, side.getTown().getUUID().toString());
|
||||
sideStatement.setTimestamp(7, Timestamp.from(side.getSiegeGrace()));
|
||||
sideStatement.setTimestamp(8, Timestamp.from(side.getRaidGrace()));
|
||||
|
||||
// Update
|
||||
sideStatement.setString(9, side.getSide().toString());
|
||||
sideStatement.setString(10, side.getTeam().toString());
|
||||
sideStatement.setString(11, side.getName());
|
||||
sideStatement.setString(12, side.getTown().getUUID().toString());
|
||||
sideStatement.setTimestamp(13, Timestamp.from(side.getSiegeGrace()));
|
||||
sideStatement.setTimestamp(14, Timestamp.from(side.getRaidGrace()));
|
||||
|
||||
sideStatement.executeUpdate();
|
||||
|
||||
saveSideNations(con, side, false);
|
||||
saveSideNations(con, side, true);
|
||||
saveSideTowns(con, side, false);
|
||||
saveSideTowns(con, side, true);
|
||||
saveSidePlayers(con, side, false);
|
||||
saveSidePlayers(con, side, true);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSideNations(Connection con, Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `nation`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"));
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (Nation nation : (surrendered ? side.getSurrenderedNations() : side.getNations())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, nation.getUUID().toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch(Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSideTowns(Connection con, Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `town`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"));
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (Town town : (surrendered ? side.getSurrenderedTowns() : side.getTowns())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, town.getUUID().toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch(Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSidePlayers(Connection con, Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `player`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"));
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (UUID uuid : (surrendered ? side.getSurrenderedPlayersIncludingOffline() : side.getPlayersIncludingOffline())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, uuid.toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch(Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Set<War> loadAll() {
|
||||
Set<War> wars = new HashSet<>();
|
||||
|
||||
try (
|
||||
Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_list`")
|
||||
) {
|
||||
// Load all wars
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get wars from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
// War data
|
||||
UUID uuid = UUID.fromString(warsResult.getString("uuid"));
|
||||
String name = warsResult.getString("name");
|
||||
String label = warsResult.getString("label");
|
||||
UUID side1UUID = UUID.fromString(warsResult.getString("side1"));
|
||||
UUID side2UUID = UUID.fromString(warsResult.getString("side2"));
|
||||
Side side1 = loadSide(con, uuid, side1UUID);
|
||||
Side side2 = loadSide(con, uuid, side2UUID);
|
||||
|
||||
// TODO Siege data
|
||||
|
||||
wars.add(new War(
|
||||
uuid,
|
||||
name,
|
||||
label,
|
||||
side1,
|
||||
side2,
|
||||
new HashSet<>(),
|
||||
new HashSet<>()
|
||||
));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return wars;
|
||||
}
|
||||
|
||||
public static Side loadSide(Connection con, UUID warUUID, UUID uuid) {
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_sides` WHERE `war` = ? AND `uuid` = ?")) {
|
||||
// Load side
|
||||
warStatement.setString(1, warUUID.toString());
|
||||
warStatement.setString(2, uuid.toString());
|
||||
ResultSet sideResult = warStatement.executeQuery();
|
||||
|
||||
if (sideResult == null)
|
||||
throw new SQLException("Failed to get side from DB");
|
||||
|
||||
sideResult.next();
|
||||
|
||||
// Side data
|
||||
BattleSide side = BattleSide.valueOf(sideResult.getString("side"));
|
||||
BattleTeam team = BattleTeam.valueOf(sideResult.getString("team"));
|
||||
String name = sideResult.getString("name");
|
||||
Town town = TownyAPI.getInstance().getTown(UUID.fromString(sideResult.getString("town")));
|
||||
Instant siegeGrace = sideResult.getTimestamp("siegeGrace").toInstant();
|
||||
Instant raidGrace = sideResult.getTimestamp("raidGrace").toInstant();
|
||||
|
||||
Set<UUID> players = loadSidePlayers(con, uuid, false);
|
||||
Set<UUID> playersSurrendered = loadSidePlayers(con, uuid, true);
|
||||
Set<Nation> nations = loadSideNations(con, uuid, false);
|
||||
Set<Nation> nationsSurrendered = loadSideNations(con, uuid, true);
|
||||
Set<Town> towns = loadSideTowns(con, uuid, false);
|
||||
Set<Town> townsSurrendered = loadSideTowns(con, uuid, true);
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
town,
|
||||
side,
|
||||
team,
|
||||
name,
|
||||
towns,
|
||||
nations,
|
||||
players,
|
||||
townsSurrendered,
|
||||
nationsSurrendered,
|
||||
playersSurrendered,
|
||||
siegeGrace,
|
||||
raidGrace
|
||||
);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Set<UUID> loadSidePlayers(Connection con, UUID sideUUID, boolean surrendered) {
|
||||
Set<UUID> players = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get players from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
players.add(UUID.fromString(warsResult.getString("player")));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
public static Set<Nation> loadSideNations(Connection con, UUID sideUUID, boolean surrendered) {
|
||||
Set<Nation> nations = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get nations from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
final UUID uuid = UUID.fromString(warsResult.getString("nation"));
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(uuid);
|
||||
if (nation == null) continue;
|
||||
|
||||
nations.add(nation);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return nations;
|
||||
}
|
||||
|
||||
public static Set<Town> loadSideTowns(Connection con, UUID sideUUID, boolean surrendered) {
|
||||
Set<Town> towns = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get towns from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
final UUID uuid = UUID.fromString(warsResult.getString("town"));
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(uuid);
|
||||
if (town == null) continue;
|
||||
|
||||
towns.add(town);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return towns;
|
||||
}
|
||||
|
||||
public static void deleteWar(War war) {
|
||||
try (
|
||||
Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("DELETE FROM `wars_list` WHERE `uuid` = ?");
|
||||
) {
|
||||
// Delete war data
|
||||
warStatement.setString(1, war.getUUID().toString());
|
||||
warStatement.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteSiege(Siege siege) {
|
||||
try (
|
||||
Connection con = DB.get();
|
||||
PreparedStatement siegesStatement = con.prepareStatement("DELETE FROM `wars_sieges` WHERE `uuid` = ?");
|
||||
) {
|
||||
// Delete siege data
|
||||
siegesStatement.setString(1, siege.getUUID().toString());
|
||||
siegesStatement.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.holder.WarManager;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class UUIDUtil {
|
||||
public static UUID generateWarUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarManager.getInstance().getWar(uuid) != null) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public static UUID generateSideUUID(@Nullable UUID previousSideUUID) {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarManager.getInstance().getSide(uuid) != null || uuid == previousSideUUID) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public static UUID generateSiegeUUID() {
|
||||
UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarManager.getInstance().getSiege(uuid) != null) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.Damageable;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class Utils {
|
||||
/**
|
||||
* Damages all gear in a players inventory
|
||||
*
|
||||
* @param p
|
||||
* @author ShermansWorld
|
||||
*/
|
||||
public static void damageAllGear(Player p) {
|
||||
for (ItemStack itemStack : p.getInventory().getContents()) {
|
||||
if (itemStack == null)
|
||||
continue;
|
||||
|
||||
if (weaponList.contains(itemStack.getType())) {
|
||||
setWeaponDurability(itemStack);
|
||||
}
|
||||
}
|
||||
|
||||
final ItemStack[] armor = p.getInventory().getArmorContents();
|
||||
|
||||
for (ItemStack itemStack : armor) {
|
||||
if (itemStack == null)
|
||||
continue;
|
||||
|
||||
if (armorList.contains(itemStack.getType())) {
|
||||
setArmorDurability(itemStack);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final ArrayList<Material> weaponList = new ArrayList<>(List.of(
|
||||
Material.NETHERITE_SWORD,
|
||||
Material.NETHERITE_AXE,
|
||||
Material.DIAMOND_SWORD,
|
||||
Material.DIAMOND_AXE,
|
||||
Material.IRON_SWORD,
|
||||
Material.IRON_AXE
|
||||
));
|
||||
|
||||
private static final ArrayList<Material> armorList = new ArrayList<>(List.of(
|
||||
Material.NETHERITE_HELMET,
|
||||
Material.NETHERITE_CHESTPLATE,
|
||||
Material.NETHERITE_LEGGINGS,
|
||||
Material.NETHERITE_BOOTS,
|
||||
Material.DIAMOND_HELMET,
|
||||
Material.DIAMOND_CHESTPLATE,
|
||||
Material.DIAMOND_LEGGINGS,
|
||||
Material.DIAMOND_BOOTS,
|
||||
Material.IRON_HELMET,
|
||||
Material.IRON_CHESTPLATE,
|
||||
Material.IRON_LEGGINGS,
|
||||
Material.IRON_BOOTS
|
||||
));
|
||||
|
||||
private static void setArmorDurability(@Nullable ItemStack itemStack) {
|
||||
if (itemStack == null)
|
||||
return;
|
||||
|
||||
ItemMeta meta = itemStack.getItemMeta();
|
||||
|
||||
if (meta == null)
|
||||
return;
|
||||
|
||||
if (!(meta instanceof Damageable damageable))
|
||||
return;
|
||||
|
||||
switch (itemStack.getType()) {
|
||||
case NETHERITE_HELMET -> {
|
||||
damageable.setDamage(damageable.getDamage() + 101);
|
||||
if (damageable.getDamage() > 400) {
|
||||
damageable.setDamage(406);
|
||||
}
|
||||
}
|
||||
case NETHERITE_CHESTPLATE -> {
|
||||
damageable.setDamage(damageable.getDamage() + 148);
|
||||
if (damageable.getDamage() > 450) {
|
||||
damageable.setDamage(591);
|
||||
}
|
||||
}
|
||||
case NETHERITE_LEGGINGS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 138);
|
||||
if (damageable.getDamage() > 420) {
|
||||
damageable.setDamage(554);
|
||||
}
|
||||
}
|
||||
case NETHERITE_BOOTS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 120);
|
||||
if (damageable.getDamage() > 370) {
|
||||
damageable.setDamage(480);
|
||||
}
|
||||
}
|
||||
case DIAMOND_HELMET -> {
|
||||
damageable.setDamage(damageable.getDamage() + 90);
|
||||
if (damageable.getDamage() > 280) {
|
||||
damageable.setDamage(362);
|
||||
}
|
||||
}
|
||||
case DIAMOND_CHESTPLATE -> {
|
||||
damageable.setDamage(damageable.getDamage() + 132);
|
||||
if (damageable.getDamage() > 410) {
|
||||
damageable.setDamage(527);
|
||||
}
|
||||
}
|
||||
case DIAMOND_LEGGINGS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 123);
|
||||
if (damageable.getDamage() > 380) {
|
||||
damageable.setDamage(494);
|
||||
}
|
||||
}
|
||||
case DIAMOND_BOOTS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 107);
|
||||
if (damageable.getDamage() > 330) {
|
||||
damageable.setDamage(428);
|
||||
}
|
||||
}
|
||||
case IRON_HELMET -> {
|
||||
damageable.setDamage(damageable.getDamage() + 41);
|
||||
if (damageable.getDamage() > 125) {
|
||||
damageable.setDamage(164);
|
||||
}
|
||||
}
|
||||
case IRON_CHESTPLATE -> {
|
||||
damageable.setDamage(damageable.getDamage() + 60);
|
||||
if (damageable.getDamage() > 190) {
|
||||
damageable.setDamage(239);
|
||||
}
|
||||
}
|
||||
case IRON_LEGGINGS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 56);
|
||||
if (damageable.getDamage() > 180) {
|
||||
damageable.setDamage(224);
|
||||
}
|
||||
}
|
||||
case IRON_BOOTS -> {
|
||||
damageable.setDamage(damageable.getDamage() + 48);
|
||||
if (damageable.getDamage() > 150) {
|
||||
damageable.setDamage(194);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
itemStack.setItemMeta(damageable);
|
||||
}
|
||||
|
||||
private static void setWeaponDurability(@Nullable ItemStack itemStack) {
|
||||
if (itemStack == null)
|
||||
return;
|
||||
|
||||
ItemMeta meta = itemStack.getItemMeta();
|
||||
|
||||
if (meta == null)
|
||||
return;
|
||||
|
||||
if (!(meta instanceof Damageable damageable))
|
||||
return;
|
||||
|
||||
switch (itemStack.getType()) {
|
||||
case NETHERITE_SWORD, NETHERITE_AXE -> {
|
||||
damageable.setDamage(damageable.getDamage() + 507);
|
||||
if (damageable.getDamage() > 2000) {
|
||||
damageable.setDamage(2030);
|
||||
}
|
||||
}
|
||||
case DIAMOND_SWORD, DIAMOND_AXE -> {
|
||||
damageable.setDamage(damageable.getDamage() + 390);
|
||||
if (damageable.getDamage() > 1500) {
|
||||
damageable.setDamage(1560);
|
||||
}
|
||||
}
|
||||
case IRON_SWORD, IRON_AXE, TRIDENT -> {
|
||||
damageable.setDamage(damageable.getDamage() + 62);
|
||||
if (damageable.getDamage() > 200) {
|
||||
damageable.setDamage(249);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
itemStack.setItemMeta(damageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param worldCoord worldCoord
|
||||
* @return List of connected chunks
|
||||
* @author NinjaMandalorian
|
||||
*/
|
||||
private static ArrayList<WorldCoord> getAdjCells(WorldCoord worldCoord) {
|
||||
ArrayList<WorldCoord> worldCoords = new ArrayList<>();
|
||||
|
||||
int[][] XZarray = new int[][]{
|
||||
{-1, 0},
|
||||
{1, 0},
|
||||
{0, -1},
|
||||
{0, 1}
|
||||
}; // Array that contains relative orthogonal shifts from origin
|
||||
|
||||
for (int[] pair : XZarray) {
|
||||
// Constructs new WorldCoord for comparison
|
||||
WorldCoord tCoord = new WorldCoord(worldCoord.getWorldName(), worldCoord.getX() + pair[0], worldCoord.getZ() + pair[1]);
|
||||
if (tCoord.getTownOrNull() != null && tCoord.getTownOrNull() == worldCoord.getTownOrNull()) {
|
||||
// If in town, and in same town, adds to return list
|
||||
worldCoords.add(tCoord);
|
||||
}
|
||||
}
|
||||
return worldCoords;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all adjacently connected townblocks
|
||||
*
|
||||
* @param chunkCoord - WorldCoord to check at
|
||||
* @return List of WorldCoords
|
||||
* @author NinjaMandalorian
|
||||
*/
|
||||
public static ArrayList<WorldCoord> getCluster(WorldCoord chunkCoord) {
|
||||
// worldCoords is the returning array, searchList is the to-search list.
|
||||
ArrayList<WorldCoord> worldCoords = new ArrayList<>();
|
||||
ArrayList<WorldCoord> searchList = new ArrayList<>(Collections.singletonList(chunkCoord)); // Adds 1st chunk to list
|
||||
|
||||
// Iterates through searchList, to create a full list of every adjacent cell.
|
||||
while (!searchList.isEmpty()) {
|
||||
WorldCoord toSearch = searchList.get(0); // Gets WorldCoord
|
||||
ArrayList<WorldCoord> adjCells = getAdjCells(toSearch); // Gets adjacent cells
|
||||
|
||||
for (WorldCoord cell : adjCells) {
|
||||
if (worldCoords.contains(cell)) continue; // If in final list, ignore.
|
||||
if (searchList.contains(cell)) continue; // If in to-search list, ignore
|
||||
|
||||
// Otherwise, add to search-list.
|
||||
searchList.add(cell);
|
||||
}
|
||||
|
||||
// Removes from search list and adds to finished list. After checking all adjacent chunks.
|
||||
searchList.remove(toSearch);
|
||||
worldCoords.add(toSearch);
|
||||
}
|
||||
|
||||
return worldCoords; // Returns list
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
public class UtilsChat {
|
||||
public static String getPrefix() {
|
||||
return "<dark_gray>[<gradient:#D72A09:#B01F03>War<dark_gray>]<reset> ";
|
||||
}
|
||||
|
||||
public static String color(final String input) {
|
||||
return ChatColor.translateAlternateColorCodes('&', input);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user