refactor: rename main package

This commit is contained in:
darksaid98 committed 2024-02-23 02:14:36 +01:00
1 parent 45f7415c6b
commit e52dc755b2
87 files changed

No files matched your search

@@ -0,0 +1,102 @@
package com.github.alathra.alathranwars;
import com.github.alathra.alathranwars.commands.CommandManager;
import com.github.alathra.alathranwars.config.ConfigHandler;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.db.DatabaseHandler;
import com.github.alathra.alathranwars.db.DatabaseQueries;
import com.github.alathra.alathranwars.hooks.HookManager;
import com.github.alathra.alathranwars.items.WarItemRegistry;
import com.github.alathra.alathranwars.listeners.ListenerHandler;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.MorePaperLib;
public class AlathranWars extends JavaPlugin {
public static @Nullable Economy econ = null;
private static MorePaperLib paperLib;
private static AlathranWars instance;
private ConfigHandler configHandler;
private DatabaseHandler databaseHandler;
private ListenerHandler listenerHandler;
private CommandManager commandManager;
private HookManager hookManager;
@SuppressWarnings("rawtypes")
private boolean setupEconomy() {
if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
@SuppressWarnings("unchecked") final @Nullable RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) this.getServer()
.getServicesManager().getRegistration((Class) Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
public void onLoad() {
instance = this;
paperLib = new MorePaperLib(instance);
WarController.getInstance();
configHandler = new ConfigHandler(instance);
databaseHandler = new DatabaseHandler(instance);
commandManager = new CommandManager(instance);
listenerHandler = new ListenerHandler(instance);
hookManager = new HookManager();
configHandler.onLoad();
databaseHandler.onLoad();
commandManager.onLoad();
listenerHandler.onLoad();
hookManager.onLoad();
}
public void onEnable() {
this.saveDefaultConfig();
new WarItemRegistry();
setupEconomy();
configHandler.onEnable();
databaseHandler.onEnable();
commandManager.onEnable();
listenerHandler.onEnable();
hookManager.onEnable();
WarController.getInstance().loadAll();
}
public void onDisable() {
getPaperLib().scheduling().cancelGlobalTasks();
DatabaseQueries.saveAll();
commandManager.onDisable();
listenerHandler.onDisable();
hookManager.onDisable();
databaseHandler.onDisable();
configHandler.onDisable();
}
@NotNull
public static AlathranWars getInstance() {
return instance;
}
public static MorePaperLib getPaperLib() {
return paperLib;
}
@NotNull
public DatabaseHandler getDataHandler() {
return databaseHandler;
}
@NotNull
public ConfigHandler getConfigHandler() {
return configHandler;
}
}
@@ -0,0 +1,21 @@
package com.github.alathra.alathranwars;
/**
* Implemented in classes that should support being reloaded IE executing the methods during runtime after startup.
*/
public interface Reloadable {
/**
* On plugin load.
*/
void onLoad();
/**
* On plugin enable.
*/
void onEnable();
/**
* On plugin disable.
*/
void onDisable();
}
@@ -0,0 +1,127 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import com.github.alathra.alathranwars.items.WarItemRegistry;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import dev.jorel.commandapi.CommandAPIBukkit;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.PlayerArgument;
import dev.jorel.commandapi.arguments.StringArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class AdminCommands {
public AdminCommands() {
new CommandAPICommand("alathranwarsadmin")
.withAliases("awa", "wa", "waradmin")
.withPermission("AlathranWars.admin")
.withSubcommands(
commandItem(),
commandWar(),
commandSiege(),
commandNames()
)
.executes((sender, args) -> {
if (args.count() == 0)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments.").build());
})
.register();
}
private CommandAPICommand commandItem() {
return new CommandAPICommand("item")
.withArguments(
new StringArgument("item")
.replaceSuggestions(
ArgumentSuggestions.strings(
CommandUtil.getWarItems()
)
),
new IntegerArgument("amount").setOptional(true),
new PlayerArgument("player").setOptional(true)
)
.executesPlayer((Player sender, CommandArguments args) -> {
// Parse item
if (!(args.get("item") instanceof String argItem))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid item argument.").build());
@Nullable ItemStack stack;
if (argItem.contains(AlathranWars.getInstance().getName().toLowerCase())) {
stack = WarItemRegistry.getInstance().getOrNullNamespace(argItem);
} else {
stack = WarItemRegistry.getInstance().getOrNull(argItem);
}
if (stack == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The item is not an AlathranWars item.").build());
// Parse amount
int argAmount = (int) args.getOptional("amount").orElse(1);
if (argAmount > 64)
argAmount = 64;
else if (argAmount < 1) {
argAmount = 1;
}
stack.setAmount(argAmount);
// Determine who gets the item
Player argPlayer = (Player) args.getOptional("player").orElse(sender);
// Give
argPlayer.getInventory().addItem(stack);
final @Nullable Component itemName = stack.getItemMeta() == null ? ColorParser.of(stack.toString()).build() : stack.getItemMeta().displayName();
sender.sendMessage(
ColorParser.of(
"<prefix>Gave <amount>x <item> to <player>."
)
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("amount", String.valueOf(stack.getAmount()))
.parseMinimessagePlaceholder("item", itemName)
.parseMinimessagePlaceholder("player", argPlayer.getName())
.build()
);
});
}
private CommandAPICommand commandWar() {
return new CommandAPICommand("war")
.withSubcommands(
WarCommands.commandCreate(true),
WarCommands.commandDelete(true),
WarCommands.commandJoin(true),
WarCommands.commandJoinNear(),
WarCommands.commandSurrender(true),
WarCommands.commandList(),
WarCommands.commandInfo(),
WarCommands.commandKick()
);
}
private CommandAPICommand commandSiege() {
return new CommandAPICommand("siege")
.withSubcommands(
SiegeCommands.commandStart(true),
SiegeCommands.commandStop(true),
SiegeCommands.commandAbandon(true),
SiegeCommands.commandSurrender(true),
SiegeCommands.commandList()
);
}
private CommandAPICommand commandNames() {
return new CommandAPICommand("updatenames")
.executesPlayer((player, commandArguments) -> {
Bukkit.getOnlinePlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
});
}
}
@@ -0,0 +1,30 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.AlathranWars;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig;
public class CommandManager {
private final AlathranWars instance;
public CommandManager(AlathranWars instance) {
this.instance = instance;
}
public void onLoad() {
CommandAPI.onLoad(new CommandAPIBukkitConfig(instance).shouldHookPaperReload(true).silentLogs(true));
}
public void onEnable() {
CommandAPI.onEnable();
// Register commands
new WarCommands();
new SiegeCommands();
new AdminCommands();
}
public void onDisable() {
CommandAPI.onDisable();
}
}
@@ -0,0 +1,669 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.enums.CommandArgsSiege;
import com.github.alathra.alathranwars.enums.CommandArgsWar;
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.SuggestionInfo;
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 org.bukkit.Bukkit;
import org.bukkit.Statistic;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
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(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
return TownyAPI.getInstance().getNation(argNationName);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
final @NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
return TownyAPI.getInstance().getTown(argTownName);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
final @NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
if (!hideNationsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
return TownyAPI.getInstance().getNation(argNationName);
@Nullable Nation nation = TownyAPI.getInstance().getNation(argNationName);
if (war.getNations().contains(nation) || war.getSurrenderedNations().contains(nation))
return nation;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation is already at war!").parseLegacy().build());
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
final @NotNull List<String> nationNames = TownyHook.getNations()
.stream()
.map(Nation::getName)
.sorted()
.collect(Collectors.toList());
final @NotNull List<String> townNames = TownyHook.getTowns()
.stream()
.map(Town::getName)
.sorted()
.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 @NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
if (!hideTownsInWar || !(info.previousArgs().get(warNodeName) instanceof War war))
return TownyAPI.getInstance().getTown(argTownName);
@Nullable Town town = TownyAPI.getInstance().getTown(argTownName);
if (war.getTowns().contains(town) || war.getSurrenderedTowns().contains(town))
return town;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is already at war!").parseLegacy().build());
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
final @NotNull 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 @NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
@Nullable Nation nation = TownyAPI.getInstance().getNation(info.input());
if (nation == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
if (!war.isNationInWar(nation))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(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(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
@Nullable Town town = TownyAPI.getInstance().getTown(info.input());
if (town == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
if (!war.isTownInWar(town))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(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 town or nation UUID
*/
static public Argument<UUID> customTownAndNationArgument(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.getUUID();
@Nullable Nation nation = TownyAPI.getInstance().getNation(argTownOrNationName);
if (nation != null)
return nation.getUUID();
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
ColorParser.of(UtilsChat.getPrefix() + "<red>The town or nation <name> does not exist!")
.parseMinimessagePlaceholder("name", argTownOrNationName)
.build()
);
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
final @NotNull List<String> nationNames = TownyHook.getNations()
.stream()
.map(Nation::getName)
.sorted()
.collect(Collectors.toList());
final @NotNull List<String> townNames = TownyHook.getTowns()
.stream()
.map(Town::getName)
.sorted()
.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 @NotNull 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;
}));
}
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(ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!").parseLegacy().build());
@Nullable Town town = TownyAPI.getInstance().getTown(info.input());
if (town == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
if (!war.isTownInWar(town))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
if (checkIfSieged) {
for (@NotNull Siege siege : WarController.getInstance().getSieges()) {
if (siege.getTown().getUUID() == town.getUUID())
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(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 @NotNull 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()
.toList()
);
} else if (war.getSide2().isPlayerOnSide(p)) {
townNames.addAll(war.getSide1().getTowns()
.stream()
.map(TownyObject::getName)
.sorted()
.toList()
);
}
}
return townNames;
}));
}
public static Argument<Siege> siegeSiegeArgument(String nodeName, final boolean isAdmin, final CommandArgsSiege checkSiege, final String playerNodeName) {
return new CustomArgument<>(new StringArgument(nodeName), info -> {
final String argSiegeName = info.input();
@Nullable UUID siegeUUID = null;
for (Siege siege : WarController.getInstance().getSieges()) {
if (siege.getName().equals(argSiegeName)) {
siegeUUID = siege.getUUID();
}
}
final @Nullable Siege siege = WarController.getInstance().getSiege(siegeUUID);
if (siege == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The siege <siege> does not exist!").parseMinimessagePlaceholder("siege", argSiegeName).build());
switch (checkSiege) {
case IN_SIEGE -> {
if (isAdmin) {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
if (!siege.isPlayerInSiege(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
if (!siege.isPlayerInSiege(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").build());
}
}
case OUT_SIEGE -> {
if (isAdmin) {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
if (siege.isPlayerInSiege(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
if (siege.isPlayerInSiege(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").build());
}
}
}
return siege;
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> switch (checkSiege) {
case ALL_SIEGES -> siegeAll(info, isAdmin);
case IN_SIEGE -> siegeInside(info, isAdmin, playerNodeName);
case OUT_SIEGE -> siegeOutside(info, isAdmin, playerNodeName);
}));
}
private static List<String> siegeAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
return WarController.getInstance().getSieges().stream().map(Siege::getName).toList();
}
private static List<String> siegeOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
List<String> siegeNames = new ArrayList<>();
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
}
}
return siegeNames;
}
private static List<String> siegeInside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
List<String> siegeNames = new ArrayList<>();
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
}
}
return siegeNames;
}
public static Argument<War> warWarArgument(String nodeName, final boolean isAdmin, final CommandArgsWar checkWar, final String playerNodeName) {
return new CustomArgument<>(new StringArgument(nodeName), info -> {
final String argWarName = info.input();
final @Nullable War war = WarController.getInstance().getWar(argWarName);
if (war == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war <war> does not exist!").parseMinimessagePlaceholder("war", argWarName).build());
switch (checkWar) {
case IN_WAR -> {
if (isAdmin) {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
if (!war.isPlayerInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
if (!war.isPlayerInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").parseLegacy().build());
}
}
case OUT_WAR -> {
if (isAdmin) {
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
if (war.isPlayerInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
if (war.isPlayerInWar(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").parseLegacy().build());
}
}
}
return war;
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> switch (checkWar) {
case ALL_WARS -> warsAll(info, isAdmin);
case IN_WAR -> warsInside(info, isAdmin, playerNodeName);
case OUT_WAR -> warsOutside(info, isAdmin, playerNodeName);
}));
}
private static List<String> warsAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
return WarController.getInstance().getWarNames();
}
private static List<String> warsOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
List<String> warNames = new ArrayList<>();
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
}
}
return warNames;
}
private static List<String> warsInside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
List<String> warNames = new ArrayList<>();
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
}
} else {
if (info.sender() instanceof Player player) {
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
}
}
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(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").parseLegacy().build());
final String argSideName = info.input();
if (!war.isSideValid(argSideName))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The side does not exist.").parseLegacy().build());
final @Nullable Side side = war.getSide(argSideName);
if (side == null)
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(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(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
if (side.getPlayers().contains(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already on that side.").parseLegacy().build());
} else {
if (!(info.sender() instanceof Player player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
if (side.getPlayers().contains(player))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(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 @NotNull List<String> sideNames = new ArrayList<>();
if (checkIfIn) {
if (isAdmin) {
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
for (@NotNull Side side : war.getSides()) {
if (!side.getPlayers().contains(player))
sideNames.add(side.getName());
}
}
} else {
if (info.sender() instanceof Player player) {
for (@NotNull 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;
}
));
}
public static Argument<String> warTargetCreateArgument(final String nodeName, final String warNodeName, final boolean isAdmin) {
return new CustomArgument<>(new StringArgument(nodeName), info -> {
final String argTargetName = info.input();
if (!(info.previousArgs().get(warNodeName) instanceof War war))
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war.").parseLegacy().build());
final boolean isNation = TownyAPI.getInstance().getNation(argTargetName) != null;
final boolean isTown = TownyAPI.getInstance().getTown(argTargetName) != null;
final boolean isPlayer = Bukkit.getPlayer(argTargetName) != null;
if (isNation && !war.getNations().stream().map(Nation::getName).toList().contains(argTargetName))
return argTargetName;
if (isTown && !war.getTowns().stream().map(Town::getName).toList().contains(argTargetName))
return argTargetName;
if (isPlayer && !war.getPlayers().stream().map(Player::getName).toList().contains(argTargetName))
return argTargetName;
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid target.").build());
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> { // Returns list of every nation, town and player not in the war
if (!(info.previousArgs().get(warNodeName) instanceof War war))
return Collections.emptyList();
// Get all participants in war into list
final List<String> inWar = Stream.concat(
war.getPlayers().stream().map(Player::getName),
Stream.concat(
war.getNations().stream().map(Nation::getName),
war.getTowns().stream().map(Town::getName)
)
).toList();
// Make list of all nations, towns and player
final List<String> players = Bukkit.getOnlinePlayers().stream().map(Player::getName).toList();
final List<String> towns = TownyAPI.getInstance().getTowns().stream().map(Town::getName).toList();
final List<String> nations = TownyAPI.getInstance().getNations().stream().map(Nation::getName).toList();
return Stream.concat(
nations.stream(),
Stream.concat(
towns.stream(),
players.stream()
)
)
.filter(string -> !inWar.contains(string)) // Remove participants in te war
.toList();
}
));
}
/**
* @param player player to check
* @return 0, 1, 2 (good to go, insufficient join, insufficient playtime)
*/
public static int isPlayerMinuteman(String player) {
@Nullable 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 (AlathranWars.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 * AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge"))
out = 1;
}
if (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
//check playtime, if its less than min its true
if (playTicks < (AlathranWars.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 @NotNull List<String> getWarItems() {
return new ArrayList<>(WarItemRegistry.getInstance().getItemRegistry().keySet());
}
}
@@ -0,0 +1,236 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
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.Resident;
import com.palmergames.bukkit.towny.object.Town;
import dev.jorel.commandapi.CommandAPIBukkit;
import dev.jorel.commandapi.CommandAPICommand;
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.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.Set;
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.ALL_SIEGES;
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.IN_SIEGE;
import static com.github.alathra.alathranwars.enums.CommandArgsWar.ALL_WARS;
import static com.github.alathra.alathranwars.enums.CommandArgsWar.IN_WAR;
public class SiegeCommands {
public SiegeCommands() {
new CommandAPICommand("siege")
.withSubcommands(
commandStart(false),
commandStop(false),
commandAbandon(false),
commandSurrender(false),
commandList()
)
.executesPlayer((sender, args) -> {
if (args.count() == 0)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /siege help").build());
})
.register();
}
public static CommandAPICommand commandStart(boolean asAdmin) {
return new CommandAPICommand("start")
// .withPermission("AlathranWars.admin")
.withArguments(
CommandUtil.warWarArgument(
"war",
asAdmin,
asAdmin ? ALL_WARS : IN_WAR,
""
),
CommandUtil.customSiegeAttackableTownArgument(
"town",
"war",
false,
true
),
new PlayerArgument("leader")
.setOptional(!asAdmin)
.withPermission("AlathranWars.admin")/*,
new BooleanArgument("minutemen")
.setOptional(true)
.withPermission("AlathranWars.admin")*/
)
.executesPlayer((Player p, CommandArguments args) -> siegeStart(p, args, asAdmin));
}
public static CommandAPICommand commandStop(boolean asAdmin) {
return new CommandAPICommand("stop")
.withPermission("AlathranWars.admin")
.withArguments(
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
)
.executesPlayer((Player p, CommandArguments args) -> siegeStop(p, args, asAdmin));
}
public static CommandAPICommand commandAbandon(boolean asAdmin) {
return new CommandAPICommand("abandon")
.withArguments(
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
)
.executesPlayer((Player p, CommandArguments args) -> siegeAbandon(p, args, asAdmin));
}
public static CommandAPICommand commandSurrender(boolean asAdmin) {
return new CommandAPICommand("surrender")
.withArguments(
CommandUtil.siegeSiegeArgument("siege", asAdmin, asAdmin ? ALL_SIEGES : IN_SIEGE, "player")
)
.executesPlayer((Player p, CommandArguments args) -> siegeSurrender(p, args, asAdmin));
}
public static CommandAPICommand commandList() {
return new CommandAPICommand("list")
.executesPlayer(SiegeCommands::siegeList);
}
protected static void siegeStart(@NotNull Player sender, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
if (!(args.get("war") instanceof final @NotNull War war))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to specify a war.").build());
if (!(args.get("town") instanceof final @NotNull Town town))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to specify a town.").build());
final @NotNull Player siegeLeader = (Player) args.getOptional("leader").orElse(sender);
// Player participance check
@Nullable Side side = war.getPlayerSide(siegeLeader);
if (side == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in this war.").build());
if (side.isPlayerSurrendered(siegeLeader))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You have surrendered and cannot participate in this war.").build());
if (side.isSiegeGraceActive() && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(
ColorParser.of("<red>Your side needs to wait <time> minutes before starting another siege.")
.parseMinimessagePlaceholder("time", String.valueOf(side.getSiegeGraceCooldown().toMinutes()))
.build()
);
// Attacking own side
if (side.isTownOnSide(town) && !side.isTownSurrendered(town)) {
if (asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot attack your own side.").build());
else
siegeLeader.sendMessage(ColorParser.of("<red>You cannot attack your own towns.").build());
return;
}
final Location location = siegeLeader.getLocation();
final Location townLocation = town.getSpawnOrNull();
if (townLocation == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>The town you are attacking doesn't have a spawn point set. Contact admin.").build());
if (!location.getWorld().equals(townLocation.getWorld()))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be in the same world as the town you're attacking!").build());
if (location.distance(townLocation) >= Siege.BATTLEFIELD_START_MAX_RANGE && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be within <range> blocks of the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MAX_RANGE)).build());
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be further than <range> blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to have $<amount> to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
side.setSiegeGrace();
Siege siege = new Siege(war, town, siegeLeader);
war.addSiege(siege);
Bukkit.broadcast(
ColorParser.of(
"<prefix>The town of <town> has been put to siege by <side>!"
)
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", town.getName())
.parseMinimessagePlaceholder("side", siege.getAttackerSide().getName())
.build()
);
siege.start();
}
private static void siegeStop(@NotNull Player sender, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
if (!(args.get("siege") instanceof final @NotNull Siege siege))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
siege.equalWin(BattleVictoryReason.ADMIN_COMMAND);
}
private static void siegeAbandon(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
if (!(args.get("siege") instanceof final @NotNull Siege siege))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
@NotNull OfflinePlayer siegeLeader = siege.getSiegeLeader();
if (siegeLeader != p && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not the leader of this siege.").build());
siege.defendersWin(BattleVictoryReason.OPPONENT_RETREAT);
}
private static void siegeSurrender(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
if (!(args.get("siege") instanceof final @NotNull Siege siege))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
Town town = siege.getTown();
@Nullable Resident res = TownyAPI.getInstance().getResident(p);
if (res == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
final boolean canKingSurrender = (res.hasNation() && town.hasNation() && res.getNationOrNull().equals(town.getNationOrNull()) && res.isKing());
final boolean canMayorSurrender = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor());
if (!asAdmin && !canKingSurrender && !canMayorSurrender)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender this town.").build());
siege.attackersWin(BattleVictoryReason.OPPONENT_RETREAT);
}
private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
Set<Siege> sieges = WarController.getInstance().getSieges();
if (sieges.isEmpty()) {
sender.sendMessage(ColorParser.of("<red>There are no sieges at the moment.").build());
return;
}
final StringBuilder msg = new StringBuilder();
for (Siege siege : sieges) {
msg.append("\n<white><bold>%s<reset>".formatted(siege.getName()));
msg.append("\n <grey>Progress: <white>%.0f%%".formatted(siege.getSiegeProgressPercentage() * 100));
msg.append("\n <grey>Remaining: <white>%s minutes".formatted(String.valueOf(Duration.between(Instant.now(), siege.getEndTime()).toMinutesPart())));
msg.append("\n");
}
sender.sendMessage(
ColorParser.of(
msg.toString()
).build()
);
}
}
@@ -0,0 +1,500 @@
package com.github.alathra.alathranwars.commands;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
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.BooleanArgument;
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 net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import static com.github.alathra.alathranwars.enums.CommandArgsWar.*;
public class WarCommands {
public WarCommands() {
new CommandAPICommand("war")
.withSubcommands(
commandCreate(false),
commandDelete(false),
commandJoin(false),
commandSurrender(false),
commandList(),
commandInfo()
)
.executesPlayer((sender, args) -> {
if (args.count() == 0)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid Arguments. /war help").build());
})
.register();
}
public static CommandAPICommand commandCreate(boolean asAdmin) {
return new CommandAPICommand("create")
.withPermission("AlathranWars.admin")
.withArguments(
CommandUtil.customTownAndNationArgument("side1", "war", false),
CommandUtil.customTownAndNationArgument("side2", "war", false),
new BooleanArgument("event"),
new GreedyStringArgument("warlabel")
.replaceSuggestions(
ArgumentSuggestions.stringCollection(info -> List.of(
"Nations War of Conquest",
"Nations War for Survival",
"Nations War of Liberation"
))
)
)
.executesPlayer(WarCommands::warCreate);
}
public static CommandAPICommand commandDelete(boolean asAdmin) {
return new CommandAPICommand("delete")
.withPermission("AlathranWars.admin")
.withArguments(
CommandUtil.warWarArgument("war", asAdmin, ALL_WARS, "")
)
.executesPlayer(WarCommands::warDelete);
}
public static CommandAPICommand commandJoin(boolean asAdmin) {
return new CommandAPICommand("join")
.withArguments(
CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : OUT_WAR, ""),
CommandUtil.warSideCreateArgument("side", "war", asAdmin, !asAdmin, ""),
CommandUtil.warTargetCreateArgument("target", "war", asAdmin).setOptional(!asAdmin)
// new PlayerArgument("player").setOptional(true).withPermission("AlathranWars.admin.join"),
// new PlayerArgument("nation").setOptional(true).withPermission("AlathranWars.admin.join"),
// new PlayerArgument("town").setOptional(true).withPermission("AlathranWars.admin.join")
)
.executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, asAdmin));
}
public static CommandAPICommand commandJoinNear() {
return new CommandAPICommand("joinnear")
.withPermission("AlathranWars.admin")
.withArguments(
CommandUtil.warWarArgument("war", true, ALL_WARS, ""),
CommandUtil.warSideCreateArgument("side", "war", true, false, "")
)
.executesPlayer((Player p, CommandArguments args) -> warJoinNear(p, args, true));
}
public static CommandAPICommand commandSurrender(boolean asAdmin) {
return new CommandAPICommand("surrender")
.withArguments(
CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : IN_WAR, "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(WarCommands::warList);
}
public static CommandAPICommand commandInfo() {
return new CommandAPICommand("info")
.withArguments(
CommandUtil.warWarArgument("war", false, ALL_WARS, "player")
)
.executesPlayer(WarCommands::warInfo);
}
public static CommandAPICommand commandKick() {
return new CommandAPICommand("kick")
.withArguments(
CommandUtil.warWarArgument("war", true, ALL_WARS, "player"),
new PlayerArgument("player")
.setOptional(true)
.withPermission("AlathranWars.admin")
)
.executesPlayer(WarCommands::warKick);
}
protected static void warCreate(CommandSender p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
if (!(args.get("warlabel") instanceof final String argLabel))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war label.").build());
if (Objects.equals(args.get("side1"), args.get("side2")))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Cannot declare war on oneself.").build());
final boolean event = (boolean) args.getOrDefault("event", false);
final UUID uuid1 = (UUID) args.get("side1");
final UUID uuid2 = (UUID) args.get("side2");
// Create new war depending on what argument was specified
@Nullable Town town1 = TownyAPI.getInstance().getTown(uuid1);
@Nullable Town town2 = TownyAPI.getInstance().getTown(uuid2);
// Automatically escalate to nation level if possible
@Nullable Nation nation1 = town1 == null ? TownyAPI.getInstance().getNation(uuid1) : town1.getNationOrNull();
@Nullable Nation nation2 = town2 == null ? TownyAPI.getInstance().getNation(uuid2) : town2.getNationOrNull();
// Implement permission checking here if this is ever going to be exposed to players
// Create war depending on what args have been passed, attempt to create nation wars first
WarBuilder builder = new WarBuilder()
.setUuid(UUID.randomUUID())
.setLabel(argLabel)
.setEvent(event);
if (nation1 != null) {
if (nation2 != null) { // Nation vs Nation
// Allow civil wars
if (nation2.getUUID() != nation1.getUUID()) {
builder
.setAggressor(nation1)
.setVictim(nation2);
} else {
builder
.setAggressor(town1)
.setVictim(town2);
}
} else if (town2 != null) { // Nation vs Town
builder
.setAggressor(nation1)
.setVictim(town2);
}
} else if (town1 != null) {
if (town2 != null) { // Town vs Town
builder
.setAggressor(town1)
.setVictim(town2);
} else if (nation2 != null) { // Nation vs Town
builder
.setAggressor(town1)
.setVictim(nation2);
}
}
try {
builder.create(); // TODO Add war to list
} catch (SideCreationException e) {
throw new RuntimeException(e);
}
}
private static void warDelete(Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
war.draw();
}
protected static void warJoin(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
if (!(args.get("side") instanceof final Side side))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
// The target or empty string
if (!(args.getOptional("target").orElse("") instanceof String targetString))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid target name.").build());
// The target player or sender of the command
Player targetPlayer = args.getOptional("target").map(o -> Bukkit.getPlayer((String) o)).orElse(p);
// Get the player resident
@Nullable Resident res = TownyAPI.getInstance().getResident(targetPlayer);
if (res == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
// Get nations and towns
@Nullable Nation nation = res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString);
@Nullable Town town = res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString);
final boolean isArgNation = nation != null;
final boolean isArgTown = town != null;
final boolean isArgPlayer = targetPlayer != null;
// If no valid targets
if ((!isArgNation && !isArgTown && !isArgPlayer))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid target.").build());
// Check if player can validly join or not
final boolean canKingJoin = (res.hasNation() && res.getNationOrNull().equals(nation) && res.isKing() && nation.isKing(res));
final boolean canMayorJoin = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor() && town.isMayor(res));
if (!war.isEventWar()) {
// Join nation into war
if (isArgNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) {
side.addNation(nation);
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player));
Bukkit.broadcast(
ColorParser.of(
"<prefix>The nation of <nation> joined the war of <war> on the side of <side>."
)
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("nation", nation.getName())
.parseMinimessagePlaceholder("war", war.getLabel())
.parseMinimessagePlaceholder("side", side.getName())
.build()
);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>You entered the war of <war>!")
.parseMinimessagePlaceholder("war", war.getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
player.showTitle(warTitle);
player.playSound(warSound);
});
return;
} else if (town == null && nation != null && (!canKingJoin || !asAdmin)) {
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Nation is already in that war.").build());
}
// Join town into war
if (isArgTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) {
side.addTown(town);
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player));
Bukkit.broadcast(
ColorParser.of(
"<prefix>The town of <town> joined the war of <war> on the side of <side>."
)
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", town.getName())
.parseMinimessagePlaceholder("war", war.getLabel())
.parseMinimessagePlaceholder("side", side.getName())
.build()
);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>You entered the war of <war>!")
.parseMinimessagePlaceholder("war", war.getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
player.showTitle(warTitle);
player.playSound(warSound);
});
return;
} else if (targetPlayer == null && town != null && !canMayorJoin) {
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Town is already in that war.").build());
}
}
// Join player into war
if (isArgPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) {
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
side.addPlayer(targetPlayer);
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>You entered the war of <war>!")
.parseMinimessagePlaceholder("war", war.getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
targetPlayer.showTitle(warTitle);
targetPlayer.playSound(warSound);
return;
} else if (!asAdmin) {
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Players cannot individually join wars.").build());
} else {
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Player is already in that war.").build());
}
// Join player into war
// if (war.isPlayerInWar(player))
// throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are already in this war.").build());
/*for (@NotNull Siege siege : war.getSieges()) {
if (siege.getAttackerSide().equals(side)) {
siege.addPlayer(argPlayer, BattleSide.ATTACKER);
} else {
siege.addPlayer(argPlayer, BattleSide.DEFENDER);
}
}*/
}
protected static void warJoinNear(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
if (!(args.get("side") instanceof final Side side))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
final Location location = p.getLocation();
for (Player targetPlayer : Bukkit.getOnlinePlayers()) {
if (p.equals(targetPlayer)) continue;
final Location targetLocation = targetPlayer.getLocation();
if (!location.getWorld().equals(targetLocation.getWorld())) continue;
if (location.distance(targetLocation) > 25D) continue;
if (war.isPlayerInWar(targetPlayer)) continue;
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
side.addPlayer(targetPlayer);
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>You entered the war of <war>!")
.parseMinimessagePlaceholder("war", war.getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
targetPlayer.showTitle(warTitle);
targetPlayer.playSound(warSound);
}
}
protected static void warSurrender(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Player not found.").build());
// Towny Resident Object
@Nullable Resident res = TownyAPI.getInstance().getResident(argPlayer);
if (res == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
// Town check
@Nullable Town town = res.getTownOrNull();
if (town == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in a town.").build());
@Nullable Side side = war.getTownSide(town);
if (side == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in that war.").build());
final @Nullable Nation resNation = res.getNationOrNull();
final @Nullable Town resTown = res.getTownOrNull();
if (resNation != null && (p.hasPermission("AlathranWars.nationsurrender") || res.isKing() || asAdmin)) {
// Has nation surrender permission
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
war.surrenderNation(resNation);
} else if (resTown == null) {
// Cannot surrender nation involvement
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender for your nation.").build());
}
if (resTown != null && (p.hasPermission("AlathranWars.townsurrender") || res.isMayor() || asAdmin)) {
// Is in indepdenent town & has surrender perms
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
war.cancelSieges(resTown);
war.surrenderTown(resTown);
} else {
// No perms
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender war for your town.").build());
}
}
protected static void warKick(@NotNull Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
if (!(args.getOptional("player").orElse(p) instanceof Player argPlayer))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Player not found.").build());
if (!war.isPlayerInWar(argPlayer))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>The player is not in that war.").build());
@Nullable Side side = war.getPlayerSide(argPlayer);
if (side == null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>The player is not in that war.").build());
p.sendMessage(ColorParser.of("Target yeeted.").build());
side.removePlayer(argPlayer);
NameColorHandler.getInstance().calculatePlayerColors(argPlayer);
}
private static void warList(@NotNull Player p, CommandArguments args) throws WrapperCommandSyntaxException {
Set<War> wars = WarController.getInstance().getWars();
if (wars.isEmpty()) {
p.sendMessage(ColorParser.of("<red>There are no wars at the moment, the world is at peace.").build());
return;
}
final StringBuilder msg = new StringBuilder();
for (War war : wars) {
msg.append("\n<white><bold>%s<reset>".formatted(war.getLabel()));
msg.append("\n <grey>Sides: <white>%s <grey>vs <white>%s".formatted(war.getSide1().getName(), war.getSide2().getName()));
msg.append("\n <grey>Score: <white>%s <grey>vs <white>%s".formatted(war.getSide1().getScore(), war.getSide2().getScore()));
msg.append("\n");
}
p.sendMessage(
ColorParser.of(
msg.toString()
).build()
);
}
private static void warInfo(Player p, CommandArguments args) throws WrapperCommandSyntaxException {
War war = (War) args.get("war");
if (war == null) return;
final StringBuilder msg = new StringBuilder();
for (Side side : war.getSides()) {
msg.append("\n<white><bold>%s<reset>".formatted(side.getName()));
msg.append("\n <grey>Score: <green>%s".formatted(side.getScore()));
msg.append("\n <grey>Nations: <green>%s<grey>/<red>%s".formatted(side.getNations().size(), side.getNations().size() + side.getSurrenderedNations().size()));
msg.append("\n <grey>Towns: <green>%s<grey>/<red>%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getSurrenderedTowns().size()));
msg.append("\n <grey>Players: <green>%s<grey>/<red>%s".formatted(side.getPlayersIncludingOffline().size(), side.getPlayersIncludingOffline().size() + side.getSurrenderedPlayersIncludingOffline().size()));
msg.append("\n");
}
p.sendMessage(
ColorParser.of(
msg.toString()
).build()
);
}
}
@@ -0,0 +1,47 @@
package com.github.alathra.alathranwars.config;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.Reloadable;
import com.github.milkdrinkers.Crate.Config;
import javax.inject.Singleton;
/**
* A class that generates/loads & provides access to a configuration file.
*/
@Singleton
public class ConfigHandler implements Reloadable {
private final AlathranWars alathranWars;
private Config cfg;
/**
* Instantiates a new Config handler.
*
* @param alathranWars the plugin instance
*/
public ConfigHandler(AlathranWars alathranWars) {
this.alathranWars = alathranWars;
}
@Override
public void onLoad() {
cfg = new Config("config", alathranWars.getDataFolder().getPath(), alathranWars.getResource("config.yml")); // Create a config file from the template in our resources folder
}
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
/**
* Gets alathranWars config object.
*
* @return the alathranWars config object
*/
public Config getConfig() {
return cfg;
}
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.conflict;
import com.github.alathra.alathranwars.enums.ConflictType;
public class Conflict {
private ConflictType conflictType;
}
@@ -0,0 +1,62 @@
package com.github.alathra.alathranwars.conflict;
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import org.jetbrains.annotations.Nullable;
public class Occupation {
public static boolean isOccupied(Town town) {
return town.isConquered();
}
public static void removeOccupied(Town town) {
if (!isOccupied(town)) return;
// final boolean hasPreviousNation = town.hasNation();
// final Nation previousNation = town.getNationOrNull();
// if (hasPreviousNation) {
// town.removeNation();
// }
town.setConquered(false);
town.save();
// if (hasPreviousNation) {
// previousNation.save();
// }
}
public static void setOccupied(Nation occupied, @Nullable Nation occupier) {
for (Town town : occupied.getTowns())
setOccupied(town, occupier);
}
public static void setOccupied(Town town, @Nullable Nation occupier) {
if (isOccupied(town)) return;
// Remove from current nation
final boolean hasPreviousNation = town.hasNation();
final boolean hasNewNation = occupier != null;
final Nation previousNation = town.getNationOrNull();
if (hasPreviousNation && hasNewNation && previousNation != occupier)
town.removeNation();
// Put town into occupiers nation
try {
if (hasNewNation)
town.setNation(occupier);
} catch (AlreadyRegisteredException e) {
e.printStackTrace();
return;
}
town.setConquered(true);
town.save();
if (hasNewNation)
occupier.save();
if (hasPreviousNation && previousNation != occupier)
previousNation.save();
}
}
@@ -0,0 +1,54 @@
package com.github.alathra.alathranwars.conflict.battle;
import com.github.alathra.alathranwars.enums.battle.BattleType;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
public interface Battle {
void start(); // Initiates battle
void stop(); // Ends battle
void resume(); // Resume battle after server restart or plugin reload
void attackersWin(BattleVictoryReason reason); // A Attacker victory
void defendersWin(BattleVictoryReason reason); // A Defender victory
void equalWin(BattleVictoryReason reason); // A Draw
UUID uuid = null; // Battle UUID
default @NotNull UUID getUUID() {
return uuid;
}
/**
* Equals boolean.
*
* @param uuid the uuid
* @return the boolean
*/
default boolean equals(UUID uuid) {
return getUUID().equals(uuid);
}
/**
* Equals boolean.
*
* @param battle the battle
* @return the boolean
*/
default boolean equals(@NotNull Battle battle) {
return getUUID().equals(battle.getUUID());
}
BattleType battleType = null;
default BattleType getBattleType() {
return battleType;
}
}
@@ -0,0 +1,94 @@
/*
MIT License
Copyright (c) 2021 SkytAsul
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.alathra.alathranwars.conflict.battle.beam;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.UUID;
public class CrystalLaser extends Laser {
private final Object crystal;
private final int crystalID = Packets.generateEID();
private Object createCrystalPacket;
private Object metadataPacketCrystal;
private final Object[] destroyPackets;
private final Object fakeCrystalDataWatcher;
/**
* Creates a new Ender Crystal Laser instance
*
* @param start Location where laser will starts. The Crystal laser do not handle decimal number, it will be rounded to blocks.
* @param end Location where laser will ends. The Crystal laser do not handle decimal number, it will be rounded to blocks.
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible (<i>-1 if infinite</i>)
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see #start(Plugin) to start the laser
* @see #durationInTicks() to make the duration in ticks
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
*/
public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration, distance);
fakeCrystalDataWatcher = Packets.createFakeDataWatcher();
Packets.setCrystalWatcher(fakeCrystalDataWatcher, end);
if (Packets.version < 17) {
crystal = null;
} else {
crystal = Packets.createCrystal(start, UUID.randomUUID(), crystalID);
}
metadataPacketCrystal = Packets.createPacketMetadata(crystalID, fakeCrystalDataWatcher);
destroyPackets = Packets.createPacketsRemoveEntities(crystalID);
}
private Object getCrystalSpawnPacket() throws ReflectiveOperationException {
if (createCrystalPacket == null) {
if (Packets.version < 17) {
createCrystalPacket = Packets.createPacketEntitySpawnNormal(start, Packets.crystalID, Packets.crystalType, crystalID);
} else {
createCrystalPacket = Packets.createPacketEntitySpawnNormal(crystal);
}
}
return createCrystalPacket;
}
@Override
public LaserType getLaserType() {
return LaserType.ENDER_CRYSTAL;
}
@Override
protected void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException {
Packets.sendPackets(p, getCrystalSpawnPacket());
Packets.sendPackets(p, metadataPacketCrystal);
}
@Override
protected void sendDestroyPackets(Player p) throws ReflectiveOperationException {
Packets.sendPackets(p, destroyPackets);
}
}
@@ -0,0 +1,213 @@
/*
MIT License
Copyright (c) 2021 SkytAsul
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.alathra.alathranwars.conflict.battle.beam;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.utility.Logger;
import com.github.milkdrinkers.colorparser.ColorParser;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* A whole class to create Guardian Lasers and Ender Crystal Beams using packets and reflection.<br>
* Inspired by the API
* <a href="https://www.spigotmc.org/resources/guardianbeamapi.18329">GuardianBeamAPI</a><br>
* <b>1.9 -> 1.20</b>
*
* @author SkytAsul
* @version 2.3.3
* @see <a href="https://github.com/SkytAsul/GuardianBeam">GitHub repository</a>
*/
public abstract class Laser {
protected final int distanceSquared;
protected final int duration;
protected boolean durationInTicks = false;
protected Location start;
protected Location end;
protected Plugin plugin;
protected ScheduledTask task;
protected Set<Player> show = ConcurrentHashMap.newKeySet();
private final Set<Player> seen = new HashSet<>();
private final List<Runnable> executeEnd = new ArrayList<>(1);
protected Laser(Location start, Location end, int duration, int distance) {
if (!Packets.enabled)
throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization.");
if (start.getWorld() != end.getWorld())
throw new IllegalArgumentException("Locations do not belong to the same worlds.");
this.start = start.clone();
this.end = end.clone();
this.duration = duration;
distanceSquared = distance < 0 ? -1 : distance * distance;
}
/**
* Adds a runnable to execute when the laser reaches its final duration
*
* @param runnable action to execute
* @return this {@link Laser} instance
*/
public Laser executeEnd(Runnable runnable) {
executeEnd.add(runnable);
return this;
}
/**
* Makes the duration provided in the constructor passed as ticks and not seconds
*
* @return this {@link Laser} instance
*/
public Laser durationInTicks() {
durationInTicks = true;
return this;
}
/**
* Starts this laser.
* <p>
* It will make the laser visible for nearby players and start the countdown to the final duration.
* <p>
* Once finished, it will destroy the laser and execute all runnables passed with {@link Laser#executeEnd}.
*
* @param plugin plugin used to start the task
*/
public void start(Plugin plugin) {
if (task != null) throw new IllegalStateException("Task already started");
this.plugin = plugin;
Runnable runnable = new BukkitRunnable() {
int time = 0;
@Override
public void run() {
try {
if (time == duration) {
stop();
return;
}
if (!durationInTicks || time % 20 == 0) {
for (Player p : start.getWorld().getPlayers()) {
if (isCloseEnough(p)) {
if (show.add(p)) {
sendStartPackets(p, !seen.add(p));
}
} else if (show.remove(p)) {
sendDestroyPackets(p);
}
}
}
time++;
} catch (ReflectiveOperationException e) {
Logger.get().error(ColorParser.of("<red>Laser packer exception: ").build(), e);
}
}
};
task = AlathranWars.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
}
/**
* Stops this laser.
* <p>
* This will destroy the laser for every player and start execute all runnables passed with {@link Laser#executeEnd}
*/
public synchronized void stop() {
if (task == null || task.isCancelled()) throw new IllegalStateException("Task not started");
task.cancel();
try {
try {
for (Player p : show) {
sendDestroyPackets(p);
}
show.clear();
executeEnd.forEach(Runnable::run);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
} catch (IllegalStateException ignored) {
}
}
/**
* Gets laser status.
*
* @return <code>true</code> if the laser is currently running
* (i.e. {@link #start} has been called and the duration is not over)
*/
public boolean isStarted() {
return task != null;
}
/**
* Gets laser type.
*
* @return LaserType enum constant of this laser
*/
public abstract LaserType getLaserType();
/**
* Gets the start location of the laser.
*
* @return where exactly is the start position of the laser located
*/
public Location getStart() {
return start.clone();
}
/**
* Gets the end location of the laser.
*
* @return where exactly is the end position of the laser located
*/
public Location getEnd() {
return end.clone();
}
protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException;
protected abstract void sendDestroyPackets(Player p) throws ReflectiveOperationException;
protected boolean isCloseEnough(Player player) {
if (distanceSquared == -1) return true;
Location location = player.getLocation();
return getStart().distanceSquared(location) <= distanceSquared ||
getEnd().distanceSquared(location) <= distanceSquared;
}
}
@@ -0,0 +1,56 @@
/*
MIT License
Copyright (c) 2021 SkytAsul
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.alathra.alathranwars.conflict.battle.beam;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
public enum LaserType {
/**
* Represents a laser from an Ender Crystal entity.
* <p>
* Start and end locations are automatically rounded to integers (block locations).
*/
ENDER_CRYSTAL;
/**
* Creates a new Laser instance, {@link CrystalLaser} depending on this enum value.
*
* @param start Location where laser will starts
* @param end Location where laser will ends
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see Laser#start(Plugin) to start the laser
* @see Laser#durationInTicks() to make the duration in ticks
* @see Laser#executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
*/
public Laser create(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
if (this == LaserType.ENDER_CRYSTAL) {
return new CrystalLaser(start, end, duration, distance);
}
throw new IllegalStateException();
}
}
@@ -0,0 +1,396 @@
/*
MIT License
Copyright (c) 2021 SkytAsul
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.alathra.alathranwars.conflict.battle.beam;
import com.github.alathra.alathranwars.utility.Logger;
import com.github.milkdrinkers.colorparser.ColorParser;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.animal.Squid;
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
class Packets {
public static boolean enabled = false;
static int version;
private static int versionMinor;
private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
private static final String cpack = Bukkit.getServer().getClass().getPackage().getName() + ".";
static final int crystalID = 51; // pre-1.13
static Object crystalType;
private static Constructor<?> crystalConstructor;
private static Object watcherObject4; // crystal target
private static Object watcherObject5; // crystal base plate
private static Constructor<?> watcherConstructor;
private static Method watcherSet;
private static Method watcherRegister;
private static Method watcherDirty;
private static Method watcherPack;
private static Constructor<?> blockPositionConstructor;
private static Constructor<?> packetSpawnNormal;
private static Constructor<?> packetRemove;
private static Constructor<?> packetMetadata;
private static Method getHandle;
private static Field playerConnection;
private static Method sendPacket;
private static Method setUUID;
private static Method setID;
private static Object fakeSquid;
private static Object nmsWorld;
static {
try {
// e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1
String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_");
version = Integer.parseInt(versions[1]); // 1.X
if (version >= 17) {
// e.g. Bukkit.getBukkitVersion() -> 1.17.1-R0.1-SNAPSHOT
versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\.");
versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
} else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
ProtocolMappings mappings = ProtocolMappings.getMappings(version);
if (mappings == null) {
mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1];
}
Class<?> entityTypesClass = getNMSClass("world.entity", "EntityTypes");
Class<Entity> entityClass = Entity.class;
Class<EndCrystal> crystalClass = EndCrystal.class;
Class<?> squidClass = Squid.class;
// invisilibity
Object watcherObject1 = getField(entityClass, mappings.getWatcherFlags(), null);
watcherObject4 = getField(crystalClass, mappings.getWatcherTargetLocation(), null);
watcherObject5 = getField(crystalClass, mappings.getWatcherBasePlate(), null);
if (version >= 13) {
crystalType = entityTypesClass.getDeclaredField(mappings.getCrystalTypeName()).get(null);
}
Class<?> dataWatcherClass = getNMSClass("network.syncher", "DataWatcher");
watcherConstructor = dataWatcherClass.getDeclaredConstructor(entityClass);
if (version >= 18) {
watcherSet = dataWatcherClass.getDeclaredMethod("b", watcherObject1.getClass(), Object.class);
watcherRegister = dataWatcherClass.getDeclaredMethod("a", watcherObject1.getClass(), Object.class);
} else {
watcherSet = getMethod(dataWatcherClass, "set");
watcherRegister = getMethod(dataWatcherClass, "register");
}
if (version >= 15) watcherDirty = getMethod(dataWatcherClass, "markDirty");
if (version > 19 || (version == 19 && versionMinor >= 3))
watcherPack = dataWatcherClass.getDeclaredMethod("b");
packetSpawnNormal = getNMSClass("network.protocol.game", "PacketPlayOutSpawnEntity").getDeclaredConstructor(version < 17 ? new Class<?>[0] : new Class<?>[]{getNMSClass("world.entity", "Entity")});
packetRemove = getNMSClass("network.protocol.game", "PacketPlayOutEntityDestroy").getDeclaredConstructor(version == 17 && versionMinor == 0 ? int.class : int[].class);
packetMetadata = getNMSClass("network.protocol.game", "PacketPlayOutEntityMetadata")
.getDeclaredConstructor(version < 19 || (version == 19 && versionMinor < 3)
? new Class<?>[]{int.class, dataWatcherClass, boolean.class}
: new Class<?>[]{int.class, List.class});
blockPositionConstructor =
getNMSClass("core", "BlockPosition").getConstructor(int.class, int.class, int.class);
nmsWorld = Class.forName(cpack + "CraftWorld").getDeclaredMethod("getHandle").invoke(Bukkit.getWorlds().get(0));
Constructor<?> squidConstructor = squidClass.getDeclaredConstructors()[0];
if (version >= 17) {
crystalConstructor = crystalClass.getDeclaredConstructor(nmsWorld.getClass().getSuperclass(), double.class, double.class, double.class);
}
Object[] entityConstructorParams = version < 14 ? new Object[]{nmsWorld} : new Object[]{entityTypesClass.getDeclaredField(mappings.getSquidTypeName()).get(null), nmsWorld};
fakeSquid = squidConstructor.newInstance(entityConstructorParams);
Object fakeSquidWatcher = createFakeDataWatcher();
tryWatcherSet(fakeSquidWatcher, watcherObject1, (byte) 32);
getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle");
playerConnection = getNMSClass("server.level", "EntityPlayer")
.getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c"));
playerConnection.setAccessible(true);
sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(
version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"),
getNMSClass("network.protocol", "Packet"));
if (version >= 17) {
setUUID = entityClass.getDeclaredMethod("a_", UUID.class);
setID = entityClass.getDeclaredMethod("e", int.class);
}
enabled = true;
} catch (Exception e) {
Logger.get().error(
ColorParser.of("Laser reflection failed to initialize. The utility is disabled. Please ensure your version (<version>) is supported.")
.parseMinimessagePlaceholder("version", Bukkit.getServer().getClass().getPackage().getName())
.build()
, e);
}
}
static int generateEID() {
return Entity.nextEntityId();
}
public static void sendPackets(Player p, Object... packets) throws ReflectiveOperationException {
Object connection = playerConnection.get(getHandle.invoke(p));
for (Object packet : packets) {
if (packet == null) continue;
sendPacket.invoke(connection, packet);
}
}
public static Object createFakeDataWatcher() throws ReflectiveOperationException {
Object watcher = watcherConstructor.newInstance(fakeSquid);
if (version > 13) setField(watcher, "registrationLocked", false);
return watcher;
}
public static Object createCrystal(Location location, UUID uuid, int id) throws ReflectiveOperationException {
Object entity = crystalConstructor.newInstance(nmsWorld, location.getX(), location.getY(), location.getZ());
setEntityIDs(entity, uuid, id);
return entity;
}
public static Object createPacketEntitySpawnNormal(Location location, int typeID, Object type, int id) throws ReflectiveOperationException {
Object packet = packetSpawnNormal.newInstance();
setField(packet, "a", id);
setField(packet, "b", UUID.randomUUID());
setField(packet, "c", location.getX());
setField(packet, "d", location.getY());
setField(packet, "e", location.getZ());
setField(packet, "i", (int) (location.getYaw() * 256.0F / 360.0F));
setField(packet, "j", (int) (location.getPitch() * 256.0F / 360.0F));
setField(packet, "k", version < 13 ? typeID : type);
return packet;
}
public static Object createPacketEntitySpawnNormal(Object entity) throws ReflectiveOperationException {
return packetSpawnNormal.newInstance(entity);
}
public static void setCrystalWatcher(Object watcher, Location target) throws ReflectiveOperationException {
Object blockPosition =
blockPositionConstructor.newInstance(target.getBlockX(), target.getBlockY(), target.getBlockZ());
tryWatcherSet(watcher, watcherObject4, Optional.of(blockPosition));
tryWatcherSet(watcher, watcherObject5, Boolean.FALSE);
}
public static Object[] createPacketsRemoveEntities(int... entitiesId) throws ReflectiveOperationException {
Object[] packets;
if (version == 17 && versionMinor == 0) {
packets = new Object[entitiesId.length];
for (int i = 0; i < entitiesId.length; i++) {
packets[i] = packetRemove.newInstance(entitiesId[i]);
}
} else {
packets = new Object[]{packetRemove.newInstance(entitiesId)};
}
return packets;
}
public static void setEntityIDs(Object entity, UUID uuid, int id) throws ReflectiveOperationException {
setUUID.invoke(entity, uuid);
setID.invoke(entity, id);
}
static Object createPacketMetadata(int entityId, Object watcher) throws ReflectiveOperationException {
if (version < 19 || (version == 19 && versionMinor < 3)) {
return packetMetadata.newInstance(entityId, watcher, false);
} else {
return packetMetadata.newInstance(entityId, watcherPack.invoke(watcher));
}
}
private static void tryWatcherSet(Object watcher, Object watcherObject, Object watcherData) throws ReflectiveOperationException {
try {
watcherSet.invoke(watcher, watcherObject, watcherData);
} catch (InvocationTargetException ex) {
watcherRegister.invoke(watcher, watcherObject, watcherData);
if (version >= 15) watcherDirty.invoke(watcher, watcherObject);
}
}
/* Reflection utils */
private static Method getMethod(Class<?> clazz, String name) throws NoSuchMethodException {
for (Method m : clazz.getDeclaredMethods()) {
if (m.getName().equals(name)) return m;
}
throw new NoSuchMethodException(name + " in " + clazz.getName());
}
private static void setField(Object instance, String name, Object value) throws ReflectiveOperationException {
Field field = instance.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(instance, value);
}
private static Object getField(Class<?> clazz, String name, Object instance) throws ReflectiveOperationException {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(instance);
}
private static Class<?> getNMSClass(String package17, String className) throws ClassNotFoundException {
return Class.forName((version < 17 ? npack : "net.minecraft." + package17) + "." + className);
}
private enum ProtocolMappings {
V1_9(9, "Z", "bA", "bB", "b", "c", 94, 68),
V1_10(10, V1_9),
V1_11(11, V1_10),
V1_12(12, V1_11),
V1_13(13, "ac", "bF", "bG", "b", "c", 70, 28),
V1_14(14, "W", "b", "bD", "c", "d", 73, 30),
V1_15(15, "T", "b", "bA", "c", "d", 74, 31),
V1_16(16, null, "b", "d", "c", "d", -1, 31) {
@Override
public String getWatcherFlags() {
return Packets.versionMinor < 2 ? "T" : "S";
}
},
V1_17(17, "Z", "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "setCollisionRule", "getPlayerNameSet"),
V1_18(18, null, "b", "e", "c", "d", 86, 35, "K", "aJ", "u", "a", "g") {
@Override
public String getWatcherFlags() {
return Packets.versionMinor < 2 ? "aa" : "Z";
}
},
V1_19(19, null, "b", "e", "c", "d", 89, 38, null, null, "w", "a", "g") {
@Override
public String getWatcherFlags() {
return versionMinor < 4 ? "Z" : "an";
}
@Override
public String getSquidTypeName() {
if (versionMinor < 3)
return "aM";
else if (versionMinor == 3)
return "aN";
else
return "aT";
}
},
V1_20(20, null, "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g") {
@Override
public String getWatcherFlags() {
return versionMinor < 2 ? "an" : "ao";
}
},
;
private final int major;
private final String watcherFlags;
private final String watcherSpikes;
private final String watcherTargetEntity;
private final String watcherTargetLocation;
private final String watcherBasePlate;
private final int squidID;
private final int guardianID;
private final String guardianTypeName;
private final String squidTypeName;
private final String crystalTypeName;
private final String teamSetCollision;
private final String teamGetPlayers;
ProtocolMappings(int major, ProtocolMappings parent) {
this(major, parent.watcherFlags, parent.watcherSpikes, parent.watcherTargetEntity, parent.watcherTargetLocation, parent.watcherBasePlate, parent.squidID, parent.guardianID, parent.guardianTypeName, parent.squidTypeName, parent.crystalTypeName, parent.teamSetCollision, parent.teamGetPlayers);
}
ProtocolMappings(int major,
String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate,
int squidID, int guardianID) {
this(major, watcherFlags, watcherSpikes, watcherTargetEntity, watcherTargetLocation, watcherBasePlate, squidID, guardianID, null, "SQUID", "END_CRYSTAL", null, null);
}
ProtocolMappings(int major,
String watcherFlags, String watcherSpikes, String watcherTargetEntity, String watcherTargetLocation, String watcherBasePlate,
int squidID, int guardianID,
String guardianTypeName, String squidTypeName, String crystalTypeName, String teamSetCollision, String teamGetPlayers) {
this.major = major;
this.watcherFlags = watcherFlags;
this.watcherSpikes = watcherSpikes;
this.watcherTargetEntity = watcherTargetEntity;
this.watcherTargetLocation = watcherTargetLocation;
this.watcherBasePlate = watcherBasePlate;
this.squidID = squidID;
this.guardianID = guardianID;
this.guardianTypeName = guardianTypeName;
this.squidTypeName = squidTypeName;
this.crystalTypeName = crystalTypeName;
this.teamSetCollision = teamSetCollision;
this.teamGetPlayers = teamGetPlayers;
}
public static ProtocolMappings getMappings(int major) {
for (ProtocolMappings map : values()) {
if (major == map.getMajor()) return map;
}
return null;
}
public int getMajor() {
return major;
}
public String getWatcherFlags() {
return watcherFlags;
}
public String getWatcherTargetLocation() {
return watcherTargetLocation;
}
public String getWatcherBasePlate() {
return watcherBasePlate;
}
public String getSquidTypeName() {
return squidTypeName;
}
public String getCrystalTypeName() {
return crystalTypeName;
}
}
}
@@ -0,0 +1,636 @@
package com.github.alathra.alathranwars.conflict.battle.raid;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
import com.github.alathra.alathranwars.enums.battle.*;
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownBlock;
import net.kyori.adventure.bossbar.BossBar;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.title.Title;
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.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Raid implements Battle {
public static final Duration RAID_DURATION = Duration.ofMinutes(60);
public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points 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.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting
public static final int BATTLEFIELD_RANGE = 500;
public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
public static final double SIEGE_VICTORY_MONEY = 2500.0;
private final @NotNull 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 @NotNull War war; // War which raid belongs to
private Instant endTime;
private int raidProgress = 0;
private Instant lastTouched;
private RaidRunnable raidRunnable;
private Town town; // Town of the raid
private boolean side1AreAttackers; // bool of if side1 being attacker
private OfflinePlayer raidLeader;
private @Nullable TownBlock homeBlock = null;
private @Nullable Location townSpawn = null;
private @Nullable BossBar activeBossBar = null;
private boolean stopped = false; // Used to track if the raid has been already deleted
public Raid(final @NotNull War war, final Town town, Player raidLeader) {
uuid = UUID.randomUUID();
endTime = Instant.now().plus(RAID_DURATION);
lastTouched = Instant.now();
this.war = war;
this.town = town;
this.raidLeader = raidLeader;
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();
}
// Construct when loading from DB
public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
this.war = war;
this.uuid = uuid;
this.town = town;
this.raidLeader = raidLeader;
this.endTime = endTime;
this.lastTouched = lastTouched;
this.raidProgress = raidProgress;
this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
calculateOnlinePlayers();
}
/**
* Starts a raid
*/
public void start() {
raidRunnable = new RaidRunnable(this);
if (!war.isEventWar())
AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY);
final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
final Title defTitle = Title.title(
ColorParser.of("<red><u><b><town>")
.parseMinimessagePlaceholder("town", town.getName())
.build(),
ColorParser.of("<gray><i>Is under raid, defend!")
.build(),
times
);
final Title attTitle = Title.title(
ColorParser.of("<red><u><b><town>")
.parseMinimessagePlaceholder("town", town.getName())
.build(),
ColorParser.of("<gray><i>Has been put to raid, attack!")
.build(),
times
);
final List<Sound> soundList = List.of(
Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
);
getDefenderPlayers().forEach(player -> {
player.showTitle(defTitle);
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
});
getAttackerPlayers().forEach(player -> {
player.showTitle(attTitle);
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
});
}
/**
* Resumes a raid (after a server restart e.t.c.)
*/
public void resume() {
raidRunnable = new RaidRunnable(this, getRaidProgress());
}
/**
* Stops a raid
*/
public void stop() {
if (stopped) return;
stopped = true;
raidRunnable.cancel();
// DatabaseQueries.deleteRaid(this); // TODO Delete raid
war.removeRaid(this);
}
public void attackersWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
if (!war.isEventWar()) {
AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY);
double amt;
if (town.getAccount().getHoldingBalance() > 10000.0) {
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
town.getAccount().withdraw(amt, "Raid Defeat");
} else {
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat");
amt = SIEGE_VICTORY_MONEY;
}
AlathranWars.econ.depositPlayer(raidLeader, amt);
}
if (side1AreAttackers) {
war.getSide1().addScore(50);
war.getSide2().addScore(5);
} else {
war.getSide1().addScore(5);
war.getSide2().addScore(50);
}
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
stop();
if (!war.isEventWar()) {
Side townSide = getWar().getTownSide(town);
Side attackerSide = getAttackerSide();
if (attackerSide.equals(townSide)) {
if (townSide.isTownSurrendered(town))
war.unsurrenderTown(town);
} else {
if (!townSide.isTownSurrendered(town))
war.surrenderTown(town);
}
}
}
public void defendersWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
if (!war.isEventWar())
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory");
if (side1AreAttackers) {
war.getSide2().addScore(10);
} else {
war.getSide1().addScore(10);
}
new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
stop();
}
/**
* No winner declared
*/
public void equalWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
stop();
}
@NotNull
public Instant getLastTouched() {
return lastTouched;
}
public void setLastTouched(Instant lastTouched) {
this.lastTouched = lastTouched;
}
public int getRaidProgress() {
return raidProgress;
}
public void setRaidProgress(int raidProgress) {
if (raidProgress < 0) {
raidProgress = 0;
} else if (raidProgress > MAX_RAID_PROGRESS) {
raidProgress = MAX_RAID_PROGRESS;
}
this.raidProgress = raidProgress;
}
public float getRaidProgressPercentage() {
return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS;
}
@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();
}
// SECTION Display Bar
public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
if (activeBossBar == null)
createNewDisplayBar();
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
p.hideBossBar(activeBossBar);
}
for (@Nullable Player p : this.getPlayersOnBattlefield()) {
if (p != null)
p.showBossBar(activeBossBar);
}
final String color = switch (progressDirection) {
case UP -> {
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
activeBossBar.color(BossBar.Color.RED);
yield "<red>";
} else {
activeBossBar.color(BossBar.Color.BLUE);
yield "<blue>";
}
}
case CONTESTED -> {
activeBossBar.color(BossBar.Color.YELLOW);
yield "<yellow>";
}
case UNCONTESTED -> {
activeBossBar.color(BossBar.Color.WHITE);
yield "<white>";
}
case DOWN -> {
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
activeBossBar.color(BossBar.Color.BLUE);
yield "<blue>";
} else {
activeBossBar.color(BossBar.Color.RED);
yield "<red>";
}
}
};
if (Instant.now().isBefore(getEndTime())) {
activeBossBar.name(
ColorParser.of("<gray>Capture Progress: %s<progress> <gray>Time: %s<time>min".formatted(color, color))
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 100))
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutes()))
.build()
);
} else {
activeBossBar.name(
ColorParser.of("%sOVERTIME".formatted(color)).build()
);
}
activeBossBar.progress(getRaidProgressPercentage());
}
public void createNewDisplayBar() {
final @NotNull Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 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 (@NotNull Player p : Bukkit.getOnlinePlayers()) {
p.hideBossBar(activeBossBar);
}
activeBossBar = null;
}
}
// SECTION UUID
public @NotNull 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 raid the raid
* @return the boolean
*/
public boolean equals(@NotNull Raid raid) {
return getUUID().equals(raid.getUUID());
}
// SECTION 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 side1AreAttackers;
}
public void setSide1AreAttackers(final boolean side1AreAttackers) {
this.side1AreAttackers = side1AreAttackers;
}
@NotNull
public Set<Player> getPlayersOnBattlefield() {
return Stream.concat(attackers.stream(), defenders.stream()).collect(Collectors.toSet());
}
@NotNull
public Set<Player> getAttackers() {
return attackers;
}
@NotNull
public Set<Player> getDefenders() {
return defenders;
}
@NotNull
public Set<Player> getAttackerPlayers() {
return attackerPlayers;
}
@NotNull
public Set<Player> getDefenderPlayers() {
return defenderPlayers;
}
@NotNull
public OfflinePlayer getRaidLeader() {
return raidLeader;
}
public void setRaidLeader(OfflinePlayer raidLeader) {
this.raidLeader = raidLeader;
}
@NotNull
public String getName() { // TODO Make better raidnames
return getTown().getName();
}
// SECTION Time management
@NotNull
public Instant getEndTime() {
return endTime;
}
public void setEndTime(Instant time) {
endTime = time;
}
// SECTION Player management
public boolean isPlayerInRaid(UUID uuid) {
return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
}
public boolean isPlayerInRaid(@NotNull Player p) {
return isPlayerInRaid(p.getUniqueId());
}
public @NotNull BattleSide getPlayerSideInRaid(UUID uuid) {
if (attackerPlayersIncludingOffline.contains(uuid))
return BattleSide.ATTACKER;
if (defenderPlayersIncludingOffline.contains(uuid))
return BattleSide.DEFENDER;
return BattleSide.SPECTATOR;
}
public @NotNull BattleSide getPlayerSideInRaid(@NotNull Player p) {
return getPlayerSideInRaid(p.getUniqueId());
}
public void addPlayer(@NotNull Player p, @NotNull BattleSide side) {
addPlayer(p.getUniqueId(), side);
}
public void addPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull BattleSide side) {
if (offlinePlayer.hasPlayedBefore())
addPlayer(offlinePlayer.getUniqueId(), side);
}
public void addPlayer(@NotNull UUID uuid, @NotNull BattleSide side) {
if (isPlayerInRaid(uuid)) return;
switch (side) {
case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable Player p = Bukkit.getPlayer(uuid);
addOnlinePlayer(p, side);
}
}
public void addOnlinePlayer(Player p, @NotNull BattleSide side) {
switch (side) {
case ATTACKER -> attackerPlayers.add(p);
case DEFENDER -> defenderPlayers.add(p);
}
}
public void removePlayer(@NotNull Player p) {
removePlayer(p.getUniqueId());
}
public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
if (offlinePlayer.hasPlayedBefore())
removePlayer(offlinePlayer.getUniqueId());
}
public void removePlayer(@NotNull UUID uuid) {
if (!isPlayerInRaid(uuid)) return;
final @NotNull BattleSide side = getPlayerSideInRaid(uuid);
switch (side) {
case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable Player p = Bukkit.getPlayer(uuid);
removeOnlinePlayer(p, side);
}
}
public void removeOnlinePlayer(Player p, @NotNull BattleSide side) {
switch (side) {
case ATTACKER -> attackerPlayers.remove(p);
case DEFENDER -> defenderPlayers.remove(p);
}
}
public Set<UUID> getAttackerPlayersIncludingOffline() {
return attackerPlayersIncludingOffline;
}
public Set<UUID> getDefenderPlayersIncludingOffline() {
return defenderPlayersIncludingOffline;
}
public void calculateOnlinePlayers() {
final @NotNull Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
.map(Bukkit::getPlayer)
.collect(Collectors.toSet());
attackerPlayers.clear();
attackerPlayers.addAll(onlineAttackers);
final @NotNull 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(@NotNull Location location) {
final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
.filter(OfflinePlayer::isOnline)
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
.collect(Collectors.toSet());
attackers.clear();
attackers.addAll(attackersOnBattlefield);
final @NotNull Set<Player> defendersOnBattlefield = defenderPlayers.stream()
.filter(OfflinePlayer::isOnline)
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
.collect(Collectors.toSet());
defenders.clear();
defenders.addAll(defendersOnBattlefield);
// Emit events for players leaving & entering the battlefield
for (Player p : previousAttackersOnBattlefield) {
if (p.isConnected() && !attackers.contains(p)) {
// TODO Player left battlefield
}
}
for (Player p : attackers) {
if (p.isConnected() && !previousAttackersOnBattlefield.contains(p)) {
// TODO Player entered battlefield
}
}
for (Player p : previousDefendersOnBattlefield) {
if (p.isConnected() && !defenders.contains(p)) {
// TODO Player left battlefield
}
}
for (Player p : defenders) {
if (p.isConnected() && !previousDefendersOnBattlefield.contains(p)) {
// TODO Player entered battlefield
}
}
}
}
@@ -0,0 +1,260 @@
package com.github.alathra.alathranwars.conflict.battle.raid;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
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 org.bukkit.Location;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.time.Instant;
import static com.github.alathra.alathranwars.conflict.battle.raid.Raid.*;
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
public class RaidRunnable implements Runnable {
// Settings
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
private final static int CAPTURE_RANGE = 10;
private final @NotNull Raid raid;
// Variables
private @NotNull CaptureProgressDirection oldProgressDirection = UNCONTESTED;
private Instant nextAnnouncement;
private final ScheduledTask task;
private @Nullable Laser beam;
/**
* Start a raid
*
* @param raid the raid
*/
public RaidRunnable(@NotNull Raid raid) {
this.raid = raid;
raid.setRaidProgress(0);
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
raid.updateDisplayBar(CONTESTED);
}
/**
* Resume a raid at tick
*
* @param raid the raid
* @param raidProgress the raid ticks
*/
public RaidRunnable(@NotNull Raid raid, int raidProgress) {
this.raid = raid;
raid.setRaidProgress(raidProgress);
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
raid.updateDisplayBar(CONTESTED);
}
public void cancel() {
stopBeam();
if (task.isCancelled()) return;
task.cancel();
raid.deleteDisplayBar();
}
@Override
public void run() {
final @NotNull Town town = raid.getTown();
final @Nullable TownBlock homeBlock = raid.getHomeBlock();
final @Nullable Location townSpawn = raid.getTownSpawn();
if (homeBlock != null && townSpawn != null) {
town.setHomeBlock(homeBlock);
town.setSpawn(townSpawn);
}
// Render beam
startBeam();
// Calculate battlefield players
raid.calculateBattlefieldPlayers(townSpawn.toCenterLocation());
// Progress the raid
final int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
final int defendersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.DEFENDER);
final @NotNull CaptureProgressDirection progressDirection = getRaidProgressDirection(attackersOnPoint, defendersOnPoint);
// Raid is past max time or attackers haven't touched in time, defenders won
if (
(!progressDirection.equals(CONTESTED) && !progressDirection.equals(UP)) &&
(Instant.now().isAfter(raid.getEndTime()) ||
Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
) {
cancel();
raid.defendersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
// Attackers captured the town
if (raid.getRaidProgress() >= MAX_RAID_PROGRESS) {
cancel();
raid.attackersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
switch (progressDirection) {
case UP -> {
final int playerOnPointDiff = attackersOnPoint - defendersOnPoint;
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
if (playerOnPointDiff < 5) {
raid.setRaidProgress(raid.getRaidProgress() + (4 + playerOnPointDiff));
} else {
raid.setRaidProgress(raid.getRaidProgress() + 10);
}
}
case DOWN -> raid.setRaidProgress(raid.getRaidProgress() - 10);
}
if (oldProgressDirection != progressDirection) {
switch (progressDirection) {
case UP -> {
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The Attackers are capturing the home block.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case CONTESTED -> {
if (oldProgressDirection.equals(UNCONTESTED))
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The home block is being contested.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case UNCONTESTED -> {
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED) || oldProgressDirection.equals(DOWN))
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The home block is no longer being contested.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case DOWN -> {
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED))
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The Defenders re-secured the home block.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
}
}
if (Instant.now().isAfter(nextAnnouncement)) {
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>Raid time remaining: <time> minutes.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), raid.getEndTime()).toMinutesPart()))
.build()
));
}
raid.updateDisplayBar(progressDirection);
oldProgressDirection = progressDirection;
}
public int getPeopleOnPoint(@NotNull Location townSpawn, @NotNull BattleSide battleSide) {
int onPoint = 0;
for (final @NotNull Player p : (battleSide.equals(BattleSide.ATTACKER) ? raid.getAttackers() : raid.getDefenders())) {
if (p.isDead())
continue;
if (!townSpawn.getWorld().equals(p.getLocation().getWorld()))
continue;
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
onPoint += 1;
}
}
return onPoint;
}
public @NotNull CaptureProgressDirection getRaidProgressDirection(int attackersOnPoint, int defendersOnPoint) {
final boolean attackersAreOnPoint = attackersOnPoint > 0;
final boolean defendersAreOnPoint = defendersOnPoint > 0;
if (attackersAreOnPoint)
raid.setLastTouched(Instant.now());
if (attackersAreOnPoint && defendersAreOnPoint) {
if (attackersOnPoint > defendersOnPoint)
return UP;
return CONTESTED;
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
if (raid.getRaidProgress() == MAX_RAID_PROGRESS)
return CONTESTED;
return UP;
} else {
if (raid.getRaidProgress() == 0)
return UNCONTESTED;
// If the attackers haven't touched in a while, begin reverting progress
if (Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
return DOWN;
} else {
return UNCONTESTED;
}
}
}
private void startBeam() {
if (beam != null)
return;
try {
@Nullable Location loc1 = raid.getTownSpawn();
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
beam = new CrystalLaser(loc1, loc2, -1, 300);
beam.start(AlathranWars.getInstance());
} catch (ReflectiveOperationException ignored) {
}
}
private void stopBeam() {
if (beam != null) {
beam.stop();
beam = null;
}
}
}
@@ -0,0 +1,648 @@
package com.github.alathra.alathranwars.conflict.battle.siege;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.db.DatabaseQueries;
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
import com.github.alathra.alathranwars.enums.battle.*;
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
import com.github.alathra.alathranwars.events.battle.BattleStartEvent;
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
import com.github.alathra.alathranwars.events.battle.PreBattleStartEvent;
import com.github.milkdrinkers.colorparser.ColorParser;
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;
import java.util.stream.Stream;
/**
* The type Siege.
*/
public class Siege implements Battle {
public static final Duration SIEGE_DURATION = Duration.ofMinutes(60);
public static final int MAX_SIEGE_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
public static final int MAX_SIEGE_PROGRESS = 60 * 10 * MAX_SIEGE_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points 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.ofSeconds(60); // If point is not touched in this much time, siege progress begins reverting
public static final int BATTLEFIELD_RANGE = 500;
public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
public static final double SIEGE_VICTORY_MONEY = 2500.0;
private final @NotNull UUID uuid;
private final static BattleType battleType = BattleType.SIEGE;
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 @NotNull War war; // War which siege belongs to
private Instant endTime;
private int siegeProgress = 0;
private Instant lastTouched;
private SiegeRunnable siegeRunnable;
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;
private boolean stopped = false; // Used to track if the siege has been already deleted
/**
* Instantiates a new Siege. Used when creating a new siege.
*
* @param war the war
* @param town the town
* @param siegeLeader the siege leader
*/
public Siege(final @NotNull War war, final Town town, Player siegeLeader) {
uuid = UUID.randomUUID();
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();
}
/**
* Instantiates a new Siege. Used when loading existing Siege from Database.
*
* @param war the war
* @param uuid the uuid
* @param town the town
* @param siegeLeader the siege leader
* @param endTime the end time
* @param lastTouched the last touched
* @param siegeProgress the siege progress
* @param attackerPlayersIncludingOffline the attacker players including offline
* @param defenderPlayersIncludingOffline the defender players including offline
*/
public Siege(War war, @NotNull UUID uuid, Town town, OfflinePlayer siegeLeader, Instant endTime, Instant lastTouched, int siegeProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
this.war = war;
this.uuid = uuid;
this.town = town;
this.siegeLeader = siegeLeader;
this.endTime = endTime;
this.lastTouched = lastTouched;
this.siegeProgress = siegeProgress;
this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
calculateOnlinePlayers();
}
/**
* Starts the battle
*/
public void start() {
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
siegeRunnable = new SiegeRunnable(this);
stopped = false;
if (!war.isEventWar())
AlathranWars.econ.withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
new BattleStartEvent(war, this).callEvent();
}
/**
* Resumes the battle (after a server restart e.t.c.)
*/
public void resume() {
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
siegeRunnable = new SiegeRunnable(this, getSiegeProgress());
stopped = false;
new BattleStartEvent(war, this).callEvent();
}
/**
* Stops the battle
* </p>
* Internal stop method for battles which triggers cleanup methods
*/
public void stop() {
if (stopped) return;
stopped = true;
siegeRunnable.cancel();
DatabaseQueries.deleteSiege(this); // TODO Run as latent event?
war.removeSiege(this); // TODO Run as latent event?
}
/**
* Stop a battle in favor of the attackers
*
* @param reason what triggered the end
*/
public void attackersWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
if (!war.isEventWar()) {
AlathranWars.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
double amt;
if (town.getAccount().getHoldingBalance() > 10000.0) {
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
town.getAccount().withdraw(amt, "Siege Defeat");
} else {
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Siege Defeat");
amt = SIEGE_VICTORY_MONEY;
}
AlathranWars.econ.depositPlayer(siegeLeader, amt);
}
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
stop();
}
/**
* Stop a battle in favor of the defenders
*
* @param reason what triggered the end
*/
public void defendersWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
if (!war.isEventWar())
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
stop();
}
/**
* End a battle in favor of no one
*
* @param reason what triggered the end
*/
public void equalWin(BattleVictoryReason reason) {
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
stop();
}
@NotNull
public Instant getLastTouched() {
return lastTouched;
}
public void setLastTouched(Instant lastTouched) {
this.lastTouched = lastTouched;
}
public int getSiegeProgress() {
return siegeProgress;
}
public void setSiegeProgress(int siegeProgress) {
if (siegeProgress < 0) {
siegeProgress = 0;
} else if (siegeProgress > MAX_SIEGE_PROGRESS) {
siegeProgress = MAX_SIEGE_PROGRESS;
}
this.siegeProgress = siegeProgress;
}
public float getSiegeProgressPercentage() {
return (getSiegeProgress() * 1.0f) / MAX_SIEGE_PROGRESS;
}
@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 getSide1AreAttackers() ? war.getSide1() : war.getSide2();
}
/**
* Gets defender name string
*/
@NotNull
public Side getDefenderSide() {
return getSide1AreAttackers() ? war.getSide2() : war.getSide1();
}
// SECTION Display Bar
public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
if (activeBossBar == null)
createNewDisplayBar();
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
p.hideBossBar(activeBossBar);
}
for (@Nullable Player p : this.getPlayersOnBattlefield()) {
if (p != null)
p.showBossBar(activeBossBar);
}
final String color = switch (progressDirection) {
case UP -> {
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
activeBossBar.color(BossBar.Color.RED);
yield "<red>";
} else {
activeBossBar.color(BossBar.Color.BLUE);
yield "<blue>";
}
}
case CONTESTED -> {
activeBossBar.color(BossBar.Color.YELLOW);
yield "<yellow>";
}
case UNCONTESTED -> {
activeBossBar.color(BossBar.Color.WHITE);
yield "<white>";
}
case DOWN -> {
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
activeBossBar.color(BossBar.Color.BLUE);
yield "<blue>";
} else {
activeBossBar.color(BossBar.Color.RED);
yield "<red>";
}
}
};
if (Instant.now().isBefore(getEndTime())) {
activeBossBar.name(
ColorParser.of("<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(
ColorParser.of("%sOVERTIME".formatted(color)).build()
);
}
activeBossBar.progress(getSiegeProgressPercentage());
}
public void createNewDisplayBar() {
final @NotNull Component text = ColorParser.of("<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 (@NotNull Player p : Bukkit.getOnlinePlayers()) {
p.hideBossBar(activeBossBar);
}
activeBossBar = null;
}
}
// SECTION UUID
public @NotNull 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(@NotNull Siege siege) {
return getUUID().equals(siege.getUUID());
}
// SECTION BattleType
@Override
public BattleType getBattleType() {
return battleType;
}
// SECTION 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 side1AreAttackers;
}
public void setSide1AreAttackers(final boolean side1AreAttackers) {
this.side1AreAttackers = side1AreAttackers;
}
@NotNull
public Set<Player> getPlayersOnBattlefield() {
return Stream.concat(attackers.stream(), defenders.stream()).collect(Collectors.toSet());
}
@NotNull
public Set<Player> getAttackers() {
return attackers;
}
@NotNull
public Set<Player> getDefenders() {
return defenders;
}
@NotNull
public Set<Player> getAttackerPlayers() {
return attackerPlayers;
}
@NotNull
public Set<Player> getDefenderPlayers() {
return defenderPlayers;
}
@NotNull
public OfflinePlayer getSiegeLeader() {
return siegeLeader;
}
public void setSiegeLeader(OfflinePlayer siegeLeader) {
this.siegeLeader = siegeLeader;
}
@NotNull
public String getName() { // TODO Make better siegenames
return getTown().getName();
}
// SECTION Time management
@NotNull
public Instant getEndTime() {
return endTime;
}
public void setEndTime(Instant time) {
endTime = time;
}
// SECTION Player management
public boolean isPlayerInSiege(UUID uuid) {
return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
}
public boolean isPlayerInSiege(@NotNull Player p) {
return isPlayerInSiege(p.getUniqueId());
}
public @NotNull BattleSide getPlayerSideInSiege(UUID uuid) {
if (attackerPlayersIncludingOffline.contains(uuid))
return BattleSide.ATTACKER;
if (defenderPlayersIncludingOffline.contains(uuid))
return BattleSide.DEFENDER;
return BattleSide.SPECTATOR;
}
public @NotNull BattleSide getPlayerSideInSiege(@NotNull Player p) {
return getPlayerSideInSiege(p.getUniqueId());
}
public void addPlayer(@NotNull Player p, @NotNull BattleSide side) {
addPlayer(p.getUniqueId(), side);
}
public void addPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull BattleSide side) {
if (offlinePlayer.hasPlayedBefore())
addPlayer(offlinePlayer.getUniqueId(), side);
}
public void addPlayer(@NotNull UUID uuid, @NotNull BattleSide side) {
if (isPlayerInSiege(uuid)) return;
switch (side) {
case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable Player p = Bukkit.getPlayer(uuid);
addOnlinePlayer(p, side);
}
}
public void addOnlinePlayer(Player p, @NotNull BattleSide side) {
switch (side) {
case ATTACKER -> attackerPlayers.add(p);
case DEFENDER -> defenderPlayers.add(p);
}
}
public void removePlayer(@NotNull Player p) {
removePlayer(p.getUniqueId());
}
public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
if (offlinePlayer.hasPlayedBefore())
removePlayer(offlinePlayer.getUniqueId());
}
public void removePlayer(@NotNull UUID uuid) {
if (!isPlayerInSiege(uuid)) return;
final @NotNull BattleSide side = getPlayerSideInSiege(uuid);
switch (side) {
case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable Player p = Bukkit.getPlayer(uuid);
removeOnlinePlayer(p, side);
}
}
public void removeOnlinePlayer(Player p, @NotNull BattleSide side) {
switch (side) {
case ATTACKER -> attackerPlayers.remove(p);
case DEFENDER -> defenderPlayers.remove(p);
}
}
public Set<UUID> getAttackerPlayersIncludingOffline() {
return attackerPlayersIncludingOffline;
}
public Set<UUID> getDefenderPlayersIncludingOffline() {
return defenderPlayersIncludingOffline;
}
public void calculateOnlinePlayers() {
final @NotNull Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
.map(Bukkit::getPlayer)
.collect(Collectors.toSet());
attackerPlayers.clear();
attackerPlayers.addAll(onlineAttackers);
final @NotNull 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(@NotNull Location location) {
final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
.filter(OfflinePlayer::isOnline)
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
.collect(Collectors.toSet());
attackers.clear();
attackers.addAll(attackersOnBattlefield);
final @NotNull Set<Player> defendersOnBattlefield = defenderPlayers.stream()
.filter(OfflinePlayer::isOnline)
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
.collect(Collectors.toSet());
defenders.clear();
defenders.addAll(defendersOnBattlefield);
// TODO Emit events for players leaving & entering the battlefield
// Leaving attackers
previousAttackersOnBattlefield.stream()
.filter(p -> p.isConnected() && !attackers.contains(p))
.collect(Collectors.toSet())
.forEach(p -> {
// TODO Player left battlefield
}
);
// Entering attackers
attackers.stream()
.filter(p -> p.isConnected() && !previousAttackersOnBattlefield.contains(p))
.collect(Collectors.toSet())
.forEach(p -> {
// TODO Player entered battlefield
}
);
// Leaving defenders
previousDefendersOnBattlefield.stream()
.filter(p -> p.isConnected() && !defenders.contains(p))
.collect(Collectors.toSet())
.forEach(p -> {
// TODO Player left battlefield
}
);
// Entering defenders
defenders.stream()
.filter(p -> p.isConnected() && !previousDefendersOnBattlefield.contains(p))
.collect(Collectors.toSet())
.forEach(p -> {
// TODO Player entered battlefield
}
);
}
}
@@ -0,0 +1,263 @@
package com.github.alathra.alathranwars.conflict.battle.siege;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
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 org.bukkit.Location;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.time.Instant;
import static com.github.alathra.alathranwars.conflict.battle.siege.Siege.*;
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
public class SiegeRunnable implements Runnable {
// Settings
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
private final static int CAPTURE_RANGE = 10;
private final @NotNull Siege siege;
// Variables
private @NotNull CaptureProgressDirection oldProgressDirection = UNCONTESTED;
private Instant nextAnnouncement;
private final ScheduledTask task;
private @Nullable Laser beam;
/**
* Start a siege
*
* @param siege the siege
*/
public SiegeRunnable(@NotNull Siege siege) {
this.siege = siege;
siege.setSiegeProgress(0);
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
siege.updateDisplayBar(CONTESTED);
}
/**
* Resume a siege at tick
*
* @param siege the siege
* @param siegeProgress the siege ticks
*/
public SiegeRunnable(@NotNull 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);
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
siege.updateDisplayBar(CONTESTED);
}
public void cancel() {
stopBeam();
if (task.isCancelled()) return;
task.cancel();
siege.deleteDisplayBar();
}
@Override
public void run() {
final @NotNull Town town = siege.getTown();
final @Nullable TownBlock homeBlock = siege.getHomeBlock();
final @Nullable 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 int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
final int defendersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.DEFENDER);
final @NotNull CaptureProgressDirection progressDirection = getSiegeProgressDirection(attackersOnPoint, defendersOnPoint);
// Siege is past max time or attackers haven't touched in time, defenders won
if (
(!progressDirection.equals(CONTESTED) && !progressDirection.equals(UP)) &&
(Instant.now().isAfter(siege.getEndTime()) ||
Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
) {
cancel();
siege.defendersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
// Attackers captured the town
if (siege.getSiegeProgress() >= MAX_SIEGE_PROGRESS) {
cancel();
siege.attackersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
switch (progressDirection) {
case UP -> {
final int playerOnPointDiff = attackersOnPoint - defendersOnPoint;
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
if (playerOnPointDiff < 5) {
siege.setSiegeProgress(siege.getSiegeProgress() + (4 + playerOnPointDiff));
} else {
siege.setSiegeProgress(siege.getSiegeProgress() + 10);
}
}
case DOWN -> siege.setSiegeProgress(siege.getSiegeProgress() - 10);
}
if (oldProgressDirection != progressDirection) {
switch (progressDirection) {
case UP -> {
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The Attackers are capturing the home block.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case CONTESTED -> {
if (oldProgressDirection.equals(UNCONTESTED))
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The home block is being contested.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case UNCONTESTED -> {
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED) || oldProgressDirection.equals(DOWN))
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The home block is no longer being contested.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
case DOWN -> {
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED))
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<prefix>The Defenders re-secured the home block.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.build()
));
}
}
}
if (Instant.now().isAfter(nextAnnouncement)) {
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
siege.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
ColorParser.of("<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);
oldProgressDirection = progressDirection;
}
public int getPeopleOnPoint(@NotNull Location townSpawn, @NotNull BattleSide battleSide) {
int onPoint = 0;
for (final @NotNull Player p : (battleSide.equals(BattleSide.ATTACKER) ? siege.getAttackers() : siege.getDefenders())) {
if (p.isDead())
continue;
if (!townSpawn.getWorld().equals(p.getLocation().getWorld()))
continue;
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
onPoint += 1;
}
}
return onPoint;
}
public @NotNull CaptureProgressDirection getSiegeProgressDirection(int attackersOnPoint, int defendersOnPoint) {
final boolean attackersAreOnPoint = attackersOnPoint > 0;
final boolean defendersAreOnPoint = defendersOnPoint > 0;
if (attackersAreOnPoint)
siege.setLastTouched(Instant.now());
if (attackersAreOnPoint && defendersAreOnPoint) {
if (attackersOnPoint > defendersOnPoint)
return UP;
return CONTESTED;
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
if (siege.getSiegeProgress() == MAX_SIEGE_PROGRESS)
return CONTESTED;
return UP;
} else {
if (siege.getSiegeProgress() == 0)
return UNCONTESTED;
// If the attackers haven't touched in a while, begin reverting progress
if (Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
return DOWN;
} else {
return UNCONTESTED;
}
}
}
private void startBeam() {
if (beam != null)
return;
try {
try {
@Nullable Location loc1 = siege.getTownSpawn();
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
beam = new CrystalLaser(loc1, loc2, -1, 300);
beam.start(AlathranWars.getInstance());
} catch (ReflectiveOperationException ignored) {
}
} catch (NoClassDefFoundError ignored1) {
}
}
private void stopBeam() {
if (beam != null) {
beam.stop();
beam = null;
}
}
}
@@ -0,0 +1,868 @@
package com.github.alathra.alathranwars.conflict.war;
import com.github.alathra.alathranwars.conflict.Conflict;
import com.github.alathra.alathranwars.conflict.Occupation;
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
import com.github.alathra.alathranwars.db.DatabaseQueries;
import com.github.alathra.alathranwars.enums.ConflictType;
import com.github.alathra.alathranwars.enums.WarDeleteReason;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
import com.github.alathra.alathranwars.events.PreWarCreateEvent;
import com.github.alathra.alathranwars.events.PreWarDeleteEvent;
import com.github.alathra.alathranwars.events.WarCreateEvent;
import com.github.alathra.alathranwars.events.WarDeleteEvent;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.object.Government;
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 net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
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 boolean event;
private Side side1;
private 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<>();
/**
* Instantiates a existing War.
*
* @param uuid the uuid
* @param name the name
* @param label the label
* @param side1 the side 1
* @param side2 the side 2
* @param sieges the sieges
* @param raids the raids
* @param event the event
*/
@ApiStatus.Internal
public War(
UUID uuid,
String name,
String label,
Side side1,
Side side2,
Set<Siege> sieges,
Set<Raid> raids,
boolean event
) {
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;
this.event = event;
resume();
}
/**
* Instantiates a new War.
*
* @param uuid the uuid
* @param label the label
* @param aggressor the aggressor
* @param victim the victim
* @param event the event
* @throws SideCreationException the side creation exception
* @throws WrapperCommandSyntaxException the wrapper command syntax exception
*/
@ApiStatus.Internal
public War(
UUID uuid,
String label,
Government aggressor,
Government victim,
boolean event
) throws SideCreationException, WrapperCommandSyntaxException {
this.uuid = uuid;
this.label = label;
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
if (WarController.getInstance().getWar(this.name) != null)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
this.side1 = new SideBuilder()
.setWarUUID(this.uuid)
.setUuid(UUID.randomUUID())
.setLeader(aggressor)
.setSide(BattleSide.ATTACKER)
.setTeam(BattleTeam.SIDE_1)
.build();
this.side2 = new SideBuilder()
.setWarUUID(this.uuid)
.setUuid(UUID.randomUUID())
.setLeader(victim)
.setSide(BattleSide.DEFENDER)
.setTeam(BattleTeam.SIDE_2)
.build();
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
this.event = event;
if (!new PreWarCreateEvent(this).callEvent())
return;
// TODO All logic below this point should be separated out
WarController.getInstance().addWar(this);
start();
new WarCreateEvent(this).callEvent();
}
/**
* Gets uuid of the war.
*
* @return the uuid
*/
public UUID getUUID() {
return this.uuid;
}
/**
* Gets name of the war.
*
* @return the name
*/
@NotNull
public String getName() {
return name;
}
/**
* Gets label of the war.
*
* @return the label
*/
@NotNull
public String getLabel() {
return label;
}
/**
* Compare war UUID's.
*
* @param uuid the uuid
* @return the boolean
*/
public boolean equals(UUID uuid) {
return this.uuid.equals(uuid);
}
/**
* Compare war by UUID's.
*
* @param war the war
* @return the boolean
*/
public boolean equals(War war) {
return this.uuid.equals(war.getUUID());
}
/**
* Compare war by names.
*
* @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;
}
/**
* Gets sides in a list.
*
* @return the sides
*/
@NotNull
public Set<Side> getSides() {
return Set.of(
getSide1(),
getSide2()
);
}
/**
* Gets attacker side.
*
* @return the attacker
*/
@NotNull
public Side getAttacker() {
return attacker;
}
/**
* Gets defender side.
*
* @return the defender
*/
@NotNull
public Side getDefender() {
return defender;
}
/**
* Gets side by name.
*
* @param name the name
* @return the side
*/
@Nullable
public Side getSide(String name) {
if (getSide1().equals(name))
return getSide1();
if (getSide2().equals(name))
return getSide2();
return null;
}
/**
* Gets side by the side UUID.
*
* @param uuid the uuid
* @return the side
*/
@Nullable
public Side getSide(UUID uuid) {
if (getSide1().equals(uuid))
return getSide1();
if (getSide2().equals(uuid))
return getSide2();
return null;
}
/**
* Gets sieges in a list.
*
* @return the sieges
*/
@NotNull
public Set<Siege> getSieges() {
return sieges;
}
/**
* Sets sieges for the war.
*
* @param sieges the sieges
*/
@ApiStatus.Internal
public void setSieges(Set<Siege> sieges) {
this.sieges = sieges;
this.sieges.forEach(Siege::resume);
}
/**
* Gets siege by the siege UUID.
*
* @param uuid the uuid
* @return the siege
*/
@Nullable
public Siege getSiege(UUID uuid) {
return sieges.stream()
.filter(s -> s.equals(uuid))
.findAny()
.orElse(null);
}
/**
* Add siege to war.
*
* @param siege the siege
*/
@ApiStatus.Internal
public void addSiege(Siege siege) {
sieges.add(siege);
}
/**
* Remove siege from war.
*
* @param siege the siege
*/
@ApiStatus.Internal
public void removeSiege(Siege siege) {
sieges.remove(siege);
}
/**
* Gets raids.
*
* @return the raids
*/
@NotNull
public Set<Raid> getRaids() {
return raids;
}
/**
* Add raid to war.
*
* @param raid the raid
*/
@ApiStatus.Internal
public void addRaid(Raid raid) {
raids.add(raid);
}
/**
* Remove raid from war.
*
* @param raid the raid
*/
@ApiStatus.Internal
public void removeRaid(Raid raid) {
raids.remove(raid);
}
/**
* Is town under siege in this war.
*
* @param town the town
* @return the boolean
*/
public boolean isTownUnderSiege(Town town) {
return sieges.stream().anyMatch(siege -> siege.getTown().equals(town));
}
/**
* Is town under raid in this war.
*
* @param town the town
* @return the boolean
*/
public boolean isTownUnderRaid(Town town) {
return raids.stream().anyMatch(raid -> raid.getTown().equals(town));
}
/**
* Gets all online players in the war.
*
* @return the players
*/
@NotNull
public Set<Player> getPlayers() {
return Stream.concat(
getSide1().getPlayers().stream(),
getSide2().getPlayers().stream()
)
.collect(Collectors.toSet());
}
/**
* Gets all players, including offline ones in the war.
*
* @return the players including offline
*/
@NotNull
public Set<OfflinePlayer> getPlayersIncludingOffline() {
return Stream.concat(
getSide1().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
getSide2().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
)
.collect(Collectors.toSet());
}
/**
* Gets all surrendered players in the war.
*
* @return the surrendered players
*/
@NotNull
public Set<OfflinePlayer> getSurrenderedPlayers() {
return Stream.concat(
getSide1().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
getSide2().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
)
.collect(Collectors.toSet());
}
/**
* Check if player is in war.
*
* @param p the p
* @return the boolean
*/
public boolean isPlayerInWar(Player p) {
return side1.isPlayerOnSide(p) || side2.isPlayerOnSide(p);
}
/**
* Check if player is in war.
*
* @param uuid the uuid
* @return the boolean
*/
public boolean isPlayerInWar(UUID uuid) {
return side1.isPlayerOnSide(uuid) || side2.isPlayerOnSide(uuid);
}
/**
* Gets the side of the player or null if they are not in the war.
*
* @param p the p
* @return the player side
*/
@Nullable
public Side getPlayerSide(Player p) {
return getPlayerSide(p.getUniqueId());
}
/**
* Gets player side by player UUID or null if they are not in the war.
*
* @param uuid the uuid
* @return the player side
*/
@Nullable
public Side getPlayerSide(UUID uuid) {
if (side1.isPlayerOnSide(uuid))
return getSide1();
if (side2.isPlayerOnSide(uuid))
return getSide2();
return null;
}
/**
* Is town in war.
*
* @param town the town
* @return the boolean
*/
public boolean isTownInWar(Town town) {
return side1.isTownOnSide(town) || side2.isTownOnSide(town);
}
/**
* Gets town side or null if not in war.
*
* @param town the town
* @return the town side
*/
@Nullable
public Side getTownSide(Town town) {
if (side1.isTownOnSide(town))
return getSide1();
if (side2.isTownOnSide(town))
return getSide2();
return null;
}
/**
* Is nation in war boolean.
*
* @param nation the nation
* @return the boolean
*/
public boolean isNationInWar(Nation nation) {
return side1.isNationOnSide(nation) || side2.isNationOnSide(nation);
}
/**
* Gets nation side or null if not in war.
*
* @param nation the nation
* @return the nation side
*/
@Nullable
public Side getNationSide(Nation nation) {
if (side1.isNationOnSide(nation))
return getSide1();
if (side2.isNationOnSide(nation))
return getSide2();
return null;
}
/**
* Check if a side exists with the specified name.
*
* @param sideName the side name
* @return the boolean
*/
public boolean isSideValid(String sideName) {
return getSide1().equals(sideName) || getSide2().equals(sideName);
}
/**
* Cancel all active sieges in the war.
*/
@ApiStatus.Internal
public void cancelSieges() {
getTowns().forEach(this::cancelSieges);
}
/**
* Cancel all active sieges in the war. Ends the sieges in a draw.
*
* @param town the town
*/
@ApiStatus.Internal
public void cancelSieges(Town town) {
if (this != null) {
Side townSide = getTownSide(town);
if (townSide == null) return;
getSieges().forEach(siege -> { // TODO INFINITE LOOP, runs surrenderTown
if (siege.getTown().equals(town)) {
if (siege.getAttackerSide().equals(townSide)) {
siege.defendersWin(BattleVictoryReason.ADMIN_CANCEL);
} else {
siege.attackersWin(BattleVictoryReason.ADMIN_CANCEL);
}
}
});
}
}
/**
* Surrender a nation and all its towns out of the war.
*
* @param nation the nation
*/
public void surrenderNation(Nation nation) {
Side nationSide = getNationSide(nation);
if (nationSide == null) return;
final @Nullable Nation occupier = nationSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
Occupation.setOccupied(nation, occupier);
nationSide.surrenderNation(nation);
// TODO Cancel in progress sieges for towns?
nationSide.processSurrenders();
}
/**
* Surrender town and all its players out of a war.
*
* @param town the town
*/
public void surrenderTown(Town town) {
Side townSide = getTownSide(town);
if (townSide == null) return;
final @Nullable Nation townNation = town.getNationOrNull();
final @Nullable Nation occupier = townSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
Occupation.setOccupied(town, occupier);
townSide.surrenderTown(town);
if (townNation != null) {
if (townSide.shouldNationSurrender(townNation)) {
surrenderNation(townNation);
}
}
// TODO Cancel in progress sieges for towns?
townSide.processSurrenders();
}
/**
* Unsurrender a nation and all its towns and players.
*
* @param nation the nation
*/
public void unsurrenderNation(Nation nation) {
Side nationSide = getNationSide(nation);
if (nationSide == null) return;
nationSide.unsurrenderNation(nation);
nation.getTowns().forEach(this::unsurrenderTown);
}
/**
* Unsurrender town and all its players.
*
* @param town the town
*/
public void unsurrenderTown(Town town) {
Side townSide = getTownSide(town);
if (townSide == null) return;
Occupation.removeOccupied(town);
townSide.unsurrenderTown(town);
}
/**
* Gets towns in the war excluding surrendered ones.
*
* @return the towns
*/
@NotNull
public Set<Town> getTowns() {
return Stream.concat(
getSide1().getTowns().stream(),
getSide2().getTowns().stream()
)
.collect(Collectors.toSet());
}
/**
* Gets all towns in the war including surrendered towns.
*
* @return the all towns
*/
@NotNull
public Set<Town> getAllTowns() {
return Stream.concat(
getSide1().getTowns().stream(),
Stream.concat(
getSide2().getTowns().stream(),
getSurrenderedTowns().stream()
)
)
.collect(Collectors.toSet());
}
/**
* Gets nations in the war excluding surrendered ones.
*
* @return the nations
*/
@NotNull
public Set<Nation> getNations() {
return Stream.concat(
getSide1().getNations().stream(),
getSide2().getNations().stream()
)
.collect(Collectors.toSet());
}
/**
* Gets all nations in the war including surrendered.
*
* @return the all nations
*/
@NotNull
public Set<Nation> getAllNations() {
return Stream.concat(
getSide1().getNations().stream(),
Stream.concat(
getSide2().getNations().stream(),
getSurrenderedNations().stream()
)
)
.collect(Collectors.toSet());
}
/**
* Gets all surrendered towns in the war.
*
* @return the surrendered towns
*/
@NotNull
public Set<Town> getSurrenderedTowns() {
return Stream.concat(
getSide1().getSurrenderedTowns().stream(),
getSide2().getSurrenderedTowns().stream()
)
.collect(Collectors.toSet());
}
/**
* Gets all surrendered nations in the war.
*
* @return the surrendered nations
*/
@NotNull
public Set<Nation> getSurrenderedNations() {
return Stream.concat(
getSide1().getSurrenderedNations().stream(),
getSide2().getSurrenderedNations().stream()
)
.collect(Collectors.toSet());
}
/**
* Start a new war after creation.
*/
@ApiStatus.Internal
public void start() {
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has started between <attacker> and <defender>.")
.parseMinimessagePlaceholder("war", getLabel())
.parseMinimessagePlaceholder("attacker", getAttacker().getName())
.parseMinimessagePlaceholder("defender", getDefender().getName())
.build()
);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>The war of <war> has begun!")
.parseMinimessagePlaceholder("war", getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
side1.getPlayers().forEach(player -> {
player.showTitle(warTitle);
player.playSound(warSound);
});
side2.getPlayers().forEach(player -> {
player.showTitle(warTitle);
player.playSound(warSound);
});
side1.applyNameTags();
side2.applyNameTags();
}
/**
* Resume a pre-existing war after loading it from db.
*/
@ApiStatus.Internal
public void resume() {
side1.applyNameTags();
side2.applyNameTags();
}
/**
* End a war for the specified reason. Triggered internally by {@link War#defeat(Side)} & {@link War#draw()}.
*
* @param reason the reason
*/
@ApiStatus.Internal
public void end(WarDeleteReason reason) {
if (!new PreWarDeleteEvent(this, reason).callEvent())
return;
getSieges().forEach(Siege::stop);
getAllTowns().forEach(Occupation::removeOccupied);
DatabaseQueries.deleteWar(this);
WarController.getInstance().removeWar(this);
// Run check after war is removed to cleanup player tags
getPlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
new WarDeleteEvent(this, reason).callEvent();
}
/**
* End the war in defeat for the specified side. Internally runs {@link War#end(WarDeleteReason)}.
*
* @param loserSide the loser side
*/
public void defeat(Side loserSide) {
Side loser = loserSide.equals(getSide1()) ? getSide1() : getSide2();
Side winner = loserSide.equals(getSide1()) ? getSide2() : getSide1();
Bukkit.broadcast(ColorParser.of(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(WarDeleteReason.DEFEAT);
}
/**
* End the war in a white peace/draw. Internally runs {@link War#end(WarDeleteReason)}.
*/
public void draw() {
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has ended with a white peace.")
.parseMinimessagePlaceholder("war", getLabel())
.build()
);
end(WarDeleteReason.DRAW);
}
/**
* Sets if this is an event war.
*
* @param event the event
*/
public void setEventWar(boolean event) {
this.event = event;
}
/**
* Gets if this is an event war. Event wars skip or execute certain logic as they are for player events.
*
* @return the boolean
*/
public boolean isEventWar() {
return event;
}
}
@@ -0,0 +1,141 @@
package com.github.alathra.alathranwars.conflict.war;
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
import com.github.alathra.alathranwars.enums.ConflictType;
import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class WarBuilder {
private UUID uuid;
private String name;
private String label;
private ConflictType conflictType = ConflictType.WAR;
private boolean event = false;
private Side side1;
private Side side2;
private Set<Siege> sieges = new HashSet<>();
private Set<Raid> raids = new HashSet<>();
private Government aggressor;
private Government victim;
public WarBuilder() {
}
public War resume() {
if (
uuid == null ||
name == null ||
label == null ||
side1 == null ||
side2 == null ||
sieges == null ||
raids == null
) {
throw new IllegalStateException();
}
return new War(
uuid,
name,
label,
side1,
side2,
sieges,
raids,
event
);
}
public War create() throws WrapperCommandSyntaxException, SideCreationException {
this.setUuid(UUID.randomUUID());
return new War(
uuid,
label,
aggressor,
victim,
event
);
}
public WarBuilder setUuid(UUID uuid) {
this.uuid = uuid;
return this;
}
public WarBuilder setName(String name) {
this.name = name;
return this;
}
public WarBuilder setLabel(String label) {
this.label = label;
return this;
}
public WarBuilder setConflictType(ConflictType conflictType) {
this.conflictType = conflictType;
return this;
}
public WarBuilder setSide1(Side side1) {
this.side1 = side1;
return this;
}
public WarBuilder setSide2(Side side2) {
this.side2 = side2;
return this;
}
public WarBuilder setEvent(boolean event) {
this.event = event;
return this;
}
public WarBuilder setSieges(Set<Siege> sieges) {
this.sieges = sieges;
return this;
}
public WarBuilder setRaids(Set<Raid> raids) {
this.raids = raids;
return this;
}
public WarBuilder setAggressorTown(Town target) {
return this;
}
public WarBuilder setAggressorNation(Nation target) {
return this;
}
public WarBuilder setVictimTown(Town target) {
return this;
}
public WarBuilder setVictimNation(Nation target) {
return this;
}
public WarBuilder setAggressor(Government aggressor) {
this.aggressor = aggressor;
return this;
}
public WarBuilder setVictim(Government victim) {
this.victim = victim;
return this;
}
}
@@ -0,0 +1,419 @@
package com.github.alathra.alathranwars.conflict.war;
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.db.DatabaseQueries;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.inject.Singleton;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* The singleton War controller.
*/
@Singleton
public class WarController {
private static WarController instance;
private @NotNull Set<War> wars = new HashSet<>();
private WarController() {
if (instance != null)
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
}
/**
* Gets or creates an instance of the war controller.
*
* @return the instance
*/
@NotNull
public static WarController getInstance() {
if (instance == null)
instance = new WarController();
return instance;
}
/**
* Load all wars into memory from database.
*/
@ApiStatus.Internal
public void loadAll() {
wars = DatabaseQueries.loadAll();
}
/**
* Gets all wars.
*
* @return the wars
*/
@NotNull
public Set<War> getWars() {
return wars;
}
/**
* Gets war by its name or returns null.
*
* @param warName the war name
* @return the war
*/
@Nullable
public War getWar(String warName) {
return getWars().stream()
.filter(war -> war.equals(warName))
.findAny()
.orElse(null);
}
/**
* Gets war by its UUID or returns null.
*
* @param uuid the uuid
* @return the war
*/
@Nullable
public War getWar(UUID uuid) {
return getWars().stream()
.filter(war -> war.equals(uuid))
.findAny()
.orElse(null);
}
/**
* Gets side by the side UUID.
*
* @param uuid the uuid
* @return the side
*/
@Nullable
public Side getSide(UUID uuid) {
return getWars().stream()
.filter(war -> war.getSide(uuid) != null)
.map(war -> war.getSide(uuid))
.findAny()
.orElse(null);
}
/**
* Gets siege by the siege UUID.
*
* @param uuid the uuid
* @return the siege
*/
@Nullable
public Siege getSiege(UUID uuid) {
return getWars().stream()
.filter(war -> war.getSiege(uuid) != null)
.map(war -> war.getSiege(uuid))
.findAny()
.orElse(null);
}
/**
* Add a war to the war controller.
*
* @param war the war
*/
@ApiStatus.Internal
public void addWar(War war) {
getWars().add(war);
}
/**
* Remove a war from the war controller.
*
* @param war the war
*/
@ApiStatus.Internal
public void removeWar(War war) {
getWars().remove(war);
}
/**
* Is player in any wars. Includes if surrendered.
*
* @param uuid the uuid
* @return the boolean
*/
public boolean isPlayerInAnyWars(UUID uuid) {
return getWars().stream()
.anyMatch(war -> war.isPlayerInWar(uuid));
}
/**
* Is player in any wars. Includes if surrendered.
*
* @param p the p
* @return the boolean
*/
public boolean isPlayerInAnyWars(Player p) {
return isPlayerInAnyWars(p.getUniqueId());
}
/**
* Gets list of player wars. Includes if surrendered.
*
* @param p the p
* @return the player wars
*/
public @NotNull Set<War> getPlayerWars(Player p) {
return getPlayerWars(p.getUniqueId());
}
/**
* Gets list of player wars. Includes if surrendered.
*
* @param uuid the uuid
* @return the player wars
*/
public @NotNull Set<War> getPlayerWars(UUID uuid) {
return getWars().stream()
.filter(war -> war.isPlayerInWar(uuid))
.collect(Collectors.toSet());
}
/**
* Is town in any wars. Includes surrendered towns.
*
* @param town the town
* @return the boolean
*/
public boolean isTownInAnyWars(Town town) {
return getWars().stream()
.anyMatch(war -> war.isTownInWar(town));
}
/**
* Is town in any sieges. Includes surrendered towns.
*
* @param town the town
* @return the boolean
*/
public boolean isTownInAnySieges(Town town) {
return getWars().stream()
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderSiege(town));
}
/**
* Is town in any raids. Includes surrendered towns.
*
* @param town the town
* @return the boolean
*/
public boolean isTownInAnyRaids(Town town) {
return getWars().stream()
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderRaid(town));
}
/**
* Is nation in any sieges. Includes surrendered nations.
*
* @param nation the nation
* @return the boolean
*/
public boolean isNationInAnySieges(Nation nation) {
return nation.getTowns().stream()
.anyMatch(this::isTownInAnySieges);
}
/**
* Is nation in any raids. Includes surrendered nations.
*
* @param nation the nation
* @return the boolean
*/
public boolean isNationInAnyRaids(Nation nation) {
return nation.getTowns().stream()
.anyMatch(this::isTownInAnyRaids);
}
/**
* Gets town sieges. Includes surrendered towns.
*
* @param town the town
* @return the town sieges
*/
public @NotNull Set<Siege> getTownSieges(Town town) {
return getSieges().stream()
.filter(siege -> siege.getAttackerSide().isTownOnSide(town) || siege.getDefenderSide().isTownOnSide(town))
.collect(Collectors.toSet());
}
/**
* Gets town raids. Includes surrendered towns.
*
* @param town the town
* @return the town raids
*/
public @NotNull Set<Raid> getTownRaids(Town town) {
return getRaids().stream()
.filter(raid -> raid.getAttackerSide().isTownOnSide(town) || raid.getDefenderSide().isTownOnSide(town))
.collect(Collectors.toSet());
}
/**
* Gets town wars. Includes surrendered towns.
*
* @param town the town
* @return the town wars
*/
public @NotNull Set<War> getTownWars(Town town) {
return getWars().stream()
.filter(war -> war.isTownInWar(town))
.collect(Collectors.toSet());
}
/**
* Is nation in any wars. Includes surrendered nations.
*
* @param nation the nation
* @return the boolean
*/
public boolean isNationInAnyWars(Nation nation) {
return getWars().stream()
.anyMatch(war -> war.isNationInWar(nation));
}
/**
* Gets nation wars. Includes surrendered nations.
*
* @param nation the nation
* @return the nation wars
*/
public @NotNull Set<War> getNationWars(Nation nation) {
return getWars().stream()
.filter(war -> war.isNationInWar(nation))
.collect(Collectors.toSet());
}
/**
* Gets a list of war names.
*
* @return the war names
*/
@NotNull
public List<String> getWarNames() {
return getWars().stream()
.map(War::getName)
.sorted(String::compareToIgnoreCase)
.collect(Collectors.toList());
}
/**
* Gets a list of war labels.
*
* @return the war labels
*/
@NotNull
public List<String> getWarLabels() {
return getWars().stream()
.map(War::getLabel)
.sorted(String::compareToIgnoreCase)
.collect(Collectors.toList());
}
/**
* Gets a list of all active sieges.
*
* @return the sieges
*/
@NotNull
public Set<Siege> getSieges() {
return getWars().stream()
.map(War::getSieges)
.flatMap(Set::stream)
.collect(Collectors.toSet());
}
/**
* Gets a list of all active raids.
*
* @return the raids
*/
@NotNull
public Set<Raid> getRaids() {
return getWars().stream()
.map(War::getRaids)
.flatMap(Set::stream)
.collect(Collectors.toSet());
}
/**
* Is player in any siege.
*
* @param p the p
* @return the boolean
*/
public boolean isPlayerInAnySiege(Player p) {
return isPlayerInAnySiege(p.getUniqueId());
}
/**
* Is player in any siege. Returns true for offline players.
*
* @param uuid the uuid
* @return the boolean
*/
public boolean isPlayerInAnySiege(UUID uuid) {
return getSieges().stream()
.anyMatch(siege -> siege.isPlayerInSiege(uuid));
}
/**
* Gets player sieges.
*
* @param p the p
* @return the player sieges
*/
public @NotNull Set<Siege> getPlayerSieges(Player p) {
return getPlayerSieges(p.getUniqueId());
}
/**
* Gets player sieges. Returns true for offline players.
*
* @param uuid the uuid
* @return the player sieges
*/
public @NotNull Set<Siege> getPlayerSieges(UUID uuid) {
return getSieges().stream()
.filter(siege -> siege.isPlayerInSiege(uuid))
.collect(Collectors.toSet());
}
/**
* Gets nations at war. Does not include surrendered nations.
*
* @return the nations at war
*/
public @NotNull Set<Nation> getNationsAtWar() {
return getWars().stream()
.map(War::getNations)
.flatMap(Set::stream)
.collect(Collectors.toSet());
}
/**
* Gets towns at war. Does not include surrendered towns.
*
* @return the towns at war
*/
public @NotNull Set<Town> getTownsAtWar() {
return getWars().stream()
.map(War::getTowns)
.flatMap(Set::stream)
.collect(Collectors.toSet());
}
}
@@ -0,0 +1,9 @@
package com.github.alathra.alathranwars.conflict.war;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
public class WarCreationException extends SideCreationException {
public WarCreationException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,489 @@
package com.github.alathra.alathranwars.conflict.war.side;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
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.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 static final Duration SIEGE_COOLDOWN = Duration.ofMinutes(30);
private static final Duration RAID_COOLDOWN = Duration.ofMinutes(30);
private final UUID warUUID;
private final UUID uuid;
private final BattleSide side;
private final BattleTeam team;
private final String name; // A town name
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 @NotNull 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 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,
Government government,
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
) throws SideCreationException {
this.warUUID = warUUID;
this.uuid = uuid;
this.side = side;
this.team = team;
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;
if (government instanceof Nation nation) {
this.town = nation.getCapital();
} else if (government instanceof Town town2) {
this.town = town2;
} else {
throw new SideCreationException("No town or nation specified!");
}
calculateOnlinePlayers();
}
public Side(UUID warUUID, UUID uuid, Government government, BattleSide side, BattleTeam team) throws SideCreationException {
this.warUUID = warUUID;
this.uuid = uuid;
this.side = side;
this.team = team;
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<>();
if (government instanceof Nation nation) {
this.town = nation.getCapital();
addNation(nation);
} else if (government instanceof Town town2) {
this.town = town2;
addTown(town2);
} else {
throw new SideCreationException("No town or nation specified!");
}
this.name = this.town.getName();
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 @NotNull 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 void unsurrenderTown(Town town) {
if (!isTownSurrendered(town)) return;
addTown(town);
surrenderedTowns.remove(town);
town.getResidents().forEach((Resident resident) -> unsurrenderPlayer(resident.getUUID()));
}
public void unsurrenderNation(Nation nation) {
if (!isNationSurrendered(nation)) return;
addNation(nation);
surrenderedNations.remove(nation);
nation.getTowns().forEach(this::unsurrenderTown);
}
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 (getWar() != null) { // We need to check this as on side creation War doesn't exist
for (Siege siege : getWar().getSieges()) {
if (siege.getAttackerSide().equals(this)) {
siege.addPlayer(uuid, BattleSide.ATTACKER);
} else {
siege.addPlayer(uuid, BattleSide.DEFENDER);
}
}
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable 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 (getWar() != null) { // We need to check this as on side creation War doesn't exist
for (Siege siege : getWar().getSieges()) {
if (siege.getAttackerSide().equals(this)) {
siege.removePlayer(uuid);
} else {
siege.removePlayer(uuid);
}
}
}
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
final @Nullable 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 unsurrenderPlayer(Player p) {
unsurrenderPlayer(p.getUniqueId());
}
public void unsurrenderPlayer(UUID uuid) {
if (!isPlayerSurrendered(uuid)) return;
addPlayer(uuid);
surrenderedPlayersIncludingOffline.remove(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(p -> NameColorHandler.getInstance().getPlayerNameColor(p));
surrenderedPlayersIncludingOffline.stream()
.filter((UUID uuid) -> Bukkit.getPlayer(uuid) != null)
.map(Bukkit::getPlayer)
.toList()
.forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
}
// Graces
public Instant getSiegeGrace() {
return siegeGrace;
}
public void setSiegeGrace() {
siegeGrace = Instant.now().plus(SIEGE_COOLDOWN);
}
public boolean isSiegeGraceActive() {
return siegeGrace.isAfter(Instant.now());
}
public Duration getSiegeGraceCooldown() {
return Duration.between(Instant.now(), siegeGrace);
}
public Instant getRaidGrace() {
return raidGrace;
}
public void setRaidGrace() {
raidGrace = Instant.now().plus(RAID_COOLDOWN);
}
public boolean isRaidGraceActive() {
return 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;
}
@Nullable
public War getWar() {
return WarController.getInstance().getWar(warUUID); // The war must exist, or this object wouldn't
}
public void processSurrenders() {
if (shouldSurrender())
surrenderWar();
}
private void surrenderWar() {
War war = getWar();
if (war != null)
getWar().defeat(this);
}
private boolean shouldSurrender() {
return nations.isEmpty() && towns.isEmpty();
}
public boolean shouldNationSurrender(Nation nation) {
final int townsQty = nation.getNumTowns();
// List<Town> towns = nation.getTowns();
final int surrenderedTownsQty = nation.getTowns().stream().filter(this::isTownSurrendered).mapToInt(value -> 1).sum();
/*int surrenderedTownsQty = 0;
for (Town town : towns) {
if (isTownSurrendered(town))
surrenderedTownsQty++;
}*/
return surrenderedTownsQty == townsQty;
}
public Town getTown() {
return town;
}
}
@@ -0,0 +1,158 @@
package com.github.alathra.alathranwars.conflict.war.side;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import java.time.Instant;
import java.util.Set;
import java.util.UUID;
public class SideBuilder {
private UUID warUUID;
private UUID uuid;
private BattleSide side;
private BattleTeam team;
private String name;
private Government government;
private Set<Town> towns;
private Set<Nation> nations;
private Set<UUID> playersIncludingOffline;
private Set<Town> surrenderedTowns;
private Set<Nation> surrenderedNations;
private Set<UUID> surrenderedPlayersIncludingOffline;
private Instant siegeGrace;
private Instant raidGrace;
public SideBuilder() {
}
public Side rebuild() throws SideCreationException {
// if (warUUID == null || uuid == null || town == null || side == null || team == null || name == null ||
// towns == null || nations == null || playersIncludingOffline == null ||
// surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
// siegeGrace == null || raidGrace == null
// ) throw new IllegalStateException("Missing state to create Side 1");
// TODO Cleanup this shit
if (warUUID == null || uuid == null
) throw new IllegalStateException("Missing state to create Side 1.2");
if (government == null
) throw new IllegalStateException("Missing state to create Side 1.3");
if (side == null
) throw new IllegalStateException("Missing state to create Side 1.1");
if (team == null || name == null ||
towns == null || nations == null
) throw new IllegalStateException("Missing state to create Side 1");
if (playersIncludingOffline == null ||
surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
siegeGrace == null || raidGrace == null
) throw new IllegalStateException("Missing state to create Side 2");
return new Side(
warUUID,
uuid,
government,
side,
team,
name,
towns,
nations,
playersIncludingOffline,
surrenderedTowns,
surrenderedNations,
surrenderedPlayersIncludingOffline,
siegeGrace,
raidGrace
);
}
public Side build() throws SideCreationException {
if (warUUID == null || uuid == null || government == null || side == null || team == null)
throw new IllegalStateException("Missing state to create new Side");
return new Side(
warUUID,
uuid,
government,
side,
team
);
}
public SideBuilder setWarUUID(UUID warUUID) {
this.warUUID = warUUID;
return this;
}
public SideBuilder setUuid(UUID uuid) {
this.uuid = uuid;
return this;
}
public SideBuilder setSide(BattleSide side) {
this.side = side;
return this;
}
public SideBuilder setTeam(BattleTeam team) {
this.team = team;
return this;
}
public SideBuilder setName(String name) {
this.name = name;
return this;
}
public SideBuilder setLeader(Government target) {
this.government = target;
return this;
}
public SideBuilder setTowns(Set<Town> towns) {
this.towns = towns;
return this;
}
public SideBuilder setNations(Set<Nation> nations) {
this.nations = nations;
return this;
}
public SideBuilder setPlayersIncludingOffline(Set<UUID> playersIncludingOffline) {
this.playersIncludingOffline = playersIncludingOffline;
return this;
}
public SideBuilder setSurrenderedTowns(Set<Town> surrenderedTowns) {
this.surrenderedTowns = surrenderedTowns;
return this;
}
public SideBuilder setSurrenderedNations(Set<Nation> surrenderedNations) {
this.surrenderedNations = surrenderedNations;
return this;
}
public SideBuilder setSurrenderedPlayersIncludingOffline(Set<UUID> surrenderedPlayersIncludingOffline) {
this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
return this;
}
public SideBuilder setSiegeGrace(Instant siegeGrace) {
this.siegeGrace = siegeGrace;
return this;
}
public SideBuilder setRaidGrace(Instant raidGrace) {
this.raidGrace = raidGrace;
return this;
}
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.conflict.war.side;
public class SideCreationException extends Exception {
public SideCreationException(String errorMessage) {
super(errorMessage);
}
}
@@ -0,0 +1,72 @@
package com.github.alathra.alathranwars.data;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
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 @Nullable RaidPhase getByName(String name) {
for (@NotNull 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 @Nullable RaidPhase getByID(int id) {
for (@NotNull RaidPhase p : RaidPhase.values()) {
if (p.id == id) return p;
}
return null;
}
public static @Nullable RaidPhase getNext(@NotNull 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,40 @@
package com.github.alathra.alathranwars.data;
import com.github.alathra.alathranwars.AlathranWars;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.metadata.LocationDataField;
import com.palmergames.bukkit.towny.utils.MetaDataUtil;
import org.bukkit.Location;
public class TownMetaController {
private AlathranWars plugin;
private static LocationDataField defendersSpawn = new LocationDataField("alathranwars_defendersSpawn");
TownMetaController(AlathranWars plugin) {
this.plugin = plugin;
}
public static boolean hasDefendersSpawn(Town town) {
return town.hasMeta(defendersSpawn.getKey());
}
public static Location getDefendersSpawn(Town town) {
if (hasDefendersSpawn(town)) {
return MetaDataUtil.getLocation(town, defendersSpawn);
} else {
Location location = town.getSpawnOrNull();
setDefendersSpawn(town, location);
return location;
}
}
public static void setDefendersSpawn(Town town, Location location) {
if (hasDefendersSpawn(town)) {
MetaDataUtil.setLocation(town, defendersSpawn, location, true);
} else {
town.addMetaData(new LocationDataField(defendersSpawn.getKey(), location));
}
}
}
@@ -0,0 +1,303 @@
package com.github.alathra.alathranwars.db;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.Reloadable;
import com.github.alathra.alathranwars.db.flyway.DatabaseMigrationException;
import com.github.alathra.alathranwars.db.flyway.DatabaseMigrationHandler;
import com.github.alathra.alathranwars.db.jooq.JooqContext;
import com.github.alathra.alathranwars.utility.Cfg;
import com.github.alathra.alathranwars.utility.Logger;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull;
import javax.inject.Singleton;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
/**
* Class that handles HikariCP connection pool, jOOQ and Flyway migrations.
*/
@Singleton
public class DatabaseHandler implements Reloadable {
private final AlathranWars alathranWars;
private boolean isConnected = false;
private HikariDataSource hikariDataSource;
private DatabaseType database;
private JooqContext jooqContext;
/**
* Instantiates a new Data handler.
*
* @param alathranWars the plugin instance
*/
public DatabaseHandler(AlathranWars alathranWars) {
this.alathranWars = alathranWars;
}
/**
* On plugin load.
*/
@Override
public void onLoad() {
try {
openConnection();
isConnected = true;
} catch (Exception e) {
Logger.get().error("[DB] Database initialization error: ", e);
} finally {
if (!isConnected()) {
Logger.get().warn("[DB] Failed to initialize database connection. Functionality will be limited.");
}
}
}
/**
* On plugin enable.
*/
@Override
public void onEnable() {
}
/**
* On plugin disable.
*/
@Override
public void onDisable() {
try {
closeDatabaseConnection();
isConnected = false;
} catch (Exception e) {
Logger.get().error("[DB] Error closing database connections:", e);
}
}
/**
* Returns if the database is setup and functioning properly.
*
* @return the boolean
*/
public boolean isConnected() {
return isConnected;
}
/**
* Gets db.
*
* @return the db
*/
public DatabaseType getDB() {
return database;
}
/**
* Gets jooq context.
*
* @return the jooq context
*/
public JooqContext getJooqContext() {
return jooqContext;
}
/**
* Gets a connection from the connection pool.
*
* @return the connection
* @throws SQLException the sql exception
*/
@NotNull
public Connection getConnection() throws SQLException {
if (hikariDataSource == null)
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource returned null)");
final Connection connection = hikariDataSource.getConnection();
if (connection == null)
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource#getConnection returned null)");
return connection;
}
/**
* Creates a connection pool using HikariCP and executes Flyway migrations.
*/
private void openConnection() {
if (hikariDataSource != null) {
Logger.get().warn("[DB] Attempted to create a new database pool while running!");
return;
}
final HikariConfig hikariConfig = new HikariConfig();
final String vendorName = Cfg.get().get("db.type", DatabaseType.HSQLDB.getDriverName());
final DatabaseType db = DatabaseType.getDatabaseTypeFromJdbcPrefix(vendorName);
if (db == null) {
Logger.get().warn("[DB] Invalid database type was specified!");
return;
}
final String host = Cfg.get().get("db.host", "127.0.0.1");
final String port = Cfg.get().get("db.port", "3306");
final String database = Cfg.get().get("db.database", "database");
final String username = Cfg.get().get("db.user", "root");
final String password = Cfg.get().get("db.pass", "");
final String connectionProperties = switch (db) {
case H2 -> DatabaseType.H2.formatJdbcConnectionProperties(
Map.of(
"AUTO_SERVER", "TRUE",
"MODE", "MySQL", // MySQL support mode
"CASE_INSENSITIVE_IDENTIFIERS", "TRUE",
"IGNORECASE", "TRUE"
)
);
case HSQLDB -> DatabaseType.HSQLDB.formatJdbcConnectionProperties(
Map.of(
"sql.syntax_mys", "true", // MySQL support mode
// Prevent execution of multiple queries in one Statement
"sql.restrict_exec", true,
// Make the names of generated indexes the same as the names of the constraints
"sql.sys_index_names", true,
/*
* Enforce SQL standards on
* 1.) table and column names
* 2.) ambiguous column references
* 3.) illegal type conversions
*/
"sql.enforce_names", true,
"sql.enforce_refs", true,
"sql.enforce_types", true,
// Respect interrupt status during query execution
"hsqldb.tx_interrupt_rollback", true,
// Use CACHED tables by default
"hsqldb.default_table_type", "cached",
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
"allowMultiQueries", true,
// Help debug in case of exceptions
"dumpQueriesOnException", true
)
);
case MARIADB -> DatabaseType.MARIADB.formatJdbcConnectionProperties(
Map.of(
// Performance improvements
"autocommit", false,
"defaultFetchSize", 1000,
// Help debug in case of deadlock
"includeInnodbStatusInDeadlockExceptions", true,
"includeThreadDumpInDeadlockExceptions", true,
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
"socketTimeout", 14000L,
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
"allowMultiQueries", true,
// Help debug in case of exceptions
"dumpQueriesOnException", true
)
);
case MYSQL -> DatabaseType.MYSQL.formatJdbcConnectionProperties(
Map.of(
// Performance improvements
"autocommit", false,
"defaultFetchSize", 1000,
// Help debug in case of deadlock
"includeInnodbStatusInDeadlockExceptions", true,
"includeThreadDumpInDeadlockExceptions", true,
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
"socketTimeout", 14000L,
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
"allowMultiQueries", true,
// Help debug in case of exceptions
"dumpQueriesOnException", true
)
);
};
switch (db) {
case HSQLDB, H2 -> {
final String subfolder = "data";
final String fileName = "database";
final String fileExtension = switch (db) {
case HSQLDB -> ".hsql";
case H2 -> ".mv.db";
default -> "";
};
final String fileNameWithExtension = fileName + fileExtension;
// Set credentials for HSQL and H2
hikariConfig.setUsername("SA");
hikariConfig.setPassword("");
hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
hikariConfig.addDataSourceProperty("url", "jdbc:%s:%s".formatted(
db.getJdbcPrefix(),
alathranWars.getDataFolder().getAbsolutePath() + File.separatorChar + subfolder + File.separatorChar + (db.equals(DatabaseType.H2) ? fileName : fileNameWithExtension) + connectionProperties
));
}
case MYSQL, MARIADB -> {
hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
hikariConfig.addDataSourceProperty("url", "jdbc:%s://%s%s/%s".formatted(
db.getJdbcPrefix(),
host,
":%s".formatted(port),
database + connectionProperties
));
hikariConfig.setUsername(username);
hikariConfig.setPassword(password);
hikariConfig.setKeepaliveTime(0);
}
}
hikariConfig.setConnectionTimeout(14000);
hikariConfig.setMaxLifetime(25000000);
hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
final int poolSize = Cfg.get().getOrDefault("db.poolsize", 10);
hikariConfig.setMaximumPoolSize(poolSize);
hikariConfig.setMinimumIdle(poolSize);
hikariConfig.setPoolName("%s-hikari".formatted(AlathranWars.getInstance().getName()));
hikariConfig.setAutoCommit(true);
hikariConfig.setTransactionIsolation("TRANSACTION_REPEATABLE_READ");
hikariConfig.setIsolateInternalQueries(true);
hikariConfig.setConnectionInitSql(db.getConnectionInitSql());
this.hikariDataSource = new HikariDataSource(hikariConfig);
this.database = db;
this.jooqContext = new JooqContext(db.getSQLDialect());
try {
new DatabaseMigrationHandler(Cfg.get(), hikariDataSource, db)
.migrate();
} catch (DatabaseMigrationException e) {
Logger.get().error("[DB] Failed to migrate database. Please backup your database and report the issue.", e);
}
}
/**
* Closes the connection pool.
*/
private void closeDatabaseConnection() throws Exception {
Logger.get().info("[DB] Closing database connection...");
if (hikariDataSource == null) {
Logger.get().error("[DB] Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
return;
}
if (hikariDataSource.isClosed()) {
Logger.get().info("[DB] Skipped closing database connection: connection is already closed.");
return;
}
hikariDataSource.close();
hikariDataSource = null;
Logger.get().info("[DB] Closed database connection.");
}
}
@@ -0,0 +1,556 @@
package com.github.alathra.alathranwars.db;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
import com.github.alathra.alathranwars.utility.DB;
import com.github.alathra.alathranwars.utility.Logger;
import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.exception.DataAccessException;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import static com.github.alathra.alathranwars.db.schema.Tables.*;
/**
* A holder class for all SQL queries
*/
public abstract class DatabaseQueries {
private interface LambdaInterface {
void execute(Connection connection, DSLContext dslContext) throws SQLException, DataAccessException;
}
private static void transactionWrapper(Connection con, LambdaInterface lambda) throws SQLException, DataAccessException {
DSLContext context = DB.getContext(con);
final Savepoint savePoint = con.setSavepoint();
final boolean autoCommit = con.getAutoCommit();
try {
con.setAutoCommit(false);
lambda.execute(con, context);
con.commit();
} catch (SQLException | DataAccessException e) {
con.rollback(savePoint);
} finally {
con.setAutoCommit(autoCommit);
}
}
public static byte[] convertUUIDToBytes(UUID uuid) {
ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(uuid.getMostSignificantBits());
buffer.putLong(uuid.getLeastSignificantBits());
return buffer.array();
}
public static UUID convertBytesToUUID(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
}
// Setters
public static void saveAll() {
try (
Connection con = DB.getConnection();
) {
DSLContext context = DB.getContext(con);
for (War war : WarController.getInstance().getWars()) {
context
// .insertInto(LIST)
// .set(LIST.UUID, DatabaseQueries.convertUUIDToBytes(war.getUUID()))
// .set(LIST.NAME, war.getName())
// .set(LIST.LABEL, war.getLabel())
// .set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
// .set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
// .set(LIST.EVENT, war.isEventWar() ? (byte) 1 : (byte) 0)
.insertInto(LIST, LIST.UUID, LIST.NAME, LIST.LABEL, LIST.SIDE1, LIST.SIDE2, LIST.EVENT)
.values(
DatabaseQueries.convertUUIDToBytes(war.getUUID()),
war.getName(),
war.getLabel(),
DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()),
DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()),
war.isEventWar() ? (byte) 1 : (byte) 0
)
.onDuplicateKeyUpdate()
.set(LIST.NAME, war.getName())
.set(LIST.LABEL, war.getLabel())
.set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
.set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
.execute();
// Save sides
for (Side side : war.getSides()) {
saveSide(con, side);
}
// Save sieges
for (Siege siege : war.getSieges()) {
saveSiege(con, siege);
}
}
} catch (SQLException e) {
Logger.get().error("SQL Query failed to save data!", e);
}
}
public static void saveSide(Connection con, Side side) {
try {
DSLContext context = DB.getContext(con);
context
.insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGEGRACE, SIDES.RAIDGRACE)
.values(
convertUUIDToBytes(side.getWar().getUUID()),
convertUUIDToBytes(side.getUUID()),
side.getSide().toString(),
side.getTeam().toString(),
side.getName(),
convertUUIDToBytes(side.getTown().getUUID()),
LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC),
LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC)
)
.onDuplicateKeyUpdate()
.set(SIDES.SIDE, side.getSide().toString())
.set(SIDES.TEAM, side.getTeam().toString())
.set(SIDES.NAME, side.getName())
.set(SIDES.TOWN, convertUUIDToBytes(side.getTown().getUUID()))
.set(SIDES.SIEGEGRACE, LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC))
.set(SIDES.RAIDGRACE, LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC))
.execute();
saveSideNations(con, side);
saveSideTowns(con, side);
saveSidePlayers(con, side);
} catch (DataAccessException e) {
Logger.get().error("SQL Query failed to save side!", e);
}
}
public static void saveSideNations(Connection con, Side side) {
try {
transactionWrapper(con, (connection, context) -> {
context
.deleteFrom(SIDES_NATIONS)
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
.execute();
for (Nation nation : side.getNations()) {
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(nation.getUUID()),
(byte) 0
)
.execute();
}
for (Nation nation : side.getSurrenderedNations()) {
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(nation.getUUID()),
(byte) 1
)
.execute();
}
});
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query failed to save side nations!", e);
}
}
public static void saveSideTowns(Connection con, Side side) {
try {
transactionWrapper(con, (connection, context) -> {
context
.deleteFrom(SIDES_TOWNS)
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
.execute();
for (Town town : side.getTowns()) {
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(town.getUUID()),
(byte) 0
)
.execute();
}
for (Town town : side.getSurrenderedTowns()) {
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(town.getUUID()),
(byte) 1
)
.execute();
}
});
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query failed to save side towns!", e);
}
}
public static void saveSidePlayers(Connection con, Side side) {
try {
transactionWrapper(con, (connection, context) -> {
context
.deleteFrom(SIDES_PLAYERS)
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
.execute();
for (UUID uuid : side.getPlayersIncludingOffline()) {
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(uuid),
(byte) 0
)
.execute();
}
for (UUID uuid : side.getSurrenderedPlayersIncludingOffline()) {
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
.values(
convertUUIDToBytes(side.getUUID()),
convertUUIDToBytes(uuid),
(byte) 1
)
.execute();
}
});
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query failed to save side players!", e);
}
}
private static void saveSiege(Connection con, Siege siege) {
try {
DSLContext context = DB.getContext(con);
context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGELEADER, SIEGES.ENDTIME, SIEGES.LASTTOUCHED, SIEGES.SIEGEPROGRESS)
.values(
convertUUIDToBytes(siege.getWar().getUUID()),
convertUUIDToBytes(siege.getUUID()),
convertUUIDToBytes(siege.getTown().getUUID()),
convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC),
LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC),
siege.getSiegeProgress()
)
.onDuplicateKeyUpdate()
.set(SIEGES.WAR, convertUUIDToBytes(siege.getWar().getUUID()))
.set(SIEGES.TOWN, convertUUIDToBytes(siege.getTown().getUUID()))
.set(SIEGES.SIEGELEADER, convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()))
.set(SIEGES.ENDTIME, LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC))
.set(SIEGES.LASTTOUCHED, LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC))
.set(SIEGES.SIEGEPROGRESS, siege.getSiegeProgress())
.execute();
saveSiegePlayers(con, siege);
} catch (DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
}
public static void saveSiegePlayers(Connection con, Siege siege) {
try {
transactionWrapper(con, (connection, context) -> {
context
.deleteFrom(SIEGE_PLAYERS)
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(siege.getUUID())))
.execute();
for (UUID uuid : siege.getAttackerPlayersIncludingOffline()) {
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
.values(
convertUUIDToBytes(siege.getUUID()),
convertUUIDToBytes(uuid),
(byte) 0
)
.execute();
}
for (UUID uuid : siege.getDefenderPlayersIncludingOffline()) {
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
.values(
convertUUIDToBytes(siege.getUUID()),
convertUUIDToBytes(uuid),
(byte) 1
)
.execute();
}
});
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
}
// Getters
public static @NotNull Set<War> loadAll() {
Set<War> wars = new HashSet<>();
try (
Connection con = DB.getConnection();
) {
DSLContext context = DB.getContext(con);
Result<Record> result = context.select()
.from(LIST)
.fetch();
for (Record r : result) {
UUID uuid = convertBytesToUUID(r.get(LIST.UUID));
String name = r.get(LIST.NAME);
String label = r.get(LIST.LABEL);
@Nullable Side side1 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE1)));
@Nullable Side side2 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE2)));
boolean event = r.get(LIST.EVENT, Boolean.class);
wars.add( // TODO IllegalStateException
new WarBuilder()
.setUuid(uuid)
.setName(name)
.setLabel(label)
.setSide1(side1)
.setSide2(side2)
.setSieges(new HashSet<>())
.setRaids(new HashSet<>())
.setEvent(event)
.resume()
);
}
for (War war : wars) {
@NotNull Set<Siege> sieges = loadSieges(con, war);
war.setSieges(sieges);
}
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
return wars;
}
@Contract("_, _, _ -> new")
public static @Nullable Side loadSide(Connection con, UUID warUUID, UUID uuid) {
try {
DSLContext context = DB.getContext(con);
Record r = context.select()
.from(SIDES)
.where(SIDES.WAR.equal(convertUUIDToBytes(warUUID)))
.and(SIDES.UUID.equal(convertUUIDToBytes(uuid)))
.fetchOne();
if (r == null) return null;
// Side data
BattleSide side = BattleSide.valueOf(r.get(SIDES.SIDE));
BattleTeam team = BattleTeam.valueOf(r.get(SIDES.TEAM));
String name = r.get(SIDES.NAME);
@Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIDES.TOWN)));
Instant siegeGrace = r.get(SIDES.SIEGEGRACE).toInstant(ZoneOffset.UTC);
Instant raidGrace = r.get(SIDES.RAIDGRACE).toInstant(ZoneOffset.UTC);
// Load players
Set<UUID> players = new HashSet<>();
Set<UUID> playersSurrendered = new HashSet<>();
Result<Record> resultPlayers = context.select()
.from(SIDES_PLAYERS)
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(uuid)))
.fetch();
resultPlayers.forEach(
record -> {
if (record.get(SIDES_PLAYERS.SURRENDERED).equals((byte) 0)) {
players.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
} else {
playersSurrendered.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
}
}
);
// Load nations
Set<Nation> nations = new HashSet<>();
Set<Nation> nationsSurrendered = new HashSet<>();
Result<Record> resultNations = context.select()
.from(SIDES_NATIONS)
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(uuid)))
.fetch();
resultNations.forEach(
record -> {
final UUID identifier = convertBytesToUUID(record.get(SIDES_NATIONS.NATION));
if (record.get(SIDES_NATIONS.SURRENDERED).equals((byte) 0)) {
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
if (nation != null)
nations.add(nation);
} else {
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
if (nation != null)
nationsSurrendered.add(nation);
}
}
);
// Load towns
Set<Town> towns = new HashSet<>();
Set<Town> townsSurrendered = new HashSet<>();
Result<Record> resultTowns = context.select()
.from(SIDES_TOWNS)
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(uuid)))
.fetch();
resultTowns.forEach(
record -> {
final UUID identifier = convertBytesToUUID(record.get(SIDES_TOWNS.TOWN));
if (record.get(SIDES_TOWNS.SURRENDERED).equals((byte) 0)) {
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
if (town2 != null)
towns.add(town2);
} else {
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
if (town2 != null)
townsSurrendered.add(town2);
}
}
);
return new SideBuilder() // TODO IllegalStateException
.setWarUUID(warUUID)
.setUuid(uuid)
.setLeader(town)
.setSide(side)
.setTeam(team)
.setName(name)
.setTowns(towns)
.setNations(nations)
.setPlayersIncludingOffline(players)
.setSurrenderedTowns(townsSurrendered)
.setSurrenderedNations(nationsSurrendered)
.setSurrenderedPlayersIncludingOffline(playersSurrendered)
.setSiegeGrace(siegeGrace)
.setRaidGrace(raidGrace)
.rebuild();
} catch (SideCreationException e) {
Logger.get().error("SQL Query threw an error!", e);
}
return null;
}
public static @NotNull Set<Siege> loadSieges(Connection con, War war) {
Set<Siege> sieges = new HashSet<>();
try {
DSLContext context = DB.getContext(con);
Result<Record> result = context.select()
.from(SIEGES)
.where(SIEGES.WAR.equal(convertUUIDToBytes(war.getUUID())))
.fetch();
for (Record r : result) {
UUID uuid = convertBytesToUUID(r.get(SIEGES.UUID));
@Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIEGES.TOWN)));
OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(convertBytesToUUID(r.get(SIEGES.SIEGELEADER)));
Instant endTime = r.get(SIEGES.ENDTIME).toInstant(ZoneOffset.UTC);
Instant lastTouched = r.get(SIEGES.LASTTOUCHED).toInstant(ZoneOffset.UTC);
int siegeProgress = r.get(SIEGES.SIEGEPROGRESS);
Set<UUID> attackersIncludingOffline = new HashSet<>();
Set<UUID> defendersIncludingOffline = new HashSet<>();
Result<Record> resultPlayers = context.select()
.from(SIEGE_PLAYERS)
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(uuid)))
.fetch();
resultPlayers.forEach(
record -> {
if (record.get(SIEGE_PLAYERS.TEAM).equals((byte) 0)) {
attackersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
} else {
defendersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
}
}
);
sieges.add(new Siege(
war,
uuid,
town,
siegeLeader,
endTime,
lastTouched,
siegeProgress,
attackersIncludingOffline,
defendersIncludingOffline
));
}
} catch (DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
return sieges;
}
// Deleters
public static void deleteWar(War war) {
try (
Connection con = DB.getConnection();
) {
DSLContext context = DB.getContext(con);
context
.deleteFrom(LIST)
.where(LIST.UUID.equal(convertUUIDToBytes(war.getUUID())))
.execute();
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
}
public static void deleteSiege(Siege siege) {
try (
Connection con = DB.getConnection();
) {
DSLContext context = DB.getContext(con);
context
.deleteFrom(SIEGES)
.where(SIEGES.UUID.equal(convertUUIDToBytes(siege.getUUID())))
.execute();
} catch (SQLException | DataAccessException e) {
Logger.get().error("SQL Query threw an error!", e);
}
}
}
@@ -0,0 +1,288 @@
package com.github.alathra.alathranwars.db;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.hsqldb.jdbc.JDBCDataSource;
import org.jetbrains.annotations.Nullable;
import org.jooq.SQLDialect;
import org.mariadb.jdbc.MariaDbDataSource;
import java.util.List;
import java.util.Map;
/**
* Enum containing information for handling different Database types.
*/
public enum DatabaseType {
/**
* HSQLDB database type.
*/
HSQLDB("HSQLDB", org.hsqldb.jdbcDriver.class.getName(), JDBCDataSource.class.getName(), "hsqldb", ';', ';'),
/**
* H2 Database Engine database type.
*/
H2("H2", org.h2.Driver.class.getName(), JdbcDataSource.class.getName(), "h2", ';', ';'),
/**
* MySQL database type.
*/
MYSQL("MySQL", com.mysql.jdbc.Driver.class.getName(), MysqlDataSource.class.getName(), "mysql", '?', '&'),
/**
* MariaDB database type.
*/
MARIADB("MariaDB", org.mariadb.jdbc.Driver.class.getName(), MariaDbDataSource.class.getName(), "mariadb", '?', '&'),
;
private final String driverName;
private final String driverClassName;
private final String dataSourceClassName;
private final String jdbcPrefix;
private final char jdbcPropertyPrefix;
private final char jdbcPropertySeparator;
DatabaseType(String driverName, String driverClassName, String dataSourceClassName, String jdbcPrefix, char jdbcPropertyPrefix, char jdbcPropertySeparator) {
this.driverName = driverName;
this.driverClassName = driverClassName;
this.dataSourceClassName = dataSourceClassName;
this.jdbcPrefix = jdbcPrefix;
this.jdbcPropertyPrefix = jdbcPropertyPrefix;
this.jdbcPropertySeparator = jdbcPropertySeparator;
}
/**
* Gets driver name.
*
* @return the driver name
*/
public String getDriverName() {
return driverName;
}
/**
* Gets driver class name.
*
* @return the driver class name
*/
public String getDriverClassName() {
return driverClassName;
}
/**
* Gets data source class name.
*
* @return the data source class name
*/
public String getDataSourceClassName() {
return dataSourceClassName;
}
/**
* Gets the jdbc prefix.
*
* @return the jdbc prefix like <code>mysql</code> or <code>mariadb</code>
*/
public String getJdbcPrefix() {
return jdbcPrefix;
}
/**
* Gets the jdbc property prefix.
*
* @return the jdbc property prefix like <code>{@literal ;}</code> or <code>{@literal ?}</code>
*/
public char getJdbcPropertyPrefix() {
return jdbcPropertyPrefix;
}
/**
* Gets the jdbc property separator.
*
* @return the jdbc property separator like <code>{@literal ;}</code> or <code>{@literal &}</code>
*/
public char getJdbcPropertySeparator() {
return jdbcPropertySeparator;
}
/**
* Format a map of connection properties into a valid jdbc connection properties string.
*
* @param properties the properties
* @return the string
*/
public String formatJdbcConnectionProperties(Map<String, Object> properties) {
if (properties.isEmpty()) return "";
List<String> connectionProperties = properties.entrySet().stream()
.map(map -> "%s=%s".formatted(map.getKey(), map.getValue()))
.toList();
return jdbcPropertyPrefix + String.join(Character.toString(jdbcPropertySeparator), connectionProperties);
}
/**
* Gets database type from jdbc prefix.
*
* @param prefix the prefix
* @return the database type or null
*/
@Nullable
public static DatabaseType getDatabaseTypeFromJdbcPrefix(String prefix) {
for (DatabaseType type : DatabaseType.values()) {
if (type.equals(prefix.toLowerCase())) {
return type;
}
;
}
return null;
}
@Override
public String toString() {
return getDriverName();
}
/**
* Check if this DatabaseType is equal to another.
*
* @param DatabaseType the database type
* @return boolean
*/
public boolean equals(DatabaseType DatabaseType) {
return this.equals(DatabaseType.getDriverName());
}
/**
* Check if this DatabaseType is equal to another.
*
* @param databaseTypeName the database type name
* @return boolean
*/
public boolean equals(String databaseTypeName) {
return this.getDriverName().equalsIgnoreCase(databaseTypeName);
}
/**
* Gets sql dialect for this DatabaseType.
*
* @return the sql dialect
*/
public SQLDialect getSQLDialect() {
return switch (this) {
case HSQLDB -> SQLDialect.HSQLDB;
case H2 -> SQLDialect.H2;
case MYSQL -> SQLDialect.MYSQL;
case MARIADB -> SQLDialect.MARIADB;
};
}
/**
* Gets column suffix for this DatabaseType.
*
* @return the column suffix
*/
public String getColumnSuffix() {
return switch (this) {
case HSQLDB -> "";
case H2, MARIADB, MYSQL -> " VIRTUAL";
};
}
/**
* Gets table defaults for this DatabaseType.
*
* @return the table defaults
*/
public String getTableDefaults() {
return switch (this) {
case H2, HSQLDB -> "";
case MARIADB, MYSQL -> " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
};
}
/**
* Gets uuid type for this DatabaseType.
*
* @return the uuid type
*/
public String getUuidType() {
return switch (this) {
case HSQLDB -> "UUID";
case H2, MARIADB, MYSQL -> "BINARY(16)";
};
}
/**
* Gets inet type for this DatabaseType.
*
* @return the inet type
*/
public String getInetType() {
return "VARBINARY(16)";
}
/**
* Gets binary type for this DatabaseType.
*
* @return the binary type
*/
public String getBinaryType() {
return "BLOB";
}
/**
* Gets alter view statement for this DatabaseType.
*
* @return the alter view statement
*/
public String getAlterViewStatement() {
return switch (this) {
case H2, HSQLDB, MYSQL, MARIADB -> "ALTER VIEW";
};
}
/**
* Gets connection init sql for this DatabaseType.
*
* @return the connection init sql
*/
public String getConnectionInitSql() {
return switch (this) {
case HSQLDB -> "SET DATABASE TRANSACTION CONTROL MVLOCKS;";
case MARIADB -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
// MariaDB defaults
"STRICT_TRANS_TABLES",
"ERROR_FOR_DIVISION_BY_ZERO",
"NO_AUTO_CREATE_USER",
"NO_ENGINE_SUBSTITUTION",
// ANSI SQL Compliance
"ANSI",
"NO_BACKSLASH_ESCAPES",
"SIMULTANEOUS_ASSIGNMENT", // MDEV-13417
"NO_ZERO_IN_DATE",
"NO_ZERO_DATE");
case H2 -> "";
case MYSQL -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
// MySQL defaults
"STRICT_TRANS_TABLES",
"ERROR_FOR_DIVISION_BY_ZERO",
"NO_ENGINE_SUBSTITUTION",
// ANSI SQL Compliance
"ANSI",
"NO_BACKSLASH_ESCAPES",
"NO_ZERO_IN_DATE",
"NO_ZERO_DATE");
};
}
/**
* Generates a concatenated SQL query from the specified parameters.
*
* @param sqlModes database parameters
* @return string
*/
private static String setSqlModes(String... sqlModes) {
final String modes = String.join(",", sqlModes);
return "SET @@SQL_MODE = CONCAT(@@SQL_MODE, '," + modes + "')";
}
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.db.flyway;
public class DatabaseMigrationException extends Exception {
public DatabaseMigrationException(Throwable t) {
super(t);
}
}
@@ -0,0 +1,101 @@
package com.github.alathra.alathranwars.db.flyway;
import com.github.alathra.alathranwars.db.DatabaseType;
import com.github.milkdrinkers.Crate.Config;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.ClassProvider;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.migration.JavaMigration;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
/**
* Handles Flyway migrations.
*/
public class DatabaseMigrationHandler {
// List of Java migrations
private final List<Class<? extends JavaMigration>> migrations = List.of(
);
private final Config config;
private final DataSource dataSource;
private final DatabaseType databaseType;
private Flyway flyway;
/**
* Instantiates a new Database migration handler.
*
* @param config the config
* @param dataSource the data source
* @param databaseType the database type
*/
public DatabaseMigrationHandler(Config config, DataSource dataSource, DatabaseType databaseType) {
this.config = config;
this.dataSource = dataSource;
this.databaseType = databaseType;
initializeFlywayInstance();
}
private void initializeFlywayInstance() {
final ClassProvider<JavaMigration> javaMigrationClassProvider = new FlywayMigrationsProvider(migrations);
final String SQL_TABLE_PREFIX = config.getOrDefault("db.prefix", "example_");
final Map<String, String> SQL_PLACEHOLDERS = Map.of(
"tablePrefix", SQL_TABLE_PREFIX,
"columnSuffix", databaseType.getColumnSuffix(),
"tableDefaults", databaseType.getTableDefaults(),
"uuidType", databaseType.getUuidType(),
"inetType", databaseType.getInetType(),
"binaryType", databaseType.getBinaryType(),
"alterViewStatement", databaseType.getAlterViewStatement()
);
this.flyway = Flyway
.configure(getClass().getClassLoader())
.baselineOnMigrate(true)
.baselineVersion("0.0")
.validateMigrationNaming(true)
.javaMigrationClassProvider(javaMigrationClassProvider)
.dataSource(dataSource)
.locations(
"classpath:database-migrations",
"db/migration"
)
.table(SQL_TABLE_PREFIX + "schema_history") // Configure tables and migrations
.placeholders(SQL_PLACEHOLDERS)
.load();
}
/**
* Execute Flyway migration. All pending migrations will be applied in order.
*
* @throws DatabaseMigrationException database migration exception
*/
public void migrate() throws DatabaseMigrationException {
try {
this.flyway.migrate();
} catch (FlywayException e) {
throw new DatabaseMigrationException(e);
}
}
/**
* Executes Flyway repair. Repairs the Flyway schema history table. This will perform the following actions:
*
* <ul>
* <li>Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)</li>
* <li>Realign the checksums, descriptions and types of the applied migration</li>
* </ul>
*
* @throws DatabaseMigrationException database migration exception
*/
public void repair() throws DatabaseMigrationException {
try {
if (config.getOrDefault("db.repair", false))
this.flyway.repair();
} catch (FlywayException e) {
throw new DatabaseMigrationException(e);
}
}
}
@@ -0,0 +1,20 @@
package com.github.alathra.alathranwars.db.flyway;
import org.flywaydb.core.api.ClassProvider;
import org.flywaydb.core.api.migration.JavaMigration;
import java.util.Collection;
import java.util.List;
public record FlywayMigrationsProvider(
List<Class<? extends JavaMigration>> migrations
) implements ClassProvider<JavaMigration> {
public FlywayMigrationsProvider(List<Class<? extends JavaMigration>> migrations) {
this.migrations = List.copyOf(migrations);
}
@Override
public Collection<Class<? extends JavaMigration>> getClasses() {
return migrations;
}
}
@@ -0,0 +1,22 @@
package com.github.alathra.alathranwars.db.flyway.migration;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
public class V3__Example extends BaseJavaMigration {
@Override
public void migrate(Context flywayContext) throws Exception {
/*try {
final DSLContext context = DB.getContext(flywayContext.getConnection());
context.alterTable(TEST).addColumn(field(name("meme"), VARCHAR)).execute();
context
.alterTableIfExists(TEST)
.addColumnIfNotExists(field(name("column_name"), VARCHAR(32).notNull()*//*.defaultValue("default")*//*))
.execute();
} catch (Exception e) {
Logger.get().error(e.getMessage());
}*/
}
}
@@ -0,0 +1,93 @@
package com.github.alathra.alathranwars.db.jooq;
import com.github.alathra.alathranwars.utility.Cfg;
import org.jooq.*;
import org.jooq.conf.*;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.tools.JooqLogger;
import java.sql.Connection;
import java.util.regex.Pattern;
/**
* Utility class for getting jOOQ Context to use with HikariCP.
*/
public final class JooqContext {
static {
JooqLogger.globalThreshold(Log.Level.ERROR); // Silence JOOQ warnings
}
private static final String TABLE_PREFIX = Cfg.get().getOrDefault("db.prefix", "example_"); // The table prefix as grabbed from config
private static final Pattern MATCH_ALL_EXCEPT_INFORMATION_SCHEMA = Pattern.compile("^(?!INFORMATION_SCHEMA)(.*?)$");
private static final Pattern MATCH_ALL = Pattern.compile("^(.*?)$");
private static final String REPLACEMENT = "%s$0".formatted(TABLE_PREFIX); //
private final SQLDialect dialect;
/**
* Instantiates a new Jooq context.
*
* @param dialect the getSQLDialect
*/
public JooqContext(SQLDialect dialect) {
this.dialect = dialect;
}
/**
* Create DSL Context.
*
* @param connection the connection
* @return the dsl context
*/
public DSLContext createContext(Connection connection) {
record SimpleConnectionProvider(Connection connection) implements ConnectionProvider {
@Override
public Connection acquire() throws DataAccessException {
return connection;
}
@Override
public void release(Connection connection) throws DataAccessException {
}
}
return createWith(new SimpleConnectionProvider(connection));
}
/**
* Applies default configuration
*
* @param connectionProvider A connection lifecycle handler API.
* @return DSLContext
*/
private DSLContext createWith(ConnectionProvider connectionProvider) {
return new DefaultConfiguration()
.set(connectionProvider)
.set(dialect)
.set(createSettings())
.set(new ExecuteListenerProvider[0])
.dsl();
}
/**
* Returns base settings for DSL Contexts.
*
* @return Settings
*/
private Settings createSettings() {
return new Settings()
.withBackslashEscaping(BackslashEscaping.OFF)
.withRenderSchema(false)
.withRenderMapping(new RenderMapping() // Support the tables having custom prefix
.withSchemata(new MappedSchema()
.withInputExpression(MATCH_ALL_EXCEPT_INFORMATION_SCHEMA)
.withTables(new MappedTable()
.withInputExpression(MATCH_ALL)
.withOutput(REPLACEMENT)
)
)
)
.withRenderQuotedNames(RenderQuotedNames.ALWAYS)
.withRenderNameCase(RenderNameCase.LOWER);
}
}
@@ -0,0 +1,8 @@
package com.github.alathra.alathranwars.enums;
public enum CaptureProgressDirection {
UP,
CONTESTED,
UNCONTESTED,
DOWN
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.enums;
public enum CommandArgsSiege {
IN_SIEGE,
OUT_SIEGE,
ALL_SIEGES,
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.enums;
public enum CommandArgsWar {
IN_WAR,
OUT_WAR,
ALL_WARS,
}
@@ -0,0 +1,5 @@
package com.github.alathra.alathranwars.enums;
public enum ConflictType {
WAR
}
@@ -0,0 +1,6 @@
package com.github.alathra.alathranwars.enums;
public enum WarDeleteReason {
DRAW,
DEFEAT,
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.enums.battle;
public enum BattleSide {
ATTACKER,
DEFENDER,
SPECTATOR,
}
@@ -0,0 +1,6 @@
package com.github.alathra.alathranwars.enums.battle;
public enum BattleTeam {
SIDE_1,
SIDE_2,
}
@@ -0,0 +1,6 @@
package com.github.alathra.alathranwars.enums.battle;
public enum BattleType {
SIEGE,
RAID,
}
@@ -0,0 +1,7 @@
package com.github.alathra.alathranwars.enums.battle;
public enum BattleVictor {
ATTACKER,
DEFENDER,
DRAW,
}
@@ -0,0 +1,8 @@
package com.github.alathra.alathranwars.enums.battle;
public enum BattleVictoryReason {
OPPONENT_LOST,
OPPONENT_RETREAT,
ADMIN_COMMAND,
ADMIN_CANCEL,
}
@@ -0,0 +1,52 @@
package com.github.alathra.alathranwars.events;
import com.github.alathra.alathranwars.conflict.war.War;
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;
private War war;
public PreWarCreateEvent(War war) {
this.war = war;
}
/**
* 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;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
}
@@ -0,0 +1,59 @@
package com.github.alathra.alathranwars.events;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.WarDeleteReason;
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;
private War war;
private WarDeleteReason reason;
public PreWarDeleteEvent(War war, WarDeleteReason reason) {
this.war = war;
this.reason = reason;
}
/**
* 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;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public WarDeleteReason getReason() {
return reason;
}
}
@@ -0,0 +1,28 @@
package com.github.alathra.alathranwars.events;
import com.github.alathra.alathranwars.conflict.war.War;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class WarCreateEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private War war;
public WarCreateEvent(War war) {
this.war = war;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
}
@@ -0,0 +1,35 @@
package com.github.alathra.alathranwars.events;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.WarDeleteReason;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class WarDeleteEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private War war;
private WarDeleteReason reason;
public WarDeleteEvent(War war, WarDeleteReason reason) {
this.war = war;
this.reason = reason;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public WarDeleteReason getReason() {
return reason;
}
}
@@ -0,0 +1,49 @@
package com.github.alathra.alathranwars.events.battle;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.battle.BattleVictor;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class BattleResultEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private final War war;
private final Battle battle;
private final BattleVictor battleVictor;
private final BattleVictoryReason battleVictoryReason;
public BattleResultEvent(War war, Battle battle, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
this.war = war;
this.battle = battle;
this.battleVictor = battleVictor;
this.battleVictoryReason = battleVictoryReason;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public Battle getBattle() {
return battle;
}
public BattleVictor getBattleVictor() {
return battleVictor;
}
public BattleVictoryReason getBattleVictoryReason() {
return battleVictoryReason;
}
}
@@ -0,0 +1,35 @@
package com.github.alathra.alathranwars.events.battle;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class BattleStartEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
private final War war;
private final Battle battle;
public BattleStartEvent(War war, Battle battle) {
this.war = war;
this.battle = battle;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public Battle getBattle() {
return battle;
}
}
@@ -0,0 +1,80 @@
package com.github.alathra.alathranwars.events.battle;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.battle.BattleType;
import com.github.alathra.alathranwars.enums.battle.BattleVictor;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class PreBattleResultEvent extends Event implements Cancellable {
private static final HandlerList HANDLER_LIST = new HandlerList();
private boolean cancelled;
private War war;
private final Battle battle;
private final BattleType battleType;
private final BattleVictor battleVictor;
private final BattleVictoryReason battleVictoryReason;
public PreBattleResultEvent(War war, Battle battle, BattleType battleType, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
this.war = war;
this.battle = battle;
this.battleType = battleType;
this.battleVictor = battleVictor;
this.battleVictoryReason = battleVictoryReason;
}
/**
* 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;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public Battle getBattle() {
return battle;
}
public BattleType getBattleType() {
return battleType;
}
public BattleVictor getBattleVictor() {
return battleVictor;
}
public BattleVictoryReason getBattleVictoryReason() {
return battleVictoryReason;
}
}
@@ -0,0 +1,66 @@
package com.github.alathra.alathranwars.events.battle;
import com.github.alathra.alathranwars.conflict.battle.Battle;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.enums.battle.BattleType;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class PreBattleStartEvent extends Event implements Cancellable {
private static final HandlerList HANDLER_LIST = new HandlerList();
private boolean cancelled;
private War war;
private final Battle battle;
private final BattleType battleType;
public PreBattleStartEvent(War war, Battle battle, BattleType battleType) {
this.war = war;
this.battle = battle;
this.battleType = battleType;
}
/**
* 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;
}
public static HandlerList getHandlerList() {
return HANDLER_LIST;
}
public War getWar() {
return war;
}
public Battle getBattle() {
return battle;
}
public BattleType getBattleType() {
return battleType;
}
}
@@ -0,0 +1,20 @@
package com.github.alathra.alathranwars.hooks;
import com.github.alathra.alathranwars.Reloadable;
public class HookManager implements Reloadable {
private final PAPIHook papi = new PAPIHook();
public void onLoad() {
papi.onLoad();
}
public void onEnable() {
TownyHook.init();
papi.onEnable();
}
public void onDisable() {
papi.onDisable();
}
}
@@ -0,0 +1,68 @@
package com.github.alathra.alathranwars.hooks;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.utility.Logger;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class NameColorHandler {
private static NameColorHandler instance;
private Map<Player, String> playerColor = new HashMap<>();
private Map<Player, String> playerInitial = new HashMap<>();
private NameColorHandler() {
if (instance != null)
Logger.get().warn("Tried to re-initialize singleton");
}
@NotNull
public static NameColorHandler getInstance() {
if (instance == null)
instance = new NameColorHandler();
return instance;
}
public void calculatePlayerColors(Player p) {
if (!WarController.getInstance().isPlayerInAnyWars(p)) {
playerColor.remove(p);
playerInitial.remove(p);
return;
}
Optional<War> war = WarController.getInstance().getPlayerWars(p).stream().findFirst();
if (war.isEmpty())
return;
final boolean isPlayerSurrendered = war.get().getSide1().isPlayerSurrendered(p) || war.get().getSide2().isPlayerSurrendered(p);
if (isPlayerSurrendered)
return;
final boolean isSideOne = war.get().getSide1().isPlayerOnSide(p);
if (isSideOne) {
playerColor.put(p, "<red>");
} else {
playerColor.put(p, "<blue>");
}
playerInitial.put(p, war.get().getPlayerSide(p).getName().substring(0, 1).toUpperCase());
}
public boolean isPlayerUsingModifiedName(Player p) {
calculatePlayerColors(p);
return WarController.getInstance().isPlayerInAnyWars(p);
}
public String getPlayerTabNameColor(Player p) {
return "%s[%s] ".formatted(playerColor.get(p), playerInitial.get(p));
}
public String getPlayerNameColor(Player p) {
return "%s".formatted(playerColor.get(p));
}
}
@@ -0,0 +1,71 @@
package com.github.alathra.alathranwars.hooks;
import com.github.alathra.alathranwars.AlathranWars;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PAPIExpansion extends PlaceholderExpansion {
private final AlathranWars plugin;
private final NameColorHandler colorHandler;
public PAPIExpansion(AlathranWars plugin, NameColorHandler colorHandler) {
this.plugin = plugin;
this.colorHandler = colorHandler;
}
@Override
public @Nullable String getRequiredPlugin() {
return "AlathranWars";
}
@Override
public @NotNull String getIdentifier() {
return "alathranwars";
}
@Override
public @NotNull String getAuthor() {
return String.join(", ", plugin.getPluginMeta().getAuthors());
}
@Override
public @NotNull String getVersion() {
return plugin.getPluginMeta().getVersion();
}
@Override
public boolean persist() {
return true;
}
@Override
public @Nullable String onPlaceholderRequest(Player p, @NotNull String params) {
if (params.equals("player_tablist")) {
if (colorHandler.isPlayerUsingModifiedName(p))
return colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
return "%essentials_nickname%";
}
if (params.equals("player_nametag")) {
if (colorHandler.isPlayerUsingModifiedName(p))
return colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
return "%essentials_nickname%";
}
if (params.equals("player_tablist_maquillage")) {
if (colorHandler.isPlayerUsingModifiedName(p))
return colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
return "%maquillage_namecolor_essentialsnick%";
}
if (params.equals("player_nametag_maquillage")) {
if (colorHandler.isPlayerUsingModifiedName(p))
return colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
return "%maquillage_namecolor_essentialsnick%";
}
return null;
}
}
@@ -0,0 +1,27 @@
package com.github.alathra.alathranwars.hooks;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.Reloadable;
import org.bukkit.Bukkit;
public class PAPIHook implements Reloadable {
private PAPIExpansion papiExpansion;
@Override
public void onLoad() {
}
@Override
public void onEnable() {
if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
papiExpansion = new PAPIExpansion(AlathranWars.getInstance(), NameColorHandler.getInstance());
papiExpansion.register();
}
}
@Override
public void onDisable() {
if (papiExpansion != null && papiExpansion.isRegistered())
papiExpansion.unregister();
}
}
@@ -0,0 +1,29 @@
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 javax.inject.Singleton;
import java.util.List;
@Singleton
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,88 @@
package com.github.alathra.alathranwars.items;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.items.item.RamItem;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
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 = AlathranWars.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;
// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars items.");
itemRegistry.put(registryName("ram"), new RamItem());
//THIS BREAKS EVERYTHING???? TODO
// Bukkit.getServer().addRecipe(new RamItem().getRecipe());
// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars items.");
}
public static WarItemRegistry getInstance() {
return instance;
}
/**
* generate a registry name
*
* @param item
* @return
*/
public static @NotNull String registryName(String item) {
return namespace + ":" + item;
}
public @NotNull 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,59 @@
package com.github.alathra.alathranwars.items;
import org.bukkit.inventory.Recipe;
import org.jetbrains.annotations.NotNull;
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;
// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars recipes.");
// register(WarItemRegistry.registryName("ram"), new RamItem().getRecipes());
// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars recipes.");
}
public static WarRecipeRegistry getInstance() {
return instance;
}
public void register(String name, @NotNull Set<Recipe> recipes) {
for (Recipe recipe : recipes) {
// Bukkit.getServer().addRecipe(recipe);
recipeRegistry.put(name, recipe);
}
}
public @NotNull 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,50 @@
package com.github.alathra.alathranwars.items.item;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.items.IWarItem;
import com.github.alathra.alathranwars.items.WarItemRegistry;
import com.github.milkdrinkers.colorparser.ColorParser;
import net.kyori.adventure.text.Component;
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 org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
public class RamItem implements IWarItem {
public @NotNull ItemStack getItemStack() {
@NotNull ItemStack ram = new ItemStack(Material.WOODEN_HOE);
ItemMeta meta = ram.getItemMeta();
meta.displayName(ColorParser.of("Door Ram").build());
@NotNull ArrayList<Component> lore = new ArrayList<>();
meta.lore(lore);
meta.setCustomModelData(14700);
ram.setItemMeta(meta);
return ram;
}
@Override
public @NotNull Recipe getRecipe() {
@Nullable ItemStack output = WarItemRegistry.getInstance().getOrNull("ram");
@NotNull NamespacedKey key = new NamespacedKey(AlathranWars.getInstance(), "ram");
@NotNull 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,240 @@
package com.github.alathra.alathranwars.listeners;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.utility.Utils;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.jetbrains.annotations.NotNull;
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"
};
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[]{
"homes",
"wild", "rtp", "wilderness", "wildtp",
"tpa", "tpahere", "tpaccept", "tpacancel",
"etpa", "etpahere", "etpaccept", "etpacancel",
"ehomes"
};
@EventHandler
public void onCommandSend(final @NotNull PlayerCommandPreprocessEvent event) {
@NotNull Player p = event.getPlayer();
//if player is admin, ignore this behavior
// if (p.hasPermission("!AlathranWars.admin")) return;
String @NotNull [] 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 : WarController.getInstance().getPlayerSieges(p)) {
//payment check
if (args.length >= 2) {
//parse what we have, remove the starting sslash
@NotNull String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
for (@NotNull String prefix : PREFIXES_TOWNY) {
for (String cmd : PAYMENT) {
//check for each prefix
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<red>You cannot withdraw money whilst in a siege!").parseLegacy().build());
event.setCancelled(true);
return;
}
}
}
}
if (Utils.isOnSiegeBattlefield(p, siege)) {
//set spawn and properties
if (args.length >= 3) {
@NotNull String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1] + " " + args[2];
for (@NotNull String prefix : PREFIXES_TOWNY) {
//payment check
for (String cmd : BLACKLISTED_X_LONG) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<red>You cannot modify this property during a siege!").parseLegacy().build());
event.setCancelled(true);
return;
}
}
}
}
//n spawn and t spawn
if (args.length >= 2) {
//parse what we have, remove the starting sslash
@NotNull String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
for (@NotNull String prefix : PREFIXES_TOWNY) {
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(ColorParser.of(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
return;
}
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<yellow>Use /t spawn, or /n spawn").parseLegacy().build());
event.setCancelled(true);
return;
}
//else
p.sendMessage(ColorParser.of(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
@NotNull String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0];
for (@NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<yellow>You are stuck in spawn and are allowed to teleport to your town or nation.").parseLegacy().build());
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<yellow>Use /t spawn, or /n spawn").parseLegacy().build());
event.setCancelled(true);
return;
}
p.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<red>You cannot teleport whilst in a oldSiege!").parseLegacy().build());
event.setCancelled(true);
return;
}
}
}
}
}
}
}
}
@@ -0,0 +1,58 @@
package com.github.alathra.alathranwars.listeners;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.Reloadable;
import com.github.alathra.alathranwars.listeners.items.PlayerInteractListener;
import com.github.alathra.alathranwars.listeners.siege.*;
import com.github.alathra.alathranwars.listeners.war.NationListener;
import com.github.alathra.alathranwars.listeners.war.PlayerJoinListener;
import com.github.alathra.alathranwars.listeners.war.TownListener;
import org.bukkit.Bukkit;
/**
* A class to handle registration of event listeners.
*/
public class ListenerHandler implements Reloadable {
private final AlathranWars instance;
public ListenerHandler(AlathranWars instance) {
this.instance = instance;
}
@Override
public void onLoad() {
}
@Override
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);
if (Bukkit.getServer().getPluginManager().isPluginEnabled("Graves"))
instance.getServer().getPluginManager().registerEvents(new PlayerGraveListener(), instance);
if (Bukkit.getServer().getPluginManager().isPluginEnabled("HeadsPlus"))
instance.getServer().getPluginManager().registerEvents(new PlayerHeadsPlusListener(), instance);
if (Bukkit.getServer().getPluginManager().isPluginEnabled("GSit"))
instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance);
instance.getServer().getPluginManager().registerEvents(new ItemUseListener(), instance);
instance.getServer().getPluginManager().registerEvents(new PlayerDamageEntityListener(), instance);
// Battles
instance.getServer().getPluginManager().registerEvents(new SiegeListener(), instance);
// Wars
instance.getServer().getPluginManager().registerEvents(new NationListener(), 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 CommandsListener(), instance);
instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance);
}
@Override
public void onDisable() {
}
}
@@ -0,0 +1,189 @@
package com.github.alathra.alathranwars.listeners.items;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.WarController;
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.object.TownBlock;
import com.palmergames.bukkit.towny.object.WorldCoord;
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 org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
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 final @NotNull Map<Location, Long> brokenDoors = new HashMap<>();
/**
* @param event event
* @author DunnoConz
* @author AubriTheHuman
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(final @NotNull PlayerInteractEvent event) {
@NotNull Player player = event.getPlayer();
@NotNull Action action = event.getAction();
if (action == Action.LEFT_CLICK_BLOCK) {
@Nullable Block clicked = event.getClickedBlock();
@NotNull ItemStack item = player.getInventory().getItemInMainHand();
if (clicked != null) {
if (doors.contains(clicked.getType())) { // left click + any door types
@NotNull Door door = (Door) clicked.getBlockData();
// lock door in the opposite position
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
boolean inSiegeOrRaid = false;
//siege check
for (@NotNull Siege s : WarController.getInstance().getSieges()) {
for (@NotNull 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(ColorParser.of(UtilsChat.getPrefix() + "<red>The door is already broken!").parseLegacy().build());
event.setCancelled(true);
return;
}
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<yellow>Break it down alright!").parseLegacy().build());
brokenDoors.put(getDoorPos(clicked, door), System.currentTimeMillis() + (1000L * AlathranWars.getInstance().getConfig().getInt("batteringRamEffectiveness")));
door.setOpen(!door.isOpen());
clicked.setBlockData(door);
player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount() - 1);
} else {
player.sendMessage(ColorParser.of(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 @NotNull PlayerItemDamageEvent event) {
@NotNull 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 @NotNull PlayerInteractEvent event) {
@NotNull Player player = event.getPlayer();
@NotNull Action action = event.getAction();
@Nullable Block clicked = event.getClickedBlock();
@NotNull ItemStack item = player.getInventory().getItemInMainHand();
if (action == Action.RIGHT_CLICK_BLOCK) {
if (clicked != null) {
if (doors.contains(clicked.getType())) {
@NotNull Door door = (Door) clicked.getBlockData();
if (doorBroken(clicked, door)) {
player.sendMessage(ColorParser.of(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 @NotNull Location getDoorPos(@NotNull Block clicked, @NotNull 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, @NotNull 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;
}
}
@@ -0,0 +1,157 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import com.github.alathra.alathranwars.utility.Utils;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.event.actions.TownyBuildEvent;
import com.palmergames.bukkit.towny.event.actions.TownyDestroyEvent;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.Set;
public class BlockBreakPlaceListener implements Listener {
private final static Set<Material> DESTROY_SPECIFIC = Set.of(
// Mortar & Cannons
Material.IRON_BLOCK,
Material.HEAVY_WEIGHTED_PRESSURE_PLATE,
Material.TORCH,
Material.STONE_BUTTON,
Material.BLACK_WOOL
);
private final static Set<Material> DESTROY_GLOBAL = Set.of(
Material.TNT,
// Beds
Material.WHITE_BED,
Material.YELLOW_BED,
Material.BLACK_BED,
Material.BLUE_BED,
Material.BROWN_BED,
Material.CYAN_BED,
Material.GRAY_BED,
Material.GREEN_BED,
Material.LIGHT_BLUE_BED,
Material.LIGHT_GRAY_BED,
Material.LIME_BED,
Material.MAGENTA_BED,
Material.ORANGE_BED,
Material.PINK_BED,
Material.PURPLE_BED,
Material.RED_BED,
// Siege engines
Material.ARMOR_STAND
);
private final static Set<Material> PLACE_NEUTRAL = Set.of(
// Mortar & Cannons
Material.IRON_BLOCK,
Material.HEAVY_WEIGHTED_PRESSURE_PLATE,
Material.TORCH,
Material.STONE_BUTTON,
Material.BLACK_WOOL,
// Siege engines
Material.CARVED_PUMPKIN
);
private final static Set<Material> PLACE_OWNED = Set.of(
// Beds
Material.WHITE_BED,
Material.YELLOW_BED,
Material.BLACK_BED,
Material.BLUE_BED,
Material.BROWN_BED,
Material.CYAN_BED,
Material.GRAY_BED,
Material.GREEN_BED,
Material.LIGHT_BLUE_BED,
Material.LIGHT_GRAY_BED,
Material.LIME_BED,
Material.MAGENTA_BED,
Material.ORANGE_BED,
Material.PINK_BED,
Material.PURPLE_BED,
Material.RED_BED
);
private final static Set<Material> PLACE_GLOBAL = Set.of(
Material.TNT
);
@EventHandler
public void onBlockBreak(TownyDestroyEvent e) {
Siege siege = Utils.getClosestSiege(e.getPlayer(), true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(e.getPlayer(), siege)) return;
final boolean isInsideTownClaims = e.hasTownBlock();
final boolean isDefender = siege.getPlayerSideInSiege(e.getPlayer()).equals(BattleSide.DEFENDER);
// Allow destroying beds anywhere
if (DESTROY_GLOBAL.contains(e.getMaterial())) {
e.setCancelled(false);
return;
}
// Allow destroying outside claims
if (
((isDefender || !isInsideTownClaims) && DESTROY_SPECIFIC.contains(e.getMaterial()))
) {
e.setCancelled(false);
return;
}
if (e.getPlayer().hasPermission("AlathranWars.break")) {
e.setCancelled(false);
return;
}
e.setCancelled(true);
e.setCancelMessage("");
e.getPlayer().sendMessage(ColorParser.of("<red>You can not break blocks during sieges.").build());
}
@EventHandler
public void onBlockPlace(TownyBuildEvent e) {
Siege siege = Utils.getClosestSiege(e.getPlayer(), true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(e.getPlayer(), siege)) return;
final boolean isInsideClaims = e.hasTownBlock();
final boolean isDefender = siege.getPlayerSideInSiege(e.getPlayer()).equals(BattleSide.DEFENDER);
final boolean isDefenderAllowed = (!isInsideClaims || !e.getTownBlock().isOutpost()) && isDefender; // Defenders can build on the battlefield and in towns
final boolean isAttackerAllowed = (!isInsideClaims || e.getTownBlock().isOutpost()) && !isDefender; // Attackers can build on the battlefield and in outposts
// Allow placing outside claims and in claims your side owns
if ((isAttackerAllowed || isDefenderAllowed) && PLACE_NEUTRAL.contains(e.getMaterial())) {
e.setCancelled(false);
return;
}
// Allow placing beds in claims your side owns
if (isInsideClaims && (isAttackerAllowed || isDefenderAllowed) && PLACE_OWNED.contains(e.getMaterial())) {
e.setCancelled(false);
return;
}
// Allow placing everywhere
if (PLACE_GLOBAL.contains(e.getMaterial())) {
e.setCancelled(false);
return;
}
if (e.getPlayer().hasPermission("AlathranWars.place")) {
e.setCancelled(false);
return;
}
e.setCancelled(true);
e.setCancelMessage("");
e.getPlayer().sendMessage(ColorParser.of("<red>You can not place blocks during sieges.").build());
}
}
@@ -0,0 +1,28 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import com.palmergames.bukkit.towny.event.actions.TownyItemuseEvent;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class ItemUseListener implements Listener {
/**
* Prevent using ender pearls in a combat zone.
*
* @param e the e
*/
@EventHandler
public void onEnderPearl(TownyItemuseEvent e) {
Siege siege = Utils.getClosestSiege(e.getPlayer(), true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(e.getPlayer(), siege)) return;
if (!e.getMaterial().equals(Material.ENDER_PEARL)) return;
e.setCancelMessage("You cannot throw ender pearls during a siege!");
e.setCancelled(true);
}
}
@@ -0,0 +1,42 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import com.palmergames.bukkit.towny.event.damage.TownyPlayerDamageEntityEvent;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.Arrays;
import java.util.List;
public class PlayerDamageEntityListener implements Listener {
private final List<EntityType> typeWhitelist = Arrays.asList(
EntityType.PLAYER,
EntityType.HORSE,
EntityType.DONKEY,
EntityType.PIG,
EntityType.BOAT,
EntityType.MINECART,
EntityType.MINECART_TNT
);
/**
* Always allow damaging certain entities withing the siege zone (mounts and dogs)
*
* @param e the e
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamage(TownyPlayerDamageEntityEvent e) {
Siege siege = Utils.getClosestSiege(e.getAttackingPlayer(), true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(e.getAttackingPlayer(), siege)) return;
EntityType type = e.getEntity().getType();
if (typeWhitelist.contains(type)) {
e.setCancelled(false); // Force un-cancel event
}
}
}
@@ -0,0 +1,118 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import com.palmergames.bukkit.towny.event.deathprice.NationPaysDeathPriceEvent;
import com.palmergames.bukkit.towny.event.deathprice.PlayerPaysDeathPriceEvent;
import com.palmergames.bukkit.towny.event.deathprice.TownPaysDeathPriceEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
public class PlayerDeathListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(PlayerPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
if (p == null) return;
Siege siege = Utils.getClosestSiege(p, true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(p, siege)) return;
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(TownPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
if (p == null) return;
Siege siege = Utils.getClosestSiege(p, true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(p, siege)) return;
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(NationPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
if (p == null) return;
Siege siege = Utils.getClosestSiege(p, true);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(p, siege)) return;
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
private void onPlayerDeath(PlayerDeathEvent e) {
Player victim = e.getPlayer();
Player attacker = e.getPlayer().getKiller();
if (attacker == null) return;
Siege siege = Utils.getClosestSiege(victim, false);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(victim, siege)) return;
if (siege.isPlayerInSiege(victim) && siege.isPlayerInSiege(attacker)) {
siegeKill(e);
} else {
oocKill(e);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
private void onPlayerSuicide(PlayerDeathEvent e) {
Player victim = e.getPlayer();
Player attacker = e.getPlayer().getKiller();
if (attacker != null) return;
Siege siege = Utils.getClosestSiege(victim, false);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(victim, siege)) return;
if (siege.isPlayerInSiege(victim)) {
siegeKill(e);
} else {
oocKill(e);
}
}
/**
* Damage all gear held by the player (and then send them to spawn?)
* They don't lose items from death.
*
* @param e event
*/
private void siegeKill(PlayerDeathEvent e) {
// Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "spawn " + victim.getName()); // TODO Re enable?
// Utils.damageAllGear(e.getPlayer());
e.setKeepInventory(true);
e.getDrops().clear();
e.setKeepLevel(true);
e.setDroppedExp(0);
}
/**
* Dont damage items held by the player
* They don't lose items from death.
*
* @param e event
*/
private void oocKill(PlayerDeathEvent e) {
// Bukkit.dispatchCommand((CommandSender)Bukkit.getConsoleSender(), "spawn " + victim.getName()); // TODO Re enable?
e.setKeepInventory(true);
e.getDrops().clear();
e.setKeepLevel(true);
e.setDroppedExp(0);
}
}
@@ -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,26 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import com.ranull.graves.event.GraveCreateEvent;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class PlayerGraveListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
private void onGraveCreate(GraveCreateEvent e) {
if (!e.getEntityType().equals(EntityType.PLAYER)) return;
if (!(e.getEntity() instanceof Player p)) return;
Siege siege = Utils.getClosestSiege(p, false);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(p, siege)) return;
e.setCancelled(true);
}
}
@@ -0,0 +1,19 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import io.github.thatsmusic99.headsplus.api.events.PlayerHeadDropEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class PlayerHeadsPlusListener implements Listener {
@EventHandler
private void onHeadDrop(PlayerHeadDropEvent e) {
Siege siege = Utils.getClosestSiege(e.getDeadPlayer(), false);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(e.getDeadPlayer(), siege)) return;
e.setCancelled(true);
}
}
@@ -0,0 +1,23 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.jetbrains.annotations.NotNull;
public class PlayerJoinListener implements Listener {
@EventHandler
private void onPlayerJoin(@NotNull PlayerJoinEvent e) {
final @NotNull Player p = e.getPlayer();
if (WarController.getInstance().isPlayerInAnySiege(p)) {
for (@NotNull Siege siege : WarController.getInstance().getPlayerSieges(p)) {
final @NotNull BattleSide side = siege.getPlayerSideInSiege(p);
siege.addOnlinePlayer(p, side);
}
}
}
}
@@ -0,0 +1,23 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.enums.battle.BattleSide;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
public class PlayerQuitListener implements Listener {
@EventHandler
private void onPlayerQuit(@NotNull PlayerQuitEvent e) {
final @NotNull Player p = e.getPlayer();
if (WarController.getInstance().isPlayerInAnySiege(p)) {
for (@NotNull Siege siege : WarController.getInstance().getPlayerSieges(p)) {
final @NotNull BattleSide side = siege.getPlayerSideInSiege(p);
siege.removeOnlinePlayer(p, side);
}
}
}
}
@@ -0,0 +1,23 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.utility.Utils;
import dev.geco.gsit.api.event.PreEntitySitEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class PlayerSitListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
public void onSit(PreEntitySitEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
Siege siege = Utils.getClosestSiege(p, false);
if (siege == null) return;
if (!Utils.isOnSiegeBattlefield(p, siege)) return;
e.setCancelled(true);
}
}
@@ -0,0 +1,260 @@
package com.github.alathra.alathranwars.listeners.siege;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.enums.battle.BattleType;
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
import com.github.alathra.alathranwars.events.battle.BattleStartEvent;
import com.github.alathra.alathranwars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.object.Town;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.title.Title;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.time.Duration;
import java.util.List;
import java.util.Random;
public class SiegeListener implements Listener {
private final static Title.Times TITLE_TIMES = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
private final static Sound SOUND_VICTORY = Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, 1.0F);
private final static Sound SOUND_DEFEAT = Sound.sound(Key.key("entity.wither.death"), Sound.Source.VOICE, 0.5f, 1.0F);
private final static List<Sound> SOUND_GOATHORNS = List.of(
Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
);
/**
* On battle start UI handling.
*
* @param e event
*/
@EventHandler(priority = EventPriority.LOW)
public void onBattleStart(BattleStartEvent e) {
if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
if (!(e.getBattle() instanceof Siege siege)) return;
final Title defTitle = Title.title(
ColorParser.of("<red><u><b><town>")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
ColorParser.of("<gray><i>Is under siege, defend!")
.build(),
TITLE_TIMES
);
final Title attTitle = Title.title(
ColorParser.of("<red><u><b><town>")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
ColorParser.of("<gray><i>Has been put to siege, attack!")
.build(),
TITLE_TIMES
);
siege.getDefenderPlayers().forEach(player -> {
player.showTitle(defTitle);
player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
});
siege.getAttackerPlayers().forEach(player -> {
player.showTitle(attTitle);
player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
});
}
/**
* On battle end UI handling.
*
* @param e event
*/
@EventHandler(priority = EventPriority.LOW)
public void onBattleResult(BattleResultEvent e) {
if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
if (!(e.getBattle() instanceof Siege siege)) return;
switch (e.getBattleVictor()) {
case ATTACKER -> {
if (e.getBattleVictoryReason().equals(BattleVictoryReason.OPPONENT_RETREAT)) {
Bukkit.broadcast(
ColorParser.of("<prefix>The town of <town> has surrendered.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build()
);
} else {
Bukkit.broadcast(ColorParser.of("<prefix>The town of <town> has been sacked and placed under occupation by the armies of <attacker>!")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.parseMinimessagePlaceholder("attacker", siege.getAttackerSide().getName())
.build());
}
final Title vicAttackTitle = Title.title(
ColorParser.of("<green><u><b>Victory")
.build(),
ColorParser.of("<gray><i><town> has been captured!")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
TITLE_TIMES
);
final Title losAttackTitle = Title.title(
ColorParser.of("<red><u><b>Defeat")
.build(),
ColorParser.of("<gray><i><town> has been lost!")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
TITLE_TIMES
);
siege.getAttackers().forEach(player -> {
player.showTitle(vicAttackTitle);
player.playSound(SOUND_VICTORY);
});
siege.getDefenders().forEach(player -> {
player.showTitle(losAttackTitle);
player.playSound(SOUND_DEFEAT);
});
}
case DEFENDER -> {
if (e.getBattleVictoryReason().equals(BattleVictoryReason.OPPONENT_RETREAT)) {
Bukkit.broadcast(
ColorParser.of("<prefix>The siege at <town> has been abandoned by the attackers.")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build()
);
} else {
Bukkit.broadcast(
ColorParser.of("<prefix>The siege of <town> has been lifted by the defenders!")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build()
);
}
final Title vicDefendTitle = Title.title(
ColorParser.of("<red><u><b>Defeat")
.build(),
ColorParser.of("<gray><i>We failed to capture <town>!")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
TITLE_TIMES
);
final Title losDefendTitle = Title.title(
ColorParser.of("<green><u><b>Victory")
.build(),
ColorParser.of("<gray><i><town> has been made safe!")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
TITLE_TIMES
);
siege.getAttackers().forEach(player -> {
player.showTitle(vicDefendTitle);
player.playSound(SOUND_DEFEAT);
});
siege.getDefenders().forEach(player -> {
player.showTitle(losDefendTitle);
player.playSound(SOUND_VICTORY);
});
}
case DRAW -> {
Bukkit.broadcast(
ColorParser.of("<prefix>The siege of <town> has ended in a draw!")
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build()
);
final Title drawTitle = Title.title(
ColorParser.of("<yellow><u><b>Draw")
.build(),
ColorParser.of("<gray><i>The siege at <town> has ended!")
.parseMinimessagePlaceholder("town", siege.getTown().getName())
.build(),
TITLE_TIMES
);
siege.getAttackers().forEach(player -> {
player.showTitle(drawTitle);
player.playSound(SOUND_DEFEAT);
});
siege.getDefenders().forEach(player -> {
player.showTitle(drawTitle);
player.playSound(SOUND_DEFEAT);
});
}
}
}
/**
* On battle end handle occupation results.
*
* @param e event
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleResultOccupy(BattleResultEvent e) {
if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
if (!(e.getBattle() instanceof Siege siege)) return;
switch (e.getBattleVictor()) {
case ATTACKER -> {
War war = e.getWar();
if (war.isEventWar()) return;
Town town = siege.getTown();
Side townSide = war.getTownSide(town);
if (townSide == null) return;
final boolean isLiberation = siege.getAttackerSide().equals(townSide); // Is the town being liberated or occupied
if (isLiberation) { // Liberation siege
if (townSide.isTownSurrendered(town)) {
war.unsurrenderTown(town);
}
} else { // Occupation siege
if (!townSide.isTownSurrendered(town)) {
war.surrenderTown(town);
}
}
}
case DEFENDER, DRAW -> {
}
}
}
/**
* On battle end handle war score distribution.
*
* @param e event
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onBattleResultWarScore(BattleResultEvent e) {
if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
if (!(e.getBattle() instanceof Siege siege)) return;
switch (e.getBattleVictor()) {
case ATTACKER -> {
siege.getAttackerSide().addScore(50);
siege.getDefenderSide().addScore(5);
}
case DEFENDER -> {
siege.getDefenderSide().addScore(10);
}
case DRAW -> {
}
}
}
}
@@ -0,0 +1,78 @@
package com.github.alathra.alathranwars.listeners.war;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import com.palmergames.bukkit.towny.event.NationAddTownEvent;
import com.palmergames.bukkit.towny.event.NationPreRenameEvent;
import com.palmergames.bukkit.towny.event.nation.NationPreMergeEvent;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class NationListener implements Listener {
/*@EventHandler
private void onNationKingChange(NationKingChangeEvent e) {
e.setCancelMessage("");
e.setCancelled(true);
}*/
@EventHandler
private void onRename(NationPreRenameEvent e) {
Nation nation = e.getNation();
if (WarController.getInstance().isNationInAnyWars(nation)) {
e.setCancelMessage("You can't rename a nation while it's in a war.");
e.setCancelled(true);
}
}
@EventHandler
private void onTownJoin(NationAddTownEvent e) {
Nation nation = e.getNation();
Town town = e.getTown();
// Add town to all nation wars
for (War war : WarController.getInstance().getNationWars(nation)) {
Side side = war.getNationSide(nation);
if (side == null) continue;
side.addTown(town);
}
// TODO Add nation to towns' wars
for (War war : WarController.getInstance().getTownWars(town)) {
Side side = war.getTownSide(town);
if (side == null) continue;
side.addNation(nation);
}
for (War war : WarController.getInstance().getNationWars(nation)) {
Side side = war.getNationSide(nation);
if (side == null) continue;
side.getPlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
}
}
/*@EventHandler // Do nothing, leaving a nation should not let you escape nation wars
private void onTownLeave(NationTownLeaveEvent e) {
}*/
@EventHandler
private void onMerge(NationPreMergeEvent e) {
Nation nation = e.getRemainingNation();
Nation nation1 = e.getNation();
if (WarController.getInstance().isNationInAnyWars(nation) || WarController.getInstance().isNationInAnyWars(nation1)) {
e.setCancelMessage("You can't merge nations while they are in a war.");
e.setCancelled(true);
}
// TODO Allow merging nations in war, literally just ensure that towns are added to sieges and sides
}
}
@@ -0,0 +1,30 @@
package com.github.alathra.alathranwars.listeners.war;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PlayerJoinListener implements Listener {
@EventHandler
private void onPlayerJoin(@NotNull PlayerJoinEvent e) {
final @NotNull Player p = e.getPlayer();
if (WarController.getInstance().isPlayerInAnyWars(p)) {
for (@NotNull War war : WarController.getInstance().getWars()) {
if (war.isPlayerInWar(p)) {
@Nullable Side side = war.getPlayerSide(p);
if (side != null) {
side.addOnlinePlayer(p);
}
}
}
}
NameColorHandler.getInstance().calculatePlayerColors(p);
}
}
@@ -0,0 +1,30 @@
package com.github.alathra.alathranwars.listeners.war;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PlayerQuitListener implements Listener {
@EventHandler
private void onPlayerQuit(@NotNull PlayerQuitEvent e) {
final @NotNull Player p = e.getPlayer();
if (WarController.getInstance().isPlayerInAnyWars(p)) {
for (@NotNull War war : WarController.getInstance().getWars()) {
if (war.isPlayerInWar(p)) {
@Nullable Side side = war.getPlayerSide(p);
if (side != null) {
side.removeOnlinePlayer(p);
}
}
}
}
NameColorHandler.getInstance().calculatePlayerColors(p);
}
}
@@ -0,0 +1,144 @@
package com.github.alathra.alathranwars.listeners.war;
import com.github.alathra.alathranwars.conflict.war.War;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.github.alathra.alathranwars.conflict.war.side.Side;
import com.github.alathra.alathranwars.hooks.NameColorHandler;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.event.TownAddResidentEvent;
import com.palmergames.bukkit.towny.event.TownPreRenameEvent;
import com.palmergames.bukkit.towny.event.town.TownKickEvent;
import com.palmergames.bukkit.towny.event.town.TownLeaveEvent;
import com.palmergames.bukkit.towny.event.town.TownPreMergeEvent;
import com.palmergames.bukkit.towny.event.town.TownRuinedEvent;
import com.palmergames.bukkit.towny.object.Town;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.title.Title;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.time.Duration;
public class TownListener implements Listener {
@EventHandler
private void onRename(TownPreRenameEvent e) {
Town town = e.getTown();
if (WarController.getInstance().isTownInAnyWars(town)) {
e.setCancelMessage("You can't rename a town while it's in a war.");
e.setCancelled(true);
}
// TODO Allow renaming in war, update some vars pretty much
}
@EventHandler
private void onPlayerJoin(TownAddResidentEvent e) {
Town town = e.getTown();
Player p = e.getResident().getPlayer();
if (p == null) return;
for (War war : WarController.getInstance().getTownWars(town)) {
Side side = war.getTownSide(town);
if (side == null) continue;
side.addPlayer(p);
final Title warTitle = Title.title(
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
.build(),
ColorParser.of("<gray><i>You entered the war of <war>!")
.parseMinimessagePlaceholder("war", war.getLabel())
.build(),
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
);
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
p.showTitle(warTitle);
p.playSound(warSound);
}
NameColorHandler.getInstance().calculatePlayerColors(p);
}
@EventHandler
private void onPlayerLeave(TownLeaveEvent e) {
Town town = e.getTown();
Player p = e.getResident().getPlayer();
if (p == null) return;
for (War war : WarController.getInstance().getTownWars(town)) {
Side side = war.getTownSide(town);
if (side == null) continue;
side.removePlayer(p);
}
NameColorHandler.getInstance().calculatePlayerColors(p);
}
@EventHandler
private void onPlayerKick(TownKickEvent e) {
Town town = e.getTown();
Player p = e.getKickedResident().getPlayer();
if (p == null) return;
for (War war : WarController.getInstance().getTownWars(town)) {
Side side = war.getTownSide(town);
if (side == null) continue;
side.removePlayer(p);
}
NameColorHandler.getInstance().calculatePlayerColors(p);
}
/*@EventHandler
private void onLeaderChange(TownMayorChangedEvent e) {
Town town = e.getTown();
Resident newMayor = e.getNewMayor();
Resident oldMayor = e.getOldMayor();
if (e.isKingChange() && e.isNationCapital()) {
}
}
@EventHandler
private void onLeaderChangeSuccession(TownMayorChosenBySuccessionEvent e) {
Town town = e.getTown();
Resident newMayor = e.getNewMayor();
Resident oldMayor = e.getOldMayor();
if (e.isKingChange() && e.isNationCapital()) {
}
}*/
@EventHandler
private void onMerge(TownPreMergeEvent e) {
Town town = e.getRemainingTown();
Town town2 = e.getSuccumbingTown();
if (WarController.getInstance().isTownInAnyWars(town) || WarController.getInstance().isTownInAnyWars(town2)) {
e.setCancelMessage("You can't merge towns while they are in a war.");
e.setCancelled(true);
}
// TODO Allow merging towns in war, literally just ensure that players are added to sieges and sides
}
// 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
@EventHandler
private void onRuin(TownRuinedEvent e) {
Town town = e.getTown();
for (War war : WarController.getInstance().getTownWars(town)) {
Side side = war.getTownSide(town);
if (side == null) continue;
war.unsurrenderTown(town);
side.removeTown(town);
side.processSurrenders();
}
}
}
@@ -0,0 +1,19 @@
package com.github.alathra.alathranwars.utility;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.config.ConfigHandler;
import com.github.milkdrinkers.Crate.Config;
import org.jetbrains.annotations.NotNull;
/**
* Convenience class for accessing {@link ConfigHandler#getConfig}
*/
public abstract class Cfg {
/**
* Convenience method for {@link ConfigHandler#getConfig} to getConnection {@link Config}
*/
@NotNull
public static Config get() {
return AlathranWars.getInstance().getConfigHandler().getConfig();
}
}
@@ -0,0 +1,39 @@
package com.github.alathra.alathranwars.utility;
import com.github.alathra.alathranwars.AlathranWars;
import com.github.alathra.alathranwars.db.DatabaseHandler;
import com.github.alathra.alathranwars.db.DatabaseType;
import com.github.alathra.alathranwars.db.jooq.JooqContext;
import org.jetbrains.annotations.NotNull;
import org.jooq.DSLContext;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Convenience class for accessing methods in {@link DatabaseHandler#getConnection}
*/
public abstract class DB {
/**
* Convenience method for {@link DatabaseHandler#getConnection} to getConnection {@link Connection}
*/
@NotNull
public static Connection getConnection() throws SQLException {
return AlathranWars.getInstance().getDataHandler().getConnection();
}
/**
* Convenience method for {@link JooqContext#createContext(Connection)} to getConnection {@link DSLContext}
*/
@NotNull
public static DSLContext getContext(Connection con) {
return AlathranWars.getInstance().getDataHandler().getJooqContext().createContext(con);
}
/**
* Convenience method for {@link DatabaseHandler#getDB()} to getConnection {@link DatabaseType}
*/
public static DatabaseType getDB() {
return AlathranWars.getInstance().getDataHandler().getDB();
}
}
@@ -0,0 +1,21 @@
package com.github.alathra.alathranwars.utility;
import com.github.alathra.alathranwars.AlathranWars;
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
import org.jetbrains.annotations.NotNull;
/**
* A class that provides shorthand access to {@link AlathranWars#getComponentLogger}.
*/
public class Logger {
/**
* Get component logger. Shorthand for:
*
* @return the component logger {@link AlathranWars#getComponentLogger}.
*/
@NotNull
public static ComponentLogger get() {
return AlathranWars.getInstance().getComponentLogger();
}
}
@@ -0,0 +1,42 @@
package com.github.alathra.alathranwars.utility;
import com.github.alathra.alathranwars.conflict.war.WarController;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
/**
* Convenience class for generating UUID for different things in the plugin
*/
public abstract class UUIDUtil {
public static @NotNull UUID generateWarUUID() {
@NotNull UUID uuid = UUID.randomUUID();
while (WarController.getInstance().getWar(uuid) != null) {
uuid = UUID.randomUUID();
}
return uuid;
}
public static @NotNull UUID generateSideUUID(@Nullable UUID previousSideUUID) {
@NotNull UUID uuid = UUID.randomUUID();
while (WarController.getInstance().getSide(uuid) != null || uuid == previousSideUUID) {
uuid = UUID.randomUUID();
}
return uuid;
}
public static @NotNull UUID generateSiegeUUID() {
@NotNull UUID uuid = UUID.randomUUID();
while (WarController.getInstance().getSiege(uuid) != null) {
uuid = UUID.randomUUID();
}
return uuid;
}
}
@@ -0,0 +1,295 @@
package com.github.alathra.alathranwars.utility;
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
import com.github.alathra.alathranwars.conflict.war.WarController;
import com.palmergames.bukkit.towny.object.WorldCoord;
import org.bukkit.Location;
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.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public abstract class Utils {
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
));
/**
* Damages all gear in a players inventory
*
* @param p
* @author ShermansWorld
*/
public static void damageAllGear(@NotNull Player p) {
for (@Nullable ItemStack itemStack : p.getInventory().getContents()) {
if (itemStack == null)
continue;
if (weaponList.contains(itemStack.getType())) {
setWeaponDurability(itemStack);
}
}
final ItemStack @NotNull [] armor = p.getInventory().getArmorContents();
for (@Nullable ItemStack itemStack : armor) {
if (itemStack == null)
continue;
if (armorList.contains(itemStack.getType())) {
setArmorDurability(itemStack);
}
}
}
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);
}
// TODO Implement usage in siege commands to make siege optional argument
public static @Nullable Siege getClosestSiege(Player p, boolean checkIfInSiege) {
Set<Siege> sieges = checkIfInSiege
? WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(p)).collect(Collectors.toSet())
: WarController.getInstance().getSieges();
@Nullable Siege siegeResult = null;
final Location playerLoc = p.getLocation();
double closestSiege = 100000000D;
for (Siege siege : sieges) {
final @Nullable Location location = siege.getTown().getSpawnOrNull();
if (location == null) continue;
if (!location.getWorld().equals(playerLoc.getWorld())) continue;
final double distance = location.distance(playerLoc);
if (distance < closestSiege) {
siegeResult = siege;
closestSiege = distance;
}
}
return siegeResult;
}
public static boolean isOnSiegeBattlefield(Player p, Siege siege) {
if (siege == null) return false;
final Location pLocation = p.getLocation();
final Location siegeLocation = siege.getTownSpawn();
if (siegeLocation == null) return false;
if (!pLocation.getWorld().equals(siegeLocation.getWorld())) return false;
return (pLocation.distance(siegeLocation) <= Siege.BATTLEFIELD_RANGE);
}
/**
* @param worldCoord worldCoord
* @return List of connected chunks
* @author NinjaMandalorian
*/
private static @NotNull ArrayList<WorldCoord> getAdjCells(@NotNull WorldCoord worldCoord) {
@NotNull ArrayList<WorldCoord> worldCoords = new ArrayList<>();
int[] @NotNull [] 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
@NotNull 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 @NotNull ArrayList<WorldCoord> getCluster(WorldCoord chunkCoord) {
// worldCoords is the returning array, searchList is the to-search list.
@NotNull ArrayList<WorldCoord> worldCoords = new ArrayList<>();
@NotNull 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
@NotNull 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,14 @@
package com.github.alathra.alathranwars.utility;
import org.bukkit.ChatColor;
import org.jetbrains.annotations.NotNull;
public abstract class UtilsChat {
public static @NotNull String getPrefix() {
return "<dark_gray>[<gradient:#D72A09:#B01F03>War<dark_gray>]<reset> ";
}
public static @NotNull String color(final @NotNull String input) {
return ChatColor.translateAlternateColorCodes('&', input);
}
}