refactor: cleanup

This commit is contained in:
darksaid98 committed 2023-06-25 04:39:38 +02:00
1 parent 9e5908fecc
commit 75e5aefd3d
30 files changed
+2231 -2207

No files matched your search

@@ -1,66 +1,61 @@
package me.ShermansWorld.AlathraWar; package me.ShermansWorld.AlathraWar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AlathraWarLogger { public class AlathraWarLogger {
File logsFolder; final File logsFolder;
File log; final File log;
PrintWriter output = null; PrintWriter output = null;
public AlathraWarLogger() { public AlathraWarLogger() {
logsFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "logs"); logsFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "logs");
log = new File( log = new File(
"plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt"); "plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt");
} }
public boolean checkFiles() { public boolean checkFiles() {
if (!logsFolder.exists()) { if (!logsFolder.exists()) {
Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not find logs directory"); Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not find logs directory");
return false; return false;
} }
if (!log.exists()) { if (!log.exists()) {
Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not find log.txt"); Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not find log.txt");
return false; return false;
} }
return true; return true;
} }
private void initFileWriter() { private void initFileWriter() {
// init file writer // init file writer
try { try {
FileWriter fw = new FileWriter( FileWriter fw = new FileWriter(
"plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt", "plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt",
true); true);
BufferedWriter bw = new BufferedWriter(fw); BufferedWriter bw = new BufferedWriter(fw);
output = new PrintWriter(bw); output = new PrintWriter(bw);
} catch (IOException e1) { } catch (IOException e1) {
Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not initialize file writer"); Bukkit.getLogger().warning("[AlathraWar] Error in AlathraWarLogger - could not initialize file writer");
return; }
} }
}
public void log(String msg) { public void log(String msg) {
// check for null files // check for null files
if (!checkFiles()) { if (!checkFiles()) {
return; return;
} }
initFileWriter(); initFileWriter();
Date date = new Date(); Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String logMsg = "[" + format.format(date) + "] " + msg; String logMsg = "[" + format.format(date) + "] " + msg;
output.println(logMsg); output.println(logMsg);
output.close(); output.close();
} }
} }
@@ -9,11 +9,11 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
public class Helper public class Helper {
{
public static String color(final String input) { public static String color(final String input) {
return ChatColor.translateAlternateColorCodes('&', input); return ChatColor.translateAlternateColorCodes('&', input);
} }
@@ -23,7 +23,7 @@ public class Helper
} }
public static void testMsg() { public static void testMsg() {
Bukkit.broadcastMessage("test message"); Bukkit.broadcastMessage("test message");
} }
/** /**
@@ -37,124 +37,131 @@ public class Helper
for (int i = 0; i < inv.getSize(); ++i) { for (int i = 0; i < inv.getSize(); ++i) {
final ItemStack is = inv.getItem(i); final ItemStack is = inv.getItem(i);
if (is != null && (is.getType() == Material.NETHERITE_AXE || is.getType() == Material.NETHERITE_SWORD || is.getType() == Material.DIAMOND_AXE || is.getType() == Material.DIAMOND_SWORD || is.getType() == Material.IRON_AXE || is.getType() == Material.IRON_SWORD)) { if (is != null && (is.getType() == Material.NETHERITE_AXE || is.getType() == Material.NETHERITE_SWORD || is.getType() == Material.DIAMOND_AXE || is.getType() == Material.DIAMOND_SWORD || is.getType() == Material.IRON_AXE || is.getType() == Material.IRON_SWORD)) {
ItemMeta meta = is.getItemMeta(); final ItemMeta meta = getItemMeta(is);
final Damageable damageable = (Damageable)meta;
if (is.getType() == Material.NETHERITE_SWORD || is.getType() == Material.NETHERITE_AXE) {
damageable.setDamage(damageable.getDamage() + 507);
if (damageable.getDamage() > 2000) {
damageable.setDamage(2030);
}
}
else if (is.getType() == Material.DIAMOND_SWORD || is.getType() == Material.DIAMOND_AXE) {
damageable.setDamage(damageable.getDamage() + 390);
if (damageable.getDamage() > 1500) {
damageable.setDamage(1560);
}
}
else if (is.getType() == Material.IRON_SWORD || is.getType() == Material.IRON_AXE) {
damageable.setDamage(damageable.getDamage() + 62);
if (damageable.getDamage() > 200) {
damageable.setDamage(249);
}
}
else if (is.getType() == Material.TRIDENT) {
damageable.setDamage(damageable.getDamage() + 62);
if (damageable.getDamage() > 200) {
damageable.setDamage(249);
}
}
meta = (ItemMeta)damageable;
is.setItemMeta(meta); is.setItemMeta(meta);
} }
} }
final ItemStack[] armor = p.getInventory().getArmorContents(); final ItemStack[] armor = p.getInventory().getArmorContents();
for (int j = 0; j < armor.length; ++j) { for (ItemStack itemStack : armor) {
if (armor[j] != null) { if (itemStack != null) {
final ItemStack is2 = armor[j]; if (itemStack.getType() == Material.NETHERITE_HELMET || itemStack.getType() == Material.NETHERITE_CHESTPLATE || itemStack.getType() == Material.NETHERITE_LEGGINGS || itemStack.getType() == Material.NETHERITE_BOOTS || itemStack.getType() == Material.DIAMOND_HELMET || itemStack.getType() == Material.DIAMOND_CHESTPLATE || itemStack.getType() == Material.DIAMOND_LEGGINGS || itemStack.getType() == Material.NETHERITE_BOOTS || itemStack.getType() == Material.IRON_HELMET || itemStack.getType() == Material.IRON_CHESTPLATE || itemStack.getType() == Material.IRON_LEGGINGS || itemStack.getType() == Material.IRON_BOOTS) {
if (is2.getType() == Material.NETHERITE_HELMET || is2.getType() == Material.NETHERITE_CHESTPLATE || is2.getType() == Material.NETHERITE_LEGGINGS || is2.getType() == Material.NETHERITE_BOOTS || is2.getType() == Material.DIAMOND_HELMET || is2.getType() == Material.DIAMOND_CHESTPLATE || is2.getType() == Material.DIAMOND_LEGGINGS || is2.getType() == Material.NETHERITE_BOOTS || is2.getType() == Material.IRON_HELMET || is2.getType() == Material.IRON_CHESTPLATE || is2.getType() == Material.IRON_LEGGINGS || is2.getType() == Material.IRON_BOOTS) { final ItemMeta meta2 = getItemMeta2(itemStack);
ItemMeta meta2 = is2.getItemMeta(); itemStack.setItemMeta(meta2);
final Damageable damageable2 = (Damageable)meta2;
if (is2.getType() == Material.NETHERITE_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 101);
if (damageable2.getDamage() > 400) {
damageable2.setDamage(406);
}
}
if (is2.getType() == Material.NETHERITE_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 148);
if (damageable2.getDamage() > 450) {
damageable2.setDamage(591);
}
}
if (is2.getType() == Material.NETHERITE_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 138);
if (damageable2.getDamage() > 420) {
damageable2.setDamage(554);
}
}
if (is2.getType() == Material.NETHERITE_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 120);
if (damageable2.getDamage() > 370) {
damageable2.setDamage(480);
}
}
if (is2.getType() == Material.DIAMOND_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 90);
if (damageable2.getDamage() > 280) {
damageable2.setDamage(362);
}
}
if (is2.getType() == Material.DIAMOND_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 132);
if (damageable2.getDamage() > 410) {
damageable2.setDamage(527);
}
}
if (is2.getType() == Material.DIAMOND_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 123);
if (damageable2.getDamage() > 380) {
damageable2.setDamage(494);
}
}
if (is2.getType() == Material.DIAMOND_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 107);
if (damageable2.getDamage() > 330) {
damageable2.setDamage(428);
}
}
if (is2.getType() == Material.IRON_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 41);
if (damageable2.getDamage() > 125) {
damageable2.setDamage(164);
}
}
if (is2.getType() == Material.IRON_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 60);
if (damageable2.getDamage() > 190) {
damageable2.setDamage(239);
}
}
if (is2.getType() == Material.IRON_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 56);
if (damageable2.getDamage() > 180) {
damageable2.setDamage(224);
}
}
if (is2.getType() == Material.IRON_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 48);
if (damageable2.getDamage() > 150) {
damageable2.setDamage(194);
}
}
meta2 = (ItemMeta)damageable2;
is2.setItemMeta(meta2);
} }
} }
} }
} }
@Nullable
private static ItemMeta getItemMeta2(ItemStack is2) {
ItemMeta meta2 = is2.getItemMeta();
final Damageable damageable2 = (Damageable) meta2;
if (is2.getType() == Material.NETHERITE_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 101);
if (damageable2.getDamage() > 400) {
damageable2.setDamage(406);
}
}
if (is2.getType() == Material.NETHERITE_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 148);
if (damageable2.getDamage() > 450) {
damageable2.setDamage(591);
}
}
if (is2.getType() == Material.NETHERITE_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 138);
if (damageable2.getDamage() > 420) {
damageable2.setDamage(554);
}
}
if (is2.getType() == Material.NETHERITE_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 120);
if (damageable2.getDamage() > 370) {
damageable2.setDamage(480);
}
}
if (is2.getType() == Material.DIAMOND_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 90);
if (damageable2.getDamage() > 280) {
damageable2.setDamage(362);
}
}
if (is2.getType() == Material.DIAMOND_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 132);
if (damageable2.getDamage() > 410) {
damageable2.setDamage(527);
}
}
if (is2.getType() == Material.DIAMOND_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 123);
if (damageable2.getDamage() > 380) {
damageable2.setDamage(494);
}
}
if (is2.getType() == Material.DIAMOND_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 107);
if (damageable2.getDamage() > 330) {
damageable2.setDamage(428);
}
}
if (is2.getType() == Material.IRON_HELMET) {
damageable2.setDamage(damageable2.getDamage() + 41);
if (damageable2.getDamage() > 125) {
damageable2.setDamage(164);
}
}
if (is2.getType() == Material.IRON_CHESTPLATE) {
damageable2.setDamage(damageable2.getDamage() + 60);
if (damageable2.getDamage() > 190) {
damageable2.setDamage(239);
}
}
if (is2.getType() == Material.IRON_LEGGINGS) {
damageable2.setDamage(damageable2.getDamage() + 56);
if (damageable2.getDamage() > 180) {
damageable2.setDamage(224);
}
}
if (is2.getType() == Material.IRON_BOOTS) {
damageable2.setDamage(damageable2.getDamage() + 48);
if (damageable2.getDamage() > 150) {
damageable2.setDamage(194);
}
}
meta2 = damageable2;
return meta2;
}
@Nullable
private static ItemMeta getItemMeta(ItemStack is) {
ItemMeta meta = is.getItemMeta();
final Damageable damageable = (Damageable) meta;
if (is.getType() == Material.NETHERITE_SWORD || is.getType() == Material.NETHERITE_AXE) {
damageable.setDamage(damageable.getDamage() + 507);
if (damageable.getDamage() > 2000) {
damageable.setDamage(2030);
}
} else if (is.getType() == Material.DIAMOND_SWORD || is.getType() == Material.DIAMOND_AXE) {
damageable.setDamage(damageable.getDamage() + 390);
if (damageable.getDamage() > 1500) {
damageable.setDamage(1560);
}
} else if (is.getType() == Material.IRON_SWORD || is.getType() == Material.IRON_AXE) {
damageable.setDamage(damageable.getDamage() + 62);
if (damageable.getDamage() > 200) {
damageable.setDamage(249);
}
} else if (is.getType() == Material.TRIDENT) {
damageable.setDamage(damageable.getDamage() + 62);
if (damageable.getDamage() > 200) {
damageable.setDamage(249);
}
}
meta = damageable;
return meta;
}
/** /**
*
* @param worldCoord worldCoord * @param worldCoord worldCoord
* @return List of connected chunks * @return List of connected chunks
* @author NinjaMandalorian * @author NinjaMandalorian
@@ -168,7 +175,7 @@ public class Helper
{0, -1}, {0, -1},
{0, 1} {0, 1}
}; // Array that contains relative orthogonal shifts from origin }; // Array that contains relative orthogonal shifts from origin
for ( int[] pair: XZarray) { for (int[] pair : XZarray) {
// Constructs new WorldCoord for comparison // Constructs new WorldCoord for comparison
WorldCoord tCoord = new WorldCoord(worldCoord.getWorldName(), worldCoord.getX() + pair[0], worldCoord.getZ() + pair[1]); WorldCoord tCoord = new WorldCoord(worldCoord.getWorldName(), worldCoord.getX() + pair[0], worldCoord.getZ() + pair[1]);
if (tCoord.getTownOrNull() != null && tCoord.getTownOrNull() == worldCoord.getTownOrNull()) { if (tCoord.getTownOrNull() != null && tCoord.getTownOrNull() == worldCoord.getTownOrNull()) {
@@ -179,19 +186,21 @@ public class Helper
return ReturnList; return ReturnList;
} }
/** Gets all adjacently connected townblocks /**
* Gets all adjacently connected townblocks
*
* @param chunkCoord - WorldCoord to check at * @param chunkCoord - WorldCoord to check at
* @return List of WorldCoords * @return List of WorldCoords
* @author NinjaMandalorian * @author NinjaMandalorian
*/ */
public static ArrayList<WorldCoord> getCluster(WorldCoord chunkCoord){ public static ArrayList<WorldCoord> getCluster(WorldCoord chunkCoord) {
// WCoordList is the returning array, SearchList is the to-search list. // WCoordList is the returning array, SearchList is the to-search list.
ArrayList<WorldCoord> WCoordList = new ArrayList<>(); ArrayList<WorldCoord> WCoordList = new ArrayList<>();
ArrayList<WorldCoord> SearchList = new ArrayList<>(); ArrayList<WorldCoord> SearchList = new ArrayList<>();
SearchList.add(chunkCoord); // Adds 1st chunk to list SearchList.add(chunkCoord); // Adds 1st chunk to list
// Iterates through SearchList, to create a full list of every adjacent cell. // Iterates through SearchList, to create a full list of every adjacent cell.
while (SearchList.size() > 0) { while (!SearchList.isEmpty()) {
// Gets WorldCoord // Gets WorldCoord
WorldCoord toSearch = SearchList.get(0); WorldCoord toSearch = SearchList.get(0);
// Gets adjacent cells // Gets adjacent cells
@@ -199,10 +208,8 @@ public class Helper
for (WorldCoord cell : adjCells) { for (WorldCoord cell : adjCells) {
// If in final list, ignore. // If in final list, ignore.
if (WCoordList.contains(cell)) { if (WCoordList.contains(cell)) {
continue;
// If in to-search list, ignore // If in to-search list, ignore
} else if (SearchList.contains(cell)) { } else if (SearchList.contains(cell)) {
continue;
// Otherwise, add to search-list. // Otherwise, add to search-list.
} else { } else {
SearchList.add(cell); SearchList.add(cell);
@@ -1,116 +1,114 @@
package me.ShermansWorld.AlathraWar; package me.ShermansWorld.AlathraWar;
import me.ShermansWorld.AlathraWar.commands.*; import me.ShermansWorld.AlathraWar.commands.*;
import me.ShermansWorld.AlathraWar.items.WarItemRegistry;
import me.ShermansWorld.AlathraWar.listeners.*;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.Plugin;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import me.ShermansWorld.AlathraWar.hooks.TABHook; import me.ShermansWorld.AlathraWar.hooks.TABHook;
import me.ShermansWorld.AlathraWar.items.WarItemRegistry;
import me.ShermansWorld.AlathraWar.listeners.*;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.bukkit.Bukkit;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin { public class Main extends JavaPlugin {
public static Main instance; public static Main instance;
public static Economy econ; public static Economy econ;
public static AlathraWarLogger warLogger; public static AlathraWarLogger warLogger;
static { static {
instance = null; instance = null;
econ = null; econ = null;
} }
/** /**
* Dangerous if done at the wrong time! * Dangerous if done at the wrong time!
*/ */
public static void initData() { public static void initData() {
File userDataFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "userdata"); File userDataFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "userdata");
if (!userDataFolder.exists()) { if (!userDataFolder.exists()) {
userDataFolder.mkdirs(); userDataFolder.mkdirs();
} }
WarData.setWars(WarData.createWars()); WarData.setWars(WarData.createWars());
} }
@SuppressWarnings("rawtypes") public static Main getInstance() {
private boolean setupEconomy() { return instance;
if (this.getServer().getPluginManager().getPlugin("Vault") == null) { }
return false;
}
@SuppressWarnings("unchecked")
final RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) this.getServer()
.getServicesManager().getRegistration((Class) Economy.class);
if (rsp == null) {
return false;
}
econ = (Economy) rsp.getProvider();
return econ != null;
}
public static Main getInstance() { public static void initLogs() {
return instance; File logsFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "logs");
} if (!logsFolder.exists()) {
logsFolder.mkdirs();
}
File log = new File(
"plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt");
if (!log.exists()) {
try {
log.createNewFile();
} catch (IOException e) {
Bukkit.getLogger().warning("[AlathraWar] Encountered error when creating log file!");
}
}
warLogger = new AlathraWarLogger();
}
public static void initLogs() { private static void initAPIs() {
File logsFolder = new File("plugins" + File.separator + "AlathraWar" + File.separator + "logs"); TABHook.init();
if (!logsFolder.exists()) { }
logsFolder.mkdirs();
}
File log = new File(
"plugins" + File.separator + "AlathraWar" + File.separator + "logs" + File.separator + "log.txt");
if (!log.exists()) {
try {
log.createNewFile();
} catch (IOException e) {
Bukkit.getLogger().warning("[AlathraWar] Encountered error when creating log file!");
}
}
warLogger = new AlathraWarLogger();
}
private static void initAPIs() { @SuppressWarnings("rawtypes")
TABHook.init(); private boolean setupEconomy() {
} if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
@SuppressWarnings("unchecked") final RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) this.getServer()
.getServicesManager().getRegistration((Class) Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
public void onEnable() { public void onEnable() {
instance = this; instance = this;
this.saveDefaultConfig(); this.saveDefaultConfig();
initLogs(); initLogs();
new WarData(this); new WarData(this);
// new TimeoutData(this); // new TimeoutData(this);
new WarCommands(this); new WarCommands(this);
new SiegeCommands(this); new SiegeCommands(this);
new RaidCommands(this); new RaidCommands(this);
new AdminCommands(this); new AdminCommands(this);
getCommand("war").setTabCompleter(new WarTabCompletion()); getCommand("war").setTabCompleter(new WarTabCompletion());
getCommand("siege").setTabCompleter(new SiegeTabCompletion()); getCommand("siege").setTabCompleter(new SiegeTabCompletion());
getCommand("raid").setTabCompleter(new RaidTabCompletion()); getCommand("raid").setTabCompleter(new RaidTabCompletion());
getCommand("alathrawaradmin").setTabCompleter(new AdminTabCompletion()); getCommand("alathrawaradmin").setTabCompleter(new AdminTabCompletion());
getServer().getPluginManager().registerEvents(new KillsListener(), (Plugin) this); getServer().getPluginManager().registerEvents(new KillsListener(), this);
getServer().getPluginManager().registerEvents(new CommandsListener(), (Plugin) this); getServer().getPluginManager().registerEvents(new CommandsListener(), this);
getServer().getPluginManager().registerEvents(new JoinListener(), (Plugin) this); getServer().getPluginManager().registerEvents(new JoinListener(), this);
getServer().getPluginManager().registerEvents(new BlockBreakListener(), (Plugin) this); getServer().getPluginManager().registerEvents(new BlockBreakListener(), this);
getServer().getPluginManager().registerEvents(new PlayerInteractListener(), this); getServer().getPluginManager().registerEvents(new PlayerInteractListener(), this);
// //run first // //run first
new WarItemRegistry(); new WarItemRegistry();
// //run second // //run second
// new WarRecipeRegistry(); // new WarRecipeRegistry();
initData(); initData();
initAPIs(); initAPIs();
setupEconomy(); setupEconomy();
initLogs(); initLogs();
} }
public void onDisable() { public void onDisable() {
for (War war : WarData.getWars()) { for (War war : WarData.getWars()) {
war.save(); war.save();
} }
} }
} }
@@ -16,7 +16,6 @@ import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar; import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
@@ -69,12 +68,18 @@ public class Raid {
//Ticks between activity, this is lower than siege because more activity is occuring in a raid //Ticks between activity, this is lower than siege because more activity is occuring in a raid
private static final int incremental = 40; private static final int incremental = 40;
private War war;
private final String name; private final String name;
public final NamespacedKey bossBarKey = new NamespacedKey(Main.getInstance(), "raidBar." + Raid.this.getName());
public ArrayList<String> activeRaiders = new ArrayList<>();
public ArrayList<String> raiderPlayers = new ArrayList<>();
public ArrayList<String> defenderPlayers = new ArrayList<>();
public Map<WorldCoord, LootBlock> lootedChunks;
final int[] bukkitId;
private War war;
private Town raidedTown; private Town raidedTown;
private Town gatherTown; private Town gatherTown;
private String raiders; private String raiders;
private String defenders; private final String defenders;
private boolean side1AreRaiders; private boolean side1AreRaiders;
private int raiderScore; private int raiderScore;
private int defenderScore; private int defenderScore;
@@ -85,12 +90,6 @@ public class Raid {
private RaidPhase phase; private RaidPhase phase;
private Location townSpawnRaided; private Location townSpawnRaided;
private Location townSpawnGather; private Location townSpawnGather;
int[] bukkitId;
public ArrayList<String> activeRaiders = new ArrayList<>();
public ArrayList<String> raiderPlayers = new ArrayList<>();
public ArrayList<String> defenderPlayers = new ArrayList<>();
public Map<WorldCoord, LootBlock> lootedChunks;
public final NamespacedKey bossBarKey = new NamespacedKey(Main.getInstance(), "raidBar." + Raid.this.getName());
/** /**
* Constructs raid for staging phase * Constructs raid for staging phase
@@ -168,6 +167,10 @@ public class Raid {
this.lootedChunks = new HashMap<>(); this.lootedChunks = new HashMap<>();
} }
static /* synthetic */ void access$7(final Raid raid, final int raidTicks) {
raid.raidTicks = raidTicks;
}
/** /**
* Run when raid starts * Run when raid starts
*/ */
@@ -196,19 +199,17 @@ public class Raid {
//set the last raided time to now //set the last raided time to now
raidedTown.addMetaData(new LongDataField("lastRaided", (System.currentTimeMillis() / 1000))); raidedTown.addMetaData(new LongDataField("lastRaided", (System.currentTimeMillis() / 1000)));
if(war.getSide1Players().contains(owner.getName())) { if (war.getSide1Players().contains(owner.getName())) {
war.setLastRaidTimeSide1((int) (System.currentTimeMillis() / 1000)); war.setLastRaidTimeSide1((int) (System.currentTimeMillis() / 1000));
} else if(war.getSide2Players().contains(owner.getName())) { } else if (war.getSide2Players().contains(owner.getName())) {
war.setLastRaidTimeSide2((int) (System.currentTimeMillis() / 1000)); war.setLastRaidTimeSide2((int) (System.currentTimeMillis() / 1000));
} else {
} }
setupDisplayBar(); setupDisplayBar();
// Creates 10 second looping function for Raid // Creates 10 second looping function for Raid
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin) Main.getInstance(), this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(),
getTickLoop(), 0L, incremental); getTickLoop(), 0L, incremental);
this.getWar().addRaid(this); this.getWar().addRaid(this);
@@ -216,7 +217,6 @@ public class Raid {
} }
/** /**
* Resumes a Raid (after a server restart e.t.c.) * Resumes a Raid (after a server restart e.t.c.)
*/ */
@@ -242,12 +242,11 @@ public class Raid {
setupDisplayBar(); setupDisplayBar();
// Creates 2 second looping function for Raid, restarting this! // Creates 2 second looping function for Raid, restarting this!
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin) Main.getInstance(), this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(),
getTickLoop(), 0L, incremental); getTickLoop(), 0L, incremental);
} }
/** /**
* End of raid * End of raid
*/ */
@@ -258,7 +257,6 @@ public class Raid {
RaidData.removeRaid(this); RaidData.removeRaid(this);
} }
/** /**
* Do loot logic for a chunk, synchronized in case multiple players are looting at once and something breaks * Do loot logic for a chunk, synchronized in case multiple players are looting at once and something breaks
* *
@@ -286,11 +284,13 @@ public class Raid {
//Broadcast to the whole raid //Broadcast to the whole raid
for (String s : activeRaiders) { for (String s : activeRaiders) {
Player pl = Bukkit.getPlayer(s); Player pl = Bukkit.getPlayer(s);
if(pl != null) pl.sendMessage(Helper.chatLabel() + String.format("A townblock has been looted for $%.2f and +10 points. (Added to pool)", lb.value)); if (pl != null)
pl.sendMessage(Helper.chatLabel() + String.format("A townblock has been looted for $%.2f and +10 points. (Added to pool)", lb.value));
} }
for (String s : defenderPlayers) { for (String s : defenderPlayers) {
Player pl = Bukkit.getPlayer(s); Player pl = Bukkit.getPlayer(s);
if(pl != null) pl.sendMessage(Helper.chatLabel() + String.format("A townblock has been looted for $%.2f and +10 points. (Added to pool)", lb.value)); if (pl != null)
pl.sendMessage(Helper.chatLabel() + String.format("A townblock has been looted for $%.2f and +10 points. (Added to pool)", lb.value));
} }
this.save(); this.save();
@@ -300,11 +300,13 @@ public class Raid {
this.addLootedChunk(wc); this.addLootedChunk(wc);
for (String s : activeRaiders) { for (String s : activeRaiders) {
Player pl = Bukkit.getPlayer(s); Player pl = Bukkit.getPlayer(s);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raiders have started looting a town block!"); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Raiders have started looting a town block!");
} }
for (String s : defenderPlayers) { for (String s : defenderPlayers) {
Player pl = Bukkit.getPlayer(s); Player pl = Bukkit.getPlayer(s);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raiders have started looting a town block!"); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Raiders have started looting a town block!");
} }
} }
@@ -322,7 +324,7 @@ public class Raid {
*/ */
private void startTravel() { private void startTravel() {
Raid.this.phase = RaidPhase.TRAVEL; Raid.this.phase = RaidPhase.TRAVEL;
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The Raiders of " Bukkit.broadcastMessage(Helper.chatLabel() + "The Raiders of "
+ (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2()) + (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2())
+ " are coming to raid " + " are coming to raid "
+ Raid.this.getRaidedTown().getName() + "!"); + Raid.this.getRaidedTown().getName() + "!");
@@ -335,7 +337,7 @@ public class Raid {
*/ */
private void startCombat() { private void startCombat() {
Raid.this.phase = RaidPhase.COMBAT; Raid.this.phase = RaidPhase.COMBAT;
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The Raiders of " Bukkit.broadcastMessage(Helper.chatLabel() + "The Raiders of "
+ (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2()) + (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2())
+ " have arrived at " + " have arrived at "
+ Raid.this.getRaidedTown().getName() + " and the fighting has begun!"); + Raid.this.getRaidedTown().getName() + " and the fighting has begun!");
@@ -352,11 +354,11 @@ public class Raid {
this.addPointsToDefenderScore(40); this.addPointsToDefenderScore(40);
for (final String playerName : this.getActiveRaiders()) { for (final String playerName : this.getActiveRaiders()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raider killed! -40 Raid Score"); if (pl != null) pl.sendMessage(Helper.chatLabel() + "Raider killed! -40 Raid Score");
} }
for (final String playerName : this.getDefenderPlayers()) { for (final String playerName : this.getDefenderPlayers()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raider killed! -40 Raid Score"); if (pl != null) pl.sendMessage(Helper.chatLabel() + "Raider killed! -40 Raid Score");
} }
} }
@@ -367,11 +369,11 @@ public class Raid {
this.addPointsToRaiderScore(20); this.addPointsToRaiderScore(20);
for (final String playerName : this.getActiveRaiders()) { for (final String playerName : this.getActiveRaiders()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed! +20 Raid Score"); if (pl != null) pl.sendMessage(Helper.chatLabel() + "Defender killed! +20 Raid Score");
} }
for (final String playerName : this.getDefenderPlayers()) { for (final String playerName : this.getDefenderPlayers()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed! +20 Raid Score"); if (pl != null) pl.sendMessage(Helper.chatLabel() + "Defender killed! +20 Raid Score");
} }
// //tp to raid town spawn // //tp to raid town spawn
@@ -390,11 +392,13 @@ public class Raid {
//award negative score //award negative score
for (final String playerName : this.getActiveRaiders()) { for (final String playerName : this.getActiveRaiders()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raider killed before combat, no points awarded and death treated normally."); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Raider killed before combat, no points awarded and death treated normally.");
} }
for (final String playerName : this.getDefenderPlayers()) { for (final String playerName : this.getDefenderPlayers()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Raider killed before combat, no points awarded and death treated normally."); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Raider killed before combat, no points awarded and death treated normally.");
} }
// //
// //tp to gather town spawn // //tp to gather town spawn
@@ -407,11 +411,11 @@ public class Raid {
// } // }
//teleport the killer back to the raided towns spawn //teleport the killer back to the raided towns spawn
if(killed.getKiller() != null) { if (killed.getKiller() != null) {
if (this.getDefenderSide().contains(killed.getKiller().getName())) { if (this.getDefenderSide().contains(killed.getKiller().getName())) {
try { try {
killed.getKiller().teleport(this.getRaidedTown().getSpawn()); killed.getKiller().teleport(this.getRaidedTown().getSpawn());
killed.getKiller().sendMessage(String.valueOf(Helper.chatLabel()) + "You killed a raider before the raid began and have been teleported back to the defending town."); killed.getKiller().sendMessage(Helper.chatLabel() + "You killed a raider before the raid began and have been teleported back to the defending town.");
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -425,11 +429,13 @@ public class Raid {
public void defenderKilledOutofCombat(PlayerDeathEvent event) { public void defenderKilledOutofCombat(PlayerDeathEvent event) {
for (final String playerName : this.getActiveRaiders()) { for (final String playerName : this.getActiveRaiders()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed before combat, no points awarded and death treated normally."); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Defender killed before combat, no points awarded and death treated normally.");
} }
for (final String playerName : this.getDefenderPlayers()) { for (final String playerName : this.getDefenderPlayers()) {
Player pl = Bukkit.getPlayer(playerName); Player pl = Bukkit.getPlayer(playerName);
if(pl != null) pl.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed before combat, no points awarded and death treated normally."); if (pl != null)
pl.sendMessage(Helper.chatLabel() + "Defender killed before combat, no points awarded and death treated normally.");
} }
//tp to raid town spawn //tp to raid town spawn
@@ -444,7 +450,7 @@ public class Raid {
if (this.getActiveRaiders().contains(killed.getKiller().getName())) { if (this.getActiveRaiders().contains(killed.getKiller().getName())) {
try { try {
killed.getKiller().teleport(this.getGatherTown().getSpawn()); killed.getKiller().teleport(this.getGatherTown().getSpawn());
killed.getKiller().sendMessage(String.valueOf(Helper.chatLabel()) + "You killed a defender before the raid began and have been teleported back to the gather town."); killed.getKiller().sendMessage(Helper.chatLabel() + "You killed a defender before the raid began and have been teleported back to the gather town.");
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -454,7 +460,6 @@ public class Raid {
/** /**
* Raiders win, give payout and finalize raid * Raiders win, give payout and finalize raid
*
*/ */
public void raidersWin(final OfflinePlayer owner, int raiderScore, int defenderScore) { public void raidersWin(final OfflinePlayer owner, int raiderScore, int defenderScore) {
//TODO finalize payout //TODO finalize payout
@@ -467,7 +472,7 @@ public class Raid {
if (factor > 3.0) factor = 3.0; if (factor > 3.0) factor = 3.0;
if (factor < 0) factor = 0.0; if (factor < 0) factor = 0.0;
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The raiders from " + this.raiders Bukkit.broadcastMessage(Helper.chatLabel() + "The raiders from " + this.raiders
+ " have successfully raided " + this.raidedTown.getName() + "!"); + " have successfully raided " + this.raidedTown.getName() + "!");
/* /*
@@ -537,7 +542,6 @@ public class Raid {
/** /**
* Defenders win, payout, and finalize raid * Defenders win, payout, and finalize raid
*
*/ */
public void defendersWin(int raiderScore, int defenderScore) { public void defendersWin(int raiderScore, int defenderScore) {
//TODO finalize payout //TODO finalize payout
@@ -595,7 +599,7 @@ public class Raid {
public void noWinner() { public void noWinner() {
//TODO finalize payout //TODO finalize payout
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The defenders from " + this.defenders Bukkit.broadcastMessage(Helper.chatLabel() + "The defenders from " + this.defenders
+ " didn't push back the raiders of " + this.raiders + ". Yet no loot was taken, raid considered a draw."); + " didn't push back the raiders of " + this.raiders + ". Yet no loot was taken, raid considered a draw.");
Main.warLogger Main.warLogger
.log("No one won the raid of " + this.raidedTown.getName() + "!"); .log("No one won the raid of " + this.raidedTown.getName() + "!");
@@ -642,7 +646,6 @@ public class Raid {
return this.name; return this.name;
} }
public War getWar() { public War getWar() {
return this.war; return this.war;
} }
@@ -739,14 +742,21 @@ public class Raid {
this.raidTicks = ticks; this.raidTicks = ticks;
} }
static /* synthetic */ void access$7(final Raid raid, final int raidTicks) {
raid.raidTicks = raidTicks;
}
public RaidPhase getPhase() { public RaidPhase getPhase() {
return this.phase; return this.phase;
} }
public void setPhase(RaidPhase phase) {
this.phase = phase;
if (phase == RaidPhase.GATHER) {
startGather();
} else if (phase == RaidPhase.TRAVEL) {
startTravel();
} else if (phase == RaidPhase.COMBAT) {
startCombat();
}
}
public void setRaidPhase(final RaidPhase phase) { public void setRaidPhase(final RaidPhase phase) {
this.phase = phase; this.phase = phase;
} }
@@ -783,199 +793,195 @@ public class Raid {
} }
private Runnable getTickLoop() { private Runnable getTickLoop() {
return (Runnable) new Runnable() { return () -> {
if (homeBlockRaided != null) {
raidedTown.setHomeBlock(homeBlockRaided);
raidedTown.setSpawn(townSpawnRaided);
}
if (homeBlockGather != null) {
gatherTown.setHomeBlock(homeBlockGather);
gatherTown.setSpawn(townSpawnGather);
}
if (Raid.this.side1AreRaiders) {
Raid.this.raiderPlayers = Raid.this.war.getSide1Players();
Raid.this.defenderPlayers = Raid.this.war.getSide2Players();
} else {
Raid.this.raiderPlayers = Raid.this.war.getSide2Players();
Raid.this.defenderPlayers = Raid.this.war.getSide1Players();
}
raidTicks += incremental;
@Override //check for end
public void run() { if (Raid.this.raidTicks >= RaidPhase.END.startTick && Raid.this.phase == RaidPhase.COMBAT) {
if (homeBlockRaided != null) { Raid.this.phase = RaidPhase.END;
raidedTown.setHomeBlock(homeBlockRaided); }
raidedTown.setSpawn(townSpawnRaided);
} //check and start travel phase
if (homeBlockGather != null) { if (Raid.this.raidTicks >= RaidPhase.TRAVEL.startTick && Raid.this.phase == RaidPhase.GATHER) {
gatherTown.setHomeBlock(homeBlockGather); startTravel();
gatherTown.setSpawn(townSpawnGather); }
}
if (Raid.this.side1AreRaiders) { //check and start combat phase
Raid.this.raiderPlayers = Raid.this.war.getSide1Players(); if (Raid.this.raidTicks >= RaidPhase.COMBAT.startTick && Raid.this.phase == RaidPhase.TRAVEL) {
Raid.this.defenderPlayers = Raid.this.war.getSide2Players(); startCombat();
}
//check and start gather phase
if (Raid.this.raidTicks >= RaidPhase.GATHER.startTick && Raid.this.phase == RaidPhase.START) {
startGather();
}
if (Raid.this.phase == RaidPhase.END) {
//TODO: fix raid scoring
//for raiders to win enough money, they need a significant up from the defenders, tie given to defender
if (Raid.this.raiderScore > Raid.this.defenderScore) {
Raid.this.raidersWin(Raid.this.owner, Raid.this.raiderScore, Raid.this.defenderScore);
} else { } else {
Raid.this.raiderPlayers = Raid.this.war.getSide2Players(); Raid.this.defendersWin(Raid.this.raiderScore, Raid.this.defenderScore);
Raid.this.defenderPlayers = Raid.this.war.getSide1Players();
} }
raidTicks += incremental; }
//check for end //Raid gather phase behavior
if (Raid.this.raidTicks >= RaidPhase.END.startTick && Raid.this.phase == RaidPhase.COMBAT) { if (Raid.this.phase == RaidPhase.GATHER) {
Raid.this.phase = RaidPhase.END; //Broadcast
if (raidTicks % 6000 == 0) {
Bukkit.broadcastMessage(Helper.chatLabel() + "The raid of "
+ Raid.this.getRaidedTown().getName() + " will begin in " + ((RaidPhase.TRAVEL.startTick - raidTicks) / 20 / 60) + " minutes!");
Bukkit.broadcastMessage(
"The Raiders are gathering at " + getGatherTown().getName() + " before making the journey over!");
} }
//check and start travel phase
if (Raid.this.raidTicks >= RaidPhase.TRAVEL.startTick && Raid.this.phase == RaidPhase.GATHER) {
startTravel();
}
//check and start combat phase //Prevent players from leaving gather town prematurely, if player is raid owner, dont do that
if (Raid.this.raidTicks >= RaidPhase.COMBAT.startTick && Raid.this.phase == RaidPhase.TRAVEL) { for (String playerName : getActiveRaiders()) {
startCombat(); try {
} Player p = Bukkit.getPlayer(playerName);
if (p != null) {
//check and start gather phase ArrayList<WorldCoord> cluster = Helper.getCluster(Raid.this.getGatherTown().getHomeBlock().getWorldCoord());
if (Raid.this.raidTicks >= RaidPhase.GATHER.startTick && Raid.this.phase == RaidPhase.START) { if (!cluster.contains(WorldCoord.parseWorldCoord(p))) {
startGather(); if (p.equals(owner)) {
} p.teleport(gatherTown.getSpawn());
p.sendMessage(Helper.chatLabel() + "You cannot leave the gather town. As raid party leader, you have remained in the party. To stop the raid type /raid abandon");
if (Raid.this.phase == RaidPhase.END) { p.sendMessage(Helper.chatLabel() + "You have been teleported to the gather town's spawn.");
//TODO: fix raid scoring
//for raiders to win enough money, they need a significant up from the defenders, tie given to defender
if (Raid.this.raiderScore > Raid.this.defenderScore) {
Raid.this.raidersWin(Raid.this.owner, Raid.this.raiderScore, Raid.this.defenderScore);
} else {
Raid.this.defendersWin(Raid.this.raiderScore, Raid.this.defenderScore);
}
}
//Raid gather phase behavior
if (Raid.this.phase == RaidPhase.GATHER) {
//Broadcast
if (raidTicks % 6000 == 0) {
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The raid of "
+ Raid.this.getRaidedTown().getName() + " will begin in " + (int) ((RaidPhase.TRAVEL.startTick - raidTicks) / 20 / 60) + " minutes!");
Bukkit.broadcastMessage(
"The Raiders are gathering at " + getGatherTown().getName() + " before making the journey over!");
}
//Prevent players from leaving gather town prematurely, if player is raid owner, dont do that
for (String playerName : getActiveRaiders()) {
try {
Player p = Bukkit.getPlayer(playerName);
if(p != null) {
ArrayList<WorldCoord> cluster = Helper.getCluster(Raid.this.getGatherTown().getHomeBlock().getWorldCoord());
if (!cluster.contains(WorldCoord.parseWorldCoord(p))) {
if (p.equals(owner)) {
p.teleport(gatherTown.getSpawn());
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You cannot leave the gather town. As raid party leader, you have remained in the party. To stop the raid type /raid abandon");
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You have been teleported to the gather town's spawn.");
} else {
Raid.this.removeActiveRaider(p.getName());
p.sendMessage(String.valueOf(Helper.chatLabel()) + "By leaving the gathering town you have left the raid on " + Raid.this.getRaidedTown().getName() + "!");
p.sendMessage(String.valueOf(Helper.chatLabel()) + "To rejoin, do /raid join [war] [town]");
}
}
}
} catch (NullPointerException | TownyException e) {
e.printStackTrace();
}
}
}
//Raid Travel phase behavior
else if (Raid.this.phase == RaidPhase.TRAVEL) {
//Report
if (raidTicks % 2400 == 0) {
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The Raiders of "
+ (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2())
+ " are on their way to raid "
+ Raid.this.getRaidedTown().getName() + "!");
}
//Check if a player has arrived at the town (in it, or within 200 blocks) and if so start combat
for (String player : activeRaiders) {
try {
boolean playerCloseToHomeBlockRaid = false;
final int homeBlockXCoordRaided = Raid.this.getRaidedTown().getHomeBlock().getCoord().getX() * 16;
final int homeBlockZCoordRaided = Raid.this.getRaidedTown().getHomeBlock().getCoord().getZ() * 16;
Player p = Bukkit.getPlayer(player);
if(p != null) {
//Carryover from sieges
if (Math.abs(p.getLocation().getBlockX() - homeBlockXCoordRaided) <= 200 && Math.abs(p.getLocation().getBlockZ() - homeBlockZCoordRaided) <= 200) {
playerCloseToHomeBlockRaid = true;
}
WorldCoord playercoord = WorldCoord.parseWorldCoord(Bukkit.getPlayer(player));
if (Raid.this.getRaidedTown().hasTownBlock(playercoord) || playerCloseToHomeBlockRaid) {
startCombat();
}
}
} catch (TownyException e) {
e.printStackTrace();
}
}
}
//Raid combat phase behavior
else if (Raid.this.phase == RaidPhase.COMBAT) {
//Report
if (Raid.this.raidTicks % 6000 == 0) {
Bukkit.broadcastMessage(Helper.chatLabel() + "Report on the raid of "
+ Raid.this.getRaidedTown().getName() + ":");
Bukkit.broadcastMessage(
"Raider Score - " + Raid.this.raiderScore);
Bukkit.broadcastMessage(
"Defender Score - " + Raid.this.defenderScore);
Bukkit.broadcastMessage(
"Chunks Looted - " + Raid.this.lootedChunks.size() + "/" + raidedTown.getTownBlocks().size());
}
//Looting chunks
for (String name : Raid.this.getActiveRaiders()) {
Player p = Bukkit.getPlayer(name);
if(p != null) {
WorldCoord wc = WorldCoord.parseWorldCoord(p);
if (p.isSneaking()) {
//check if our chunk is looted, if so skip this player
//Idk if thisll work but if it do then ye
if (Raid.this.lootedChunks.containsKey(wc)) {
if (Raid.this.lootedChunks.get(wc).finished) {
p.sendMessage(Helper.chatLabel() + "This chunk is already looted, try another.");
} else {
doLootAt(p, wc);
}
} else { } else {
if (Raid.this.getRaidedTown().hasTownBlock(wc)) { Raid.this.removeActiveRaider(p.getName());
doLootAt(p, wc); p.sendMessage(Helper.chatLabel() + "By leaving the gathering town you have left the raid on " + Raid.this.getRaidedTown().getName() + "!");
} else { p.sendMessage(Helper.chatLabel() + "To rejoin, do /raid join [war] [town]");
p.sendMessage(Helper.chatLabel() + "This space is not part of the raided town, you cannot loot this area."); }
} }
}
} catch (NullPointerException | TownyException e) {
e.printStackTrace();
}
}
}
//Raid Travel phase behavior
else if (Raid.this.phase == RaidPhase.TRAVEL) {
//Report
if (raidTicks % 2400 == 0) {
Bukkit.broadcastMessage(Helper.chatLabel() + "The Raiders of "
+ (side1AreRaiders ? Raid.this.war.getSide1() : Raid.this.war.getSide2())
+ " are on their way to raid "
+ Raid.this.getRaidedTown().getName() + "!");
}
//Check if a player has arrived at the town (in it, or within 200 blocks) and if so start combat
for (String player : activeRaiders) {
try {
boolean playerCloseToHomeBlockRaid = false;
final int homeBlockXCoordRaided = Raid.this.getRaidedTown().getHomeBlock().getCoord().getX() * 16;
final int homeBlockZCoordRaided = Raid.this.getRaidedTown().getHomeBlock().getCoord().getZ() * 16;
Player p = Bukkit.getPlayer(player);
if (p != null) {
//Carryover from sieges
if (Math.abs(p.getLocation().getBlockX() - homeBlockXCoordRaided) <= 200 && Math.abs(p.getLocation().getBlockZ() - homeBlockZCoordRaided) <= 200) {
playerCloseToHomeBlockRaid = true;
}
WorldCoord playercoord = WorldCoord.parseWorldCoord(Bukkit.getPlayer(player));
if (Raid.this.getRaidedTown().hasTownBlock(playercoord) || playerCloseToHomeBlockRaid) {
startCombat();
}
}
} catch (TownyException e) {
e.printStackTrace();
}
}
}
//Raid combat phase behavior
else if (Raid.this.phase == RaidPhase.COMBAT) {
//Report
if (Raid.this.raidTicks % 6000 == 0) {
Bukkit.broadcastMessage(Helper.chatLabel() + "Report on the raid of "
+ Raid.this.getRaidedTown().getName() + ":");
Bukkit.broadcastMessage(
"Raider Score - " + Raid.this.raiderScore);
Bukkit.broadcastMessage(
"Defender Score - " + Raid.this.defenderScore);
Bukkit.broadcastMessage(
"Chunks Looted - " + Raid.this.lootedChunks.size() + "/" + raidedTown.getTownBlocks().size());
}
//Looting chunks
for (String name : Raid.this.getActiveRaiders()) {
Player p = Bukkit.getPlayer(name);
if (p != null) {
WorldCoord wc = WorldCoord.parseWorldCoord(p);
if (p.isSneaking()) {
//check if our chunk is looted, if so skip this player
//Idk if thisll work but if it do then ye
if (Raid.this.lootedChunks.containsKey(wc)) {
if (Raid.this.lootedChunks.get(wc).finished) {
p.sendMessage(Helper.chatLabel() + "This chunk is already looted, try another.");
} else {
doLootAt(p, wc);
}
} else {
if (Raid.this.getRaidedTown().hasTownBlock(wc)) {
doLootAt(p, wc);
} else {
p.sendMessage(Helper.chatLabel() + "This space is not part of the raided town, you cannot loot this area.");
} }
} }
} }
} }
//refresh the existing display bar
refreshDisplayBar();
} }
//refresh the existing display bar
refreshDisplayBar();
} }
}; };
} }
public void refreshDisplayBar() { public void refreshDisplayBar() {
BossBar bossBar = Bukkit.getBossBar(bossBarKey); BossBar bossBar = Bukkit.getBossBar(bossBarKey);
if(bossBar == null) bossBar = createNewDisplayBar(); if (bossBar == null) bossBar = createNewDisplayBar();
bossBar.setTitle(String.format("%d -- Raiders -Raid Score- Defenders -- %d", Raid.this.raiderScore, Raid.this.defenderScore)); bossBar.setTitle(String.format("%d -- Raiders -Raid Score- Defenders -- %d", Raid.this.raiderScore, Raid.this.defenderScore));
bossBar.setProgress((double) (Raid.this.raiderScore + 0.5D) / ((Raid.this.raiderScore + Raid.this.defenderScore) + 1.0D)); bossBar.setProgress((Raid.this.raiderScore + 0.5D) / ((Raid.this.raiderScore + Raid.this.defenderScore) + 1.0D));
for (String s : Raid.this.getActiveRaiders()) { for (String s : Raid.this.getActiveRaiders()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) { if (p != null) {
if(!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p); if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
} }
} }
for (String s : Raid.this.getDefenderPlayers()) { for (String s : Raid.this.getDefenderPlayers()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) { if (p != null) {
if(!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p); if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
} }
} }
} }
public void setupDisplayBar() { public void setupDisplayBar() {
BossBar bossBar = Bukkit.getBossBar(bossBarKey); BossBar bossBar = Bukkit.getBossBar(bossBarKey);
if(bossBar == null) bossBar = createNewDisplayBar(); if (bossBar == null) bossBar = createNewDisplayBar();
for (String s : Raid.this.getActiveRaiders()) { for (String s : Raid.this.getActiveRaiders()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
@@ -1023,17 +1029,6 @@ public class Raid {
this.homeBlockGather = homeBlockGather; this.homeBlockGather = homeBlockGather;
} }
public void setPhase(RaidPhase phase) {
this.phase = phase;
if(phase == RaidPhase.GATHER) {
startGather();
} else if(phase == RaidPhase.TRAVEL) {
startTravel();
} else if(phase == RaidPhase.COMBAT) {
startCombat();
}
}
public Location getTownSpawnRaided() { public Location getTownSpawnRaided() {
return townSpawnRaided; return townSpawnRaided;
} }
@@ -1052,7 +1047,7 @@ public class Raid {
public static class LootBlock { public static class LootBlock {
public WorldCoord worldCoord; public final WorldCoord worldCoord;
public int ticks; public int ticks;
public double value; public double value;
public boolean finished; public boolean finished;
@@ -1,96 +1,93 @@
package me.ShermansWorld.AlathraWar; package me.ShermansWorld.AlathraWar;
import com.palmergames.bukkit.towny.exceptions.TownyException;
import org.bukkit.*;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.exceptions.TownyException;
import com.palmergames.bukkit.towny.object.*;
import me.ShermansWorld.AlathraWar.data.SiegeData;
import org.bukkit.*;
import org.bukkit.boss.BarColor; import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle; import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar; import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.object.WorldCoord;
import me.ShermansWorld.AlathraWar.data.SiegeData;
import java.util.ArrayList; import java.util.ArrayList;
import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownBlock;
public class Siege { public class Siege {
public static final int maxSiegeTicks = 72000; // 60 minute tick constant public static final int maxSiegeTicks = 72000; // 60 minute tick constant
public final NamespacedKey bossBarKey;
private War war; // War which siege belongs to public ArrayList<String> attackerPlayers;
private Town town; // Town of the siege public ArrayList<String> defenderPlayers;
private boolean side1AreAttackers; // bool of if side1 being attacker public ArrayList<Location> beaconLocs;
private int attackerPoints; int[] bukkitId;
private int defenderPoints; private War war; // War which siege belongs to
private OfflinePlayer siegeLeader; private Town town; // Town of the siege
private int siegeTicks; private boolean side1AreAttackers; // bool of if side1 being attacker
private TownBlock homeBlock; private int attackerPoints;
private Location townSpawn; private int defenderPoints;
int[] bukkitId; private OfflinePlayer siegeLeader;
public ArrayList<String> attackerPlayers; private int siegeTicks;
public ArrayList<String> defenderPlayers; private TownBlock homeBlock;
public ArrayList<Location> beaconLocs; private Location townSpawn;
public final NamespacedKey bossBarKey;
public Siege(final War war, final Town town, OfflinePlayer siegeLeader) { public Siege(final War war, final Town town, OfflinePlayer siegeLeader) {
this.siegeTicks = 0; this.siegeTicks = 0;
this.bukkitId = new int[1]; this.bukkitId = new int[1];
this.attackerPlayers = new ArrayList<String>(); this.attackerPlayers = new ArrayList<>();
this.defenderPlayers = new ArrayList<String>(); this.defenderPlayers = new ArrayList<>();
this.beaconLocs = new ArrayList<Location>(); this.beaconLocs = new ArrayList<>();
this.war = war; this.war = war;
this.town = town; this.town = town;
this.siegeLeader = siegeLeader; this.siegeLeader = siegeLeader;
bossBarKey = new NamespacedKey(Main.getInstance(), "siegeBar." + this.getName()); bossBarKey = new NamespacedKey(Main.getInstance(), "siegeBar." + this.getName());
if (war.getSide(town.getName()) == 2) side1AreAttackers = true; side1AreAttackers = war.getSide(town.getName()) == 2;
else side1AreAttackers = false;
}
/** Starts a siege */
public void start() {
attackerPoints = 0;
defenderPoints = 0;
this.siegeTicks = 0;
homeBlock = town.getHomeBlockOrNull();
townSpawn = town.getSpawnOrNull();
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin) Main.getInstance(), getTickLoop(), 0L, 200L);
setupDisplayBar();
}
/** Resumes a siege (after a server restart e.t.c.)*/
public void resume(int resumeTick) {
siegeTicks = resumeTick;
homeBlock = town.getHomeBlockOrNull();
townSpawn = town.getSpawnOrNull();
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask((Plugin) Main.getInstance(), getTickLoop(), 0L, 200L);
setupDisplayBar();
} }
/** Stops a siege */ /**
public void stop() { * Starts a siege
deleteDisplayBar(); */
Bukkit.getScheduler().cancelTask(this.bukkitId[0]); public void start() {
this.war.getSieges().remove(this); attackerPoints = 0;
SiegeData.removeSiege(this); defenderPoints = 0;
this.siegeTicks = 0;
homeBlock = town.getHomeBlockOrNull();
townSpawn = town.getSpawnOrNull();
} this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), getTickLoop(), 0L, 200L);
setupDisplayBar();
}
/**
* Resumes a siege (after a server restart e.t.c.)
*/
public void resume(int resumeTick) {
siegeTicks = resumeTick;
homeBlock = town.getHomeBlockOrNull();
townSpawn = town.getSpawnOrNull();
this.bukkitId[0] = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), getTickLoop(), 0L, 200L);
setupDisplayBar();
}
/**
* Stops a siege
*/
public void stop() {
deleteDisplayBar();
Bukkit.getScheduler().cancelTask(this.bukkitId[0]);
this.war.getSieges().remove(this);
SiegeData.removeSiege(this);
}
private Runnable getTickLoop() { private Runnable getTickLoop() {
return new Runnable() { return new Runnable() {
@@ -127,7 +124,7 @@ public class Siege {
if (pl != null) { if (pl != null) {
WorldCoord wc = WorldCoord.parseWorldCoord(pl); WorldCoord wc = WorldCoord.parseWorldCoord(pl);
if (wc.getTownBlock().getTown().equals(town)) { if (wc.getTownBlock().getTown().equals(town)) {
if(town.getHomeBlockOrNull() != null) { if (town.getHomeBlockOrNull() != null) {
if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) { if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) {
if (!pl.isDead()) { if (!pl.isDead()) {
if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) < 10) { if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) < 10) {
@@ -140,7 +137,7 @@ public class Siege {
} }
} }
} catch (NotRegisteredException ignored) { } catch (NotRegisteredException ignored) {
Main.warLogger.log(Helper.chatLabel() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl).toString()); Main.warLogger.log(Helper.chatLabel() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl));
} }
} }
for (final String playerName : Siege.this.defenderPlayers) { for (final String playerName : Siege.this.defenderPlayers) {
@@ -149,7 +146,7 @@ public class Siege {
if (pl != null) { if (pl != null) {
WorldCoord wc = WorldCoord.parseWorldCoord(pl); WorldCoord wc = WorldCoord.parseWorldCoord(pl);
if (wc.getTownBlock().getTown().equals(town)) { if (wc.getTownBlock().getTown().equals(town)) {
if(town.getHomeBlockOrNull() != null) { if (town.getHomeBlockOrNull() != null) {
if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) { if (town.getHomeBlockOrNull().getWorldCoord().equals(wc)) {
if (!pl.isDead()) { if (!pl.isDead()) {
if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) <= 10) { if ((Math.abs(pl.getLocation().getBlockY() - townSpawn.getBlockY())) <= 10) {
@@ -162,21 +159,21 @@ public class Siege {
} }
} }
} catch (NotRegisteredException ignored) { } catch (NotRegisteredException ignored) {
Main.warLogger.log(Helper.chatLabel() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl).toString()); Main.warLogger.log(Helper.chatLabel() + "Attempting to look for town at " + WorldCoord.parseWorldCoord(pl));
} }
} }
if (attackersAreOnHomeBlock && defendersAreOnHomeBlock) { // Contested if (attackersAreOnHomeBlock && defendersAreOnHomeBlock) { // Contested
if (this.homeBlockControl != 1) { if (this.homeBlockControl != 1) {
for (final String playerName : Siege.this.attackerPlayers) { for (final String playerName : Siege.this.attackerPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "HomeBlock at " + Siege.this.town.getName() + " contested!"); + "HomeBlock at " + Siege.this.town.getName() + " contested!");
} catch (NullPointerException ex5) { } catch (NullPointerException ex5) {
} }
} }
for (final String playerName : Siege.this.defenderPlayers) { for (final String playerName : Siege.this.defenderPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "HomeBlock at " + Siege.this.town.getName() + " contested!"); + "HomeBlock at " + Siege.this.town.getName() + " contested!");
} catch (NullPointerException ex6) { } catch (NullPointerException ex6) {
} }
@@ -187,7 +184,7 @@ public class Siege {
if (this.homeBlockControl != 2) { if (this.homeBlockControl != 2) {
for (final String playerName : Siege.this.attackerPlayers) { for (final String playerName : Siege.this.attackerPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "Attackers have captured the HomeBlock at " + "Attackers have captured the HomeBlock at "
+ Siege.this.town.getName() + "! +1 Attacker Points per second"); + Siege.this.town.getName() + "! +1 Attacker Points per second");
} catch (NullPointerException ex7) { } catch (NullPointerException ex7) {
@@ -195,7 +192,7 @@ public class Siege {
} }
for (final String playerName : Siege.this.defenderPlayers) { for (final String playerName : Siege.this.defenderPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "Attackers have captured the HomeBlock at " + "Attackers have captured the HomeBlock at "
+ Siege.this.town.getName() + "! +1 Attacker Points per second"); + Siege.this.town.getName() + "! +1 Attacker Points per second");
} catch (NullPointerException ex8) { } catch (NullPointerException ex8) {
@@ -208,7 +205,7 @@ public class Siege {
if (this.homeBlockControl != 3) { if (this.homeBlockControl != 3) {
for (final String playerName : Siege.this.attackerPlayers) { for (final String playerName : Siege.this.attackerPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "Defenders retain control of the HomeBlock at " + "Defenders retain control of the HomeBlock at "
+ Siege.this.town.getName() + "! +1 Defender Points per second"); + Siege.this.town.getName() + "! +1 Defender Points per second");
} catch (NullPointerException ex9) { } catch (NullPointerException ex9) {
@@ -216,7 +213,7 @@ public class Siege {
} }
for (final String playerName : Siege.this.defenderPlayers) { for (final String playerName : Siege.this.defenderPlayers) {
try { try {
Bukkit.getPlayer(playerName).sendMessage(String.valueOf(Helper.chatLabel()) Bukkit.getPlayer(playerName).sendMessage(Helper.chatLabel()
+ "Defenders retain control of the HomeBlock at " + "Defenders retain control of the HomeBlock at "
+ Siege.this.town.getName() + "! +1 Defender Points per second"); + Siege.this.town.getName() + "! +1 Defender Points per second");
} catch (NullPointerException ex10) { } catch (NullPointerException ex10) {
@@ -227,12 +224,12 @@ public class Siege {
this.homeBlockControl = 3; this.homeBlockControl = 3;
} }
if (Siege.this.siegeTicks % 6000 == 0) { // Updates every 5 minutes if (Siege.this.siegeTicks % 6000 == 0) { // Updates every 5 minutes
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "Report on the siege of " Bukkit.broadcastMessage(Helper.chatLabel() + "Report on the siege of "
+ Siege.this.town.getName() + ":"); + Siege.this.town.getName() + ":");
Bukkit.broadcastMessage( Bukkit.broadcastMessage(
"Attacker Points - " + String.valueOf(Siege.this.attackerPoints)); "Attacker Points - " + Siege.this.attackerPoints);
Bukkit.broadcastMessage( Bukkit.broadcastMessage(
"Defender Points - " + String.valueOf(Siege.this.defenderPoints)); "Defender Points - " + Siege.this.defenderPoints);
} }
if (siegeTicks % 1200 == 0) { // Saves every minute if (siegeTicks % 1200 == 0) { // Saves every minute
save(); save();
@@ -243,43 +240,43 @@ public class Siege {
} }
}; };
} }
public void attackersWin(final OfflinePlayer siegeLeader) { public void attackersWin(final OfflinePlayer siegeLeader) {
final Resident resident = TownyAPI.getInstance().getResident(siegeLeader.getUniqueId()); final Resident resident = TownyAPI.getInstance().getResident(siegeLeader.getUniqueId());
Nation nation = null; Nation nation = null;
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The attackers have won the siege of " + this.town.getName() + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The attackers have won the siege of " + this.town.getName() + "!");
try { try {
nation = resident.getTown().getNation(); nation = resident.getTown().getNation();
} catch (Exception e) {} } catch (Exception e) {
if (nation != null) { }
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The town of " + this.town.getName() if (nation != null) {
+ " has been placed under occupation by " + nation.getName() + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + this.town.getName()
} + " has been placed under occupation by " + nation.getName() + "!");
Main.econ.depositPlayer(siegeLeader, 2500.0); }
double amt = 0.0; Main.econ.depositPlayer(siegeLeader, 2500.0);
if (this.town.getAccount().getHoldingBalance() > 10000.0) { double amt = 0.0;
amt = Math.floor(this.town.getAccount().getHoldingBalance()) / 4.0; if (this.town.getAccount().getHoldingBalance() > 10000.0) {
this.town.getAccount().withdraw(amt, "war loot"); amt = Math.floor(this.town.getAccount().getHoldingBalance()) / 4.0;
} else { this.town.getAccount().withdraw(amt, "war loot");
if (this.town.getAccount().getHoldingBalance() < 2500.0) { } else {
amt = this.town.getAccount().getHoldingBalance(); if (this.town.getAccount().getHoldingBalance() < 2500.0) {
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The town of " + this.town.getName() amt = this.town.getAccount().getHoldingBalance();
+ " has been destroyed by " + this.getAttackerSide() + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + this.town.getName()
TownyUniverse.getInstance().getDataSource().deleteTown(this.town); + " has been destroyed by " + this.getAttackerSide() + "!");
Main.econ.depositPlayer(siegeLeader, amt); TownyUniverse.getInstance().getDataSource().deleteTown(this.town);
return; Main.econ.depositPlayer(siegeLeader, amt);
} return;
this.town.getAccount().withdraw(2500.0, "war loot"); }
amt = 2500.0; this.town.getAccount().withdraw(2500.0, "war loot");
} amt = 2500.0;
Bukkit.broadcastMessage("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide() }
+ ", valuing $" + String.valueOf(amt)); Bukkit.broadcastMessage("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
Main.warLogger.log("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide() + ", valuing $" + amt);
+ ", valuing $" + String.valueOf(amt)); Main.warLogger.log("The town of " + this.town.getName() + " has been sacked by " + this.getAttackerSide()
Main.econ.depositPlayer(siegeLeader, amt); + ", valuing $" + amt);
Main.econ.depositPlayer(siegeLeader, amt);
if (side1AreAttackers) { if (side1AreAttackers) {
war.addSide1Points(50); war.addSide1Points(50);
@@ -287,17 +284,17 @@ public class Siege {
war.addSide2Points(50); war.addSide2Points(50);
} }
stop(); stop();
clearBeacon(); clearBeacon();
} }
public void defendersWin() { public void defendersWin() {
this.town.getAccount().deposit(2500.0, "War chest"); this.town.getAccount().deposit(2500.0, "War chest");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The defenders have won the siege of " + this.town.getName() + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The defenders have won the siege of " + this.town.getName() + "!");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + this.town.getName() Bukkit.broadcastMessage(Helper.chatLabel() + this.town.getName()
+ " has recovered the attackers' war chest, valued at $2,500"); + " has recovered the attackers' war chest, valued at $2,500");
Main.warLogger Main.warLogger
.log(war.getName() + ": The defenders have won the siege of " + this.town.getName() + "!"); .log(war.getName() + ": The defenders have won the siege of " + this.town.getName() + "!");
if (side1AreAttackers) { if (side1AreAttackers) {
war.addSide2Points(50); war.addSide2Points(50);
@@ -305,295 +302,299 @@ public class Siege {
war.addSide1Points(50); war.addSide1Points(50);
} }
stop(); stop();
clearBeacon(); clearBeacon();
} }
/** /**
* No winnder declared * No winnder declared
*/ */
public void noWinner() { public void noWinner() {
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The siege of " + this.town.getName() + " was a draw!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The siege of " + this.town.getName() + " was a draw!");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "No money has been recovered."); Bukkit.broadcastMessage(Helper.chatLabel() + "No money has been recovered.");
Main.warLogger Main.warLogger
.log(war.getName() + ": No one won the siege of " + this.town.getName() + "!"); .log(war.getName() + ": No one won the siege of " + this.town.getName() + "!");
stop(); stop();
clearBeacon(); clearBeacon();
} }
public void createBeacon() { public void createBeacon() {
try { try {
World world = town.getWorld(); World world = town.getWorld();
int homeBlockX = this.town.getHomeBlock().getX() * 16; int homeBlockX = this.town.getHomeBlock().getX() * 16;
int homeBlockZ = (this.town.getHomeBlock().getZ() + 1) * 16; int homeBlockZ = (this.town.getHomeBlock().getZ() + 1) * 16;
if (homeBlockX > 0) { if (homeBlockX > 0) {
homeBlockX -= 8; homeBlockX -= 8;
} }
if (homeBlockZ > 0) { if (homeBlockZ > 0) {
homeBlockZ -= 8; homeBlockZ -= 8;
} }
if (homeBlockX < 0) { if (homeBlockX < 0) {
homeBlockX += 8; homeBlockX += 8;
} }
if (homeBlockZ < 0) { if (homeBlockZ < 0) {
homeBlockZ += 8; homeBlockZ += 8;
} }
int homeBlockY = 253; int homeBlockY = 253;
final Location beaconLoc = new Location(this.town.getWorld(), (double) homeBlockX, final Location beaconLoc = new Location(this.town.getWorld(), homeBlockX,
(double) (homeBlockY - 2), (double) homeBlockZ); homeBlockY - 2, homeBlockZ);
while (beaconLoc.getBlock().getType().equals((Object) Material.AIR)) { while (beaconLoc.getBlock().getType().equals(Material.AIR)) {
--homeBlockY; --homeBlockY;
beaconLoc.setY((double) homeBlockY); beaconLoc.setY(homeBlockY);
} }
homeBlockY += 2; homeBlockY += 2;
this.beaconLocs.add(new Location(world, (double) homeBlockX, (double) homeBlockY, (double) homeBlockZ)); this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY, homeBlockZ));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) homeBlockX, (double) (homeBlockY + 1), (double) homeBlockZ)); .add(new Location(world, homeBlockX, homeBlockY + 1, homeBlockZ));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) homeBlockZ)); .add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), (double) homeBlockZ)); new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), (double) homeBlockZ)); new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) (homeBlockZ + 1))); new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ + 1));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) (homeBlockZ - 1))); new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ - 1));
this.beaconLocs.add(new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), this.beaconLocs.add(new Location(world, homeBlockX + 1, homeBlockY - 1,
(double) (homeBlockZ + 1))); homeBlockZ + 1));
this.beaconLocs.add(new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), this.beaconLocs.add(new Location(world, homeBlockX + 1, homeBlockY - 1,
(double) (homeBlockZ - 1))); homeBlockZ - 1));
this.beaconLocs.add(new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), this.beaconLocs.add(new Location(world, homeBlockX - 1, homeBlockY - 1,
(double) (homeBlockZ + 1))); homeBlockZ + 1));
this.beaconLocs.add(new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), this.beaconLocs.add(new Location(world, homeBlockX - 1, homeBlockY - 1,
(double) (homeBlockZ - 1))); homeBlockZ - 1));
for (int i = 2; i < this.beaconLocs.size(); ++i) { for (int i = 2; i < this.beaconLocs.size(); ++i) {
if (this.beaconLocs.get(i).getBlock().getType() != Material.AIR) { if (this.beaconLocs.get(i).getBlock().getType() != Material.AIR) {
i = 1; i = 1;
homeBlockY++; homeBlockY++;
for (final Location loc : this.beaconLocs) { for (final Location loc : this.beaconLocs) {
loc.setY(loc.getY() + 1.0); loc.setY(loc.getY() + 1.0);
} }
} }
} }
this.beaconLocs.get(0).getBlock().setType(Material.BEACON); this.beaconLocs.get(0).getBlock().setType(Material.BEACON);
this.beaconLocs.get(1).getBlock().setType(Material.RED_STAINED_GLASS); this.beaconLocs.get(1).getBlock().setType(Material.RED_STAINED_GLASS);
for (int i = 2; i < this.beaconLocs.size(); ++i) { for (int i = 2; i < this.beaconLocs.size(); ++i) {
this.beaconLocs.get(i).getBlock().setType(Material.IRON_BLOCK); this.beaconLocs.get(i).getBlock().setType(Material.IRON_BLOCK);
} }
save(); save();
} catch (TownyException ex) { } catch (TownyException ex) {
} }
} }
public void resetBeacon(World world, int homeBlockX, int homeBlockY, int homeBlockZ) { public void resetBeacon(World world, int homeBlockX, int homeBlockY, int homeBlockZ) {
this.beaconLocs.add(new Location(world, (double) homeBlockX, (double) homeBlockY, (double) homeBlockZ)); this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY, homeBlockZ));
this.beaconLocs.add(new Location(world, (double) homeBlockX, (double) (homeBlockY + 1), (double) homeBlockZ)); this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY + 1, homeBlockZ));
this.beaconLocs.add(new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) homeBlockZ)); this.beaconLocs.add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), (double) homeBlockZ)); .add(new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), (double) homeBlockZ)); .add(new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) (homeBlockZ + 1))); .add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ + 1));
this.beaconLocs this.beaconLocs
.add(new Location(world, (double) homeBlockX, (double) (homeBlockY - 1), (double) (homeBlockZ - 1))); .add(new Location(world, homeBlockX, homeBlockY - 1, homeBlockZ - 1));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), (double) (homeBlockZ + 1))); new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ + 1));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX + 1), (double) (homeBlockY - 1), (double) (homeBlockZ - 1))); new Location(world, homeBlockX + 1, homeBlockY - 1, homeBlockZ - 1));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), (double) (homeBlockZ + 1))); new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ + 1));
this.beaconLocs.add( this.beaconLocs.add(
new Location(world, (double) (homeBlockX - 1), (double) (homeBlockY - 1), (double) (homeBlockZ - 1))); new Location(world, homeBlockX - 1, homeBlockY - 1, homeBlockZ - 1));
} }
public void clearBeacon() { public void clearBeacon() {
for (final Location loc : this.beaconLocs) { for (final Location loc : this.beaconLocs) {
loc.getBlock().setType(Material.AIR); loc.getBlock().setType(Material.AIR);
} }
} }
public void addPointsToAttackers(final int points) { public void addPointsToAttackers(final int points) {
this.attackerPoints += points; this.attackerPoints += points;
} }
public void addPointsToDefenders(final int points) { public void addPointsToDefenders(final int points) {
this.defenderPoints += points; this.defenderPoints += points;
} }
public War getWar() { public War getWar() {
return this.war; return this.war;
} }
public void setWar(final War war) { public void setWar(final War war) {
this.war = war; this.war = war;
} }
public Town getTown() { public Town getTown() {
return this.town; return this.town;
} }
public void setTown(final Town town) { public void setTown(final Town town) {
this.town = town; this.town = town;
} }
public OfflinePlayer getSiegeOwner() { public OfflinePlayer getSiegeOwner() {
return siegeLeader; return siegeLeader;
} }
public void setSiegeOwner(OfflinePlayer siegeOwner) { public void setSiegeOwner(OfflinePlayer siegeOwner) {
this.siegeLeader = siegeOwner; this.siegeLeader = siegeOwner;
} }
/** Gets attacker name string */ /**
public String getAttackerSide() { * Gets attacker name string
if (side1AreAttackers) { */
public String getAttackerSide() {
if (side1AreAttackers) {
return war.getSide1(); return war.getSide1();
} else { } else {
return war.getSide2(); return war.getSide2();
} }
} }
/** Gets defender name string */ /**
public String getDefenderSide() { * Gets defender name string
if (side1AreAttackers) { */
public String getDefenderSide() {
if (side1AreAttackers) {
return war.getSide2(); return war.getSide2();
} else { } else {
return war.getSide1(); return war.getSide1();
} }
} }
public void refreshDisplayBar() { public void refreshDisplayBar() {
BossBar bossBar = Bukkit.getBossBar(bossBarKey); BossBar bossBar = Bukkit.getBossBar(bossBarKey);
if(bossBar == null) bossBar = createNewDisplayBar(); if (bossBar == null) bossBar = createNewDisplayBar();
bossBar.setTitle(String.format("%d -- Attackers -Siege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints)); bossBar.setTitle(String.format("%d -- Attackers -Siege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints));
bossBar.setProgress((double) (this.attackerPoints + 0.5D) / ((this.attackerPoints + this.defenderPoints) + 1.0D)); bossBar.setProgress((this.attackerPoints + 0.5D) / ((this.attackerPoints + this.defenderPoints) + 1.0D));
for (String s : this.getAttackerPlayers()) { for (String s : this.getAttackerPlayers()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) { if (p != null) {
if(!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p); if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
} }
} }
for (String s : this.getDefenderPlayers()) { for (String s : this.getDefenderPlayers()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) { if (p != null) {
if(!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p); if (!bossBar.getPlayers().contains(p)) bossBar.addPlayer(p);
} }
} }
} }
public void setupDisplayBar() { public void setupDisplayBar() {
BossBar bossBar = Bukkit.getBossBar(bossBarKey); BossBar bossBar = Bukkit.getBossBar(bossBarKey);
if(bossBar == null) bossBar = createNewDisplayBar(); if (bossBar == null) bossBar = createNewDisplayBar();
for (String s : this.getAttackerPlayers()) { for (String s : this.getAttackerPlayers()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) { if (p != null) {
bossBar.addPlayer(p); bossBar.addPlayer(p);
} }
} }
for (String s : this.getDefenderPlayers()) { for (String s : this.getDefenderPlayers()) {
Player p = Bukkit.getPlayer(s); Player p = Bukkit.getPlayer(s);
if (p != null) bossBar.addPlayer(p); if (p != null) bossBar.addPlayer(p);
} }
} }
public void deleteDisplayBar() { public void deleteDisplayBar() {
BossBar bossBar = Bukkit.getBossBar(bossBarKey); BossBar bossBar = Bukkit.getBossBar(bossBarKey);
if (bossBar != null) { if (bossBar != null) {
bossBar.removeAll(); bossBar.removeAll();
} }
Bukkit.removeBossBar(bossBarKey); Bukkit.removeBossBar(bossBarKey);
} }
public BossBar createNewDisplayBar() { public BossBar createNewDisplayBar() {
return Bukkit.createBossBar(bossBarKey, String.format("%d -- Attackers -Siege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints), BarColor.YELLOW, BarStyle.SOLID); return Bukkit.createBossBar(bossBarKey, String.format("%d -- Attackers -Siege Score- Defenders -- %d", this.attackerPoints, this.defenderPoints), BarColor.YELLOW, BarStyle.SOLID);
} }
public int getAttackerPoints() { public int getAttackerPoints() {
return this.attackerPoints; return this.attackerPoints;
} }
public int getDefenderPoints() { public void setAttackerPoints(int points) {
return this.defenderPoints; this.attackerPoints = points;
} }
public int getMaxSiegeTicks() { public int getDefenderPoints() {
return maxSiegeTicks; return this.defenderPoints;
} }
public void setSiegeTicks(int siegeTicks) { public void setDefenderPoints(int points) {
this.siegeTicks = siegeTicks; this.defenderPoints = points;
} }
public TownBlock getHomeBlock() { public int getMaxSiegeTicks() {
return homeBlock; return maxSiegeTicks;
} }
public void setHomeBlock(TownBlock homeBlock) { public TownBlock getHomeBlock() {
this.homeBlock = homeBlock; return homeBlock;
} }
public Location getTownSpawn() { public void setHomeBlock(TownBlock homeBlock) {
return townSpawn; this.homeBlock = homeBlock;
} }
public void setTownSpawn(Location townSpawn) { public Location getTownSpawn() {
this.townSpawn = townSpawn; return townSpawn;
} }
public void setAttackerPoints(int points) { public void setTownSpawn(Location townSpawn) {
this.attackerPoints = points; this.townSpawn = townSpawn;
} }
public void setDefenderPoints(int points) { public boolean getSide1AreAttackers() {
this.defenderPoints = points; return this.side1AreAttackers;
} }
public boolean getSide1AreAttackers() { public void setSide1AreAttackers(final boolean side1AreAttackers) {
return this.side1AreAttackers; this.side1AreAttackers = side1AreAttackers;
} }
public void setSide1AreAttackers(final boolean side1AreAttackers) { public ArrayList<String> getAttackerPlayers() {
this.side1AreAttackers = side1AreAttackers; return this.attackerPlayers;
} }
public ArrayList<String> getAttackerPlayers() { public void setAttackerPlayer(final ArrayList<String> attackerPlayers) {
return this.attackerPlayers; this.attackerPlayers = attackerPlayers;
} }
public void setAttackerPlayer(final ArrayList<String> attackerPlayers) { public ArrayList<String> getDefenderPlayers() {
this.attackerPlayers = attackerPlayers; return this.defenderPlayers;
} }
public ArrayList<String> getDefenderPlayers() { public void setDefenderPlayer(final ArrayList<String> defenderPlayers) {
return this.defenderPlayers; this.defenderPlayers = this.attackerPlayers;
} }
public void setDefenderPlayer(final ArrayList<String> defenderPlayers) {
this.defenderPlayers = this.attackerPlayers;
}
public int getSiegeTicks() { public int getSiegeTicks() {
return siegeTicks; return siegeTicks;
} }
public void setSiegeTicks(int siegeTicks) {
this.siegeTicks = siegeTicks;
}
public OfflinePlayer getSiegeLeader() { public OfflinePlayer getSiegeLeader() {
return siegeLeader; return siegeLeader;
} }
public void save() { public void save() {
SiegeData.saveSiege(this); SiegeData.saveSiege(this);
} }
public String getName() { public String getName() {
return this.getWar().getName() + "-" + this.getTown(); return this.getWar().getName() + "-" + this.getTown();
} }
} }
@@ -1,51 +1,68 @@
package me.ShermansWorld.AlathraWar; package me.ShermansWorld.AlathraWar;
import java.io.File;
import java.util.ArrayList;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Nation; import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident; import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.Town;
import me.ShermansWorld.AlathraWar.commands.CommandHelper; import me.ShermansWorld.AlathraWar.commands.CommandHelper;
import me.ShermansWorld.AlathraWar.data.DataManager; import me.ShermansWorld.AlathraWar.data.DataManager;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import java.io.File;
import java.util.ArrayList;
public class War { public class War {
// Object Fields // Object Fields
private String name; private String name;
private String side1; private String side1;
private String side2; private String side2;
private ArrayList<String> side1Towns = new ArrayList<String>(); private ArrayList<String> side1Towns = new ArrayList<>();
private ArrayList<String> side2Towns = new ArrayList<String>(); private ArrayList<String> side2Towns = new ArrayList<>();
private ArrayList<String> surrenderedTowns = new ArrayList<String>(); private ArrayList<String> surrenderedTowns = new ArrayList<>();
private int side1Points = 0; private int side1Points = 0;
private int side2Points = 0; private int side2Points = 0;
// References // References
private ArrayList<Siege> sieges = new ArrayList<Siege>(); private final ArrayList<Siege> sieges = new ArrayList<>();
private ArrayList<Raid> raids = new ArrayList<Raid>(); private final ArrayList<Raid> raids = new ArrayList<>();
private int lastRaidTimeSide1 = 0; private int lastRaidTimeSide1 = 0;
private int lastRaidTimeSide2 = 0; private int lastRaidTimeSide2 = 0;
/** /**
* War Constructor * War Constructor
* @param name - Name of war *
* @param name - Name of war
* @param side1 - Side 1 name * @param side1 - Side 1 name
* @param side2 - Side 2 name * @param side2 - Side 2 name
*/ */
public War(final String name, final String side1, final String side2) { public War(final String name, final String side1, final String side2) {
this.name = name; this.name = name;
this.side1 = side1; this.side1 = side1;
this.side2 = side2; this.side2 = side2;
} }
private static ArrayList<String> townListToPlayers(ArrayList<String> townList) {
ArrayList<String> returnList = new ArrayList<>();
for (String townString : townList) {
Town town = TownyAPI.getInstance().getTown(townString);
if (town != null) {
for (Resident res : town.getResidents()) {
//Minuteman countermeasure! if they are they get skipped
if (CommandHelper.isPlayerMinuteman(res.getName()) == 0) {
returnList.add(res.getName());
}
}
}
}
return returnList;
}
/** /**
* Add a nation to a side of the war * Add a nation to a side of the war
*
* @param nation - Nation object * @param nation - Nation object
* @param side - Side name * @param side - Side name
*/ */
public void addNation(final Nation nation, String side) { public void addNation(final Nation nation, String side) {
for (Town town : nation.getTowns()) { for (Town town : nation.getTowns()) {
@@ -55,6 +72,7 @@ public class War {
/** /**
* Add a town to a side of the war * Add a town to a side of the war
*
* @param town - Town object * @param town - Town object
* @param side - Side name * @param side - Side name
*/ */
@@ -64,32 +82,34 @@ public class War {
/** /**
* Add a town to a side of the war * Add a town to a side of the war
*
* @param town - Town object * @param town - Town object
* @param side - Side name * @param side - Side name
*/ */
public void addTown(final String town, String side) { public void addTown(final String town, String side) {
if (side1.equalsIgnoreCase(side)) { if (side1.equalsIgnoreCase(side)) {
if (!side1Towns.contains(town.toLowerCase())) { if (!side1Towns.contains(town.toLowerCase())) {
side1Towns.add(town.toLowerCase()); side1Towns.add(town.toLowerCase());
Main.warLogger.log("Town "+ town + " joined " + this.name + " on " + side); Main.warLogger.log("Town " + town + " joined " + this.name + " on " + side);
return; return;
} }
} else if(side2.equalsIgnoreCase(side)) { } else if (side2.equalsIgnoreCase(side)) {
if (!side2Towns.contains(town.toLowerCase())) { if (!side2Towns.contains(town.toLowerCase())) {
side2Towns.add(town.toLowerCase()); side2Towns.add(town.toLowerCase());
Main.warLogger.log("Town "+ town + " joined " + this.name + " on " + side); Main.warLogger.log("Town " + town + " joined " + this.name + " on " + side);
return; return;
} }
} }
Main.warLogger.log("Town "+ town + " failed to join " + this.name + " on " + side); Main.warLogger.log("Town " + town + " failed to join " + this.name + " on " + side);
} }
/** /**
* Surrenders town * Surrenders town
*
* @param nation - Nation to surrender * @param nation - Nation to surrender
*/ */
public void surrenderNation(Nation nation) { public void surrenderNation(Nation nation) {
if(nation != null) { if (nation != null) {
for (Town town : nation.getTowns()) { for (Town town : nation.getTowns()) {
surrenderTown(town.getName()); surrenderTown(town.getName());
} }
@@ -98,6 +118,7 @@ public class War {
/** /**
* Surrenders town * Surrenders town
*
* @param town - Town to surrender * @param town - Town to surrender
*/ */
public void surrenderTown(String town) { public void surrenderTown(String town) {
@@ -108,6 +129,7 @@ public class War {
/** /**
* unsurrender town, perfidy time * unsurrender town, perfidy time
*
* @param nation - Nation to unsurrender * @param nation - Nation to unsurrender
*/ */
public void unSurrenderNation(Nation nation) { public void unSurrenderNation(Nation nation) {
@@ -118,6 +140,7 @@ public class War {
/** /**
* unsurrender town, perfidy time * unsurrender town, perfidy time
*
* @param town - Town to unsurrender * @param town - Town to unsurrender
*/ */
public void unSurrenderTown(String town) { public void unSurrenderTown(String town) {
@@ -130,6 +153,7 @@ public class War {
* 0 - None * 0 - None
* 1 - Side 1 * 1 - Side 1
* 2 - Side 2 * 2 - Side 2
*
* @param string town * @param string town
* @return result * @return result
*/ */
@@ -152,33 +176,47 @@ public class War {
return getSide(town.getName()); return getSide(town.getName());
} }
public String getName() { public String getName() {
return this.name; return this.name;
} }
public String getSide1() { public void setName(String name) {
return this.side1; DataManager.deleteFile("wars" + File.separator + this.getName() + ".yml");
} this.name = name;
this.save();
}
public String getSide2() { public String getSide1() {
return this.side2; return this.side1;
} }
public ArrayList<String> getSide1Towns() { public void setSide1(String side1) {
return this.side1Towns; this.side1 = side1;
} }
public void setSide1Towns(final ArrayList<String> side1Towns) { public String getSide2() {
this.side1Towns = side1Towns; return this.side2;
} }
public ArrayList<String> getSide2Towns() { public void setSide2(String side2) {
return this.side2Towns; this.side2 = side2;
} }
public void setSide2Towns(final ArrayList<String> side2Towns) { public ArrayList<String> getSide1Towns() {
this.side2Towns = side2Towns; return this.side1Towns;
} }
public void setSide1Towns(final ArrayList<String> side1Towns) {
this.side1Towns = side1Towns;
}
public ArrayList<String> getSide2Towns() {
return this.side2Towns;
}
public void setSide2Towns(final ArrayList<String> side2Towns) {
this.side2Towns = side2Towns;
}
public ArrayList<String> getSurrenderedTowns() { public ArrayList<String> getSurrenderedTowns() {
return surrenderedTowns; return surrenderedTowns;
@@ -204,20 +242,6 @@ public class War {
raids.add(raid); raids.add(raid);
} }
public void setName(String name) {
DataManager.deleteFile("wars" + File.separator + this.getName() + ".yml");
this.name = name;
this.save();
}
public void setSide1(String side1) {
this.side1 = side1;
}
public void setSide2(String side2) {
this.side2 = side2;
}
/** /**
* Saves the war into .yml file folders. * Saves the war into .yml file folders.
*/ */
@@ -227,8 +251,8 @@ public class War {
public String toString() { public String toString() {
return name + "[" + side1 + "." + side2 + "](" return name + "[" + side1 + "." + side2 + "]("
+ side1Towns.size() + "/" + side2Towns.size() + "/" + + side1Towns.size() + "/" + side2Towns.size() + "/" +
surrenderedTowns.size() + ")"; surrenderedTowns.size() + ")";
} }
public ArrayList<String> getSide1Players() { public ArrayList<String> getSide1Players() {
@@ -239,59 +263,43 @@ public class War {
return townListToPlayers(side2Towns); return townListToPlayers(side2Towns);
} }
private static ArrayList<String> townListToPlayers(ArrayList<String> townList) { public int getLastRaidTimeSide1() {
ArrayList<String> returnList = new ArrayList<String>(); return this.lastRaidTimeSide1;
for (String townString : townList) {
Town town = TownyAPI.getInstance().getTown(townString);
if (town != null) {
for (Resident res : town.getResidents()) {
//Minuteman countermeasure! if they are they get skipped
if (CommandHelper.isPlayerMinuteman(res.getName()) == 0) {
returnList.add(res.getName());
}
}
}
}
return returnList;
} }
public void setLastRaidTimeSide1(int lastRaidTime) { public void setLastRaidTimeSide1(int lastRaidTime) {
this.lastRaidTimeSide1 = lastRaidTime; this.lastRaidTimeSide1 = lastRaidTime;
} }
public int getLastRaidTimeSide1() { public int getLastRaidTimeSide2() {
return this.lastRaidTimeSide1; return this.lastRaidTimeSide2;
} }
public void setLastRaidTimeSide2(int lastRaidTime) { public void setLastRaidTimeSide2(int lastRaidTime) {
this.lastRaidTimeSide2 = lastRaidTime; this.lastRaidTimeSide2 = lastRaidTime;
} }
public int getLastRaidTimeSide2() {
return this.lastRaidTimeSide2;
}
public int getSide1Points() { public int getSide1Points() {
return this.side1Points; return this.side1Points;
} }
public int getSide2Points() {
return this.side2Points;
}
public void addSide1Points(int points) {
side1Points += points;
}
public void addSide2Points(int points){
side2Points += points;
}
public void setSide1Points(int side1Points) { public void setSide1Points(int side1Points) {
this.side1Points = side1Points; this.side1Points = side1Points;
} }
public int getSide2Points() {
return this.side2Points;
}
public void setSide2Points(int side2Points) { public void setSide2Points(int side2Points) {
this.side2Points = side2Points; this.side2Points = side2Points;
} }
public void addSide1Points(int points) {
side1Points += points;
}
public void addSide2Points(int points) {
side2Points += points;
}
} }
@@ -21,6 +21,7 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
@@ -35,136 +36,24 @@ public class AdminCommands implements CommandExecutor {
plugin.getCommand("awa").setExecutor(this); plugin.getCommand("awa").setExecutor(this);
} }
/**
* //done
* //edit war/event in real time, side can be "both" to effect both
* -modify raid score [war] [town] [value]
* -modify raid townspawn [war] [town] (x) (Z)
* -modify raid gather [war] [town] [town]
* -modify raid phase [war] [town] [phase] //"next" to move to next phase
* -modify raid loot [war] [town] (x) (z) [value,looted,ticks,reset] [amt] //no coords just does current chunk, reset deletes it from the list
* -modify raid time [war] [town] [add/set] [value]
* -modify raid owner [war] [town] [add/set] [value]
* -modify raid move [war] [town] [newWar] //low priority, moves raid to other war
* -modify raid clearActive [war] [town] //low priority
* <p>
* -modify siege score [war] [town] [side] [amt]
* -modify siege homeblock [war] [town] (x) (Z)
* -modify siege time [war] [town] [add/set/max] [value] //max modified the max length
* -modify siege owner [war] [town] [add/set] [value]
* -modify siege move [war] [town] [newWar] //low priority, moves siege to other war
* <p>
* -modify war score [war] [side] [amt]
* -modify war side [war] [side] [name]
* -modify war name [war] [name]
* -modify war add town [war] [town]
* -modify war add nation [war] [nation]
* -modify war surrender town [war] [town] //adds town to surrender list
* -modify war surrender nation [war] [town] //adds all towns to surrender list
* -modify war raidTime [add,set,reset] [war] [town] [amt] //set when last raid was
* <p>
* // low priority idea
* -info war score [war]
* -info war surrenderedTowns [war]
* -info war raids [war]
* -info war sieges [war]
* -info war towns [war]
* -info war lastRaidTime [war]
* <p>
* -info raid homeblock [war] [town]
* -info raid lootedTownBlocks [war] [town]
* -info raid timeSinceLastRaid [town]
* <p>
* -info siege homeblock [war] [town]
* <p>
* //done
* //force make event or war, if owner isnt defined, idk havent decided
* -create siege [war] [town] (owner)
* -create raid [war] [raidTown] (gatherTown) (owner)
* -create war [name] [side1] [side2]
* <p>
* //force end a war/event, can declare winner side, or no winner
* -force end war [war] (side/victor)
* -force end siege [war] [town] (side/victor)
* -force end raid [war] [town] (side/victor)
* <p>
* //done
* //force player into or out of a war/event
* -force join war [player] [war] [side]
* -force join siege [player] [war] [town] (side)
* -force join raid [player] [war] [town] (side)
* <p>
* //done
* -force leave raid [war] [player] (timeout) //kicks from raid party
* <p>
* // Ultra low priority idea
* -rule raidersRespawnAtGatherTown [true/false]
* -rule siegersRespawnAtTown [true/false]
* -rule anyoneCanJoinRaid [true/false]
*
* @param sender Source of the command
* @param command Command which was executed
* @param label Alias of the command which was used
* @param args Passed command arguments
* @return Valid command
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
CommandHelper.logCommand(sender, label, args);
if (!sender.hasPermission("AlathraWar.admin")) {
return fail(sender, args, "permissions");
}
if (args.length == 0) {
return fail(sender, args, "syntax");
} else if (args.length >= 1) {
if (args[0].equalsIgnoreCase("create")) {
return create(sender, args);
} else if (args[0].equalsIgnoreCase("force")) {
return force(sender, args);
} else if (args[0].equalsIgnoreCase("help")) {
return help(sender, args);
} else if (args[0].equalsIgnoreCase("info")) {
return info(sender, args);
} else if (args[0].equalsIgnoreCase("modify")) {
return modify(sender, args);
} else if (args[0].equalsIgnoreCase("awa")) {
return awa(sender, args);
} else if (args[0].equalsIgnoreCase("purgebars")) {
return purgebars(sender, args);
} else if (args[0].equalsIgnoreCase("save")) {
return save(sender, args);
} else if (args[0].equalsIgnoreCase("save-all")) {
return saveAll(sender, args);
} else if (args[0].equalsIgnoreCase("load")) {
return load(sender, args);
} else if (args[0].equalsIgnoreCase("load-all")) {
return loadAll(sender, args);
} else if (args[0].equalsIgnoreCase("item")) {
return item(sender, args);
}
}
return true;
}
private static boolean item(CommandSender sender, String[] args) { private static boolean item(CommandSender sender, String[] args) {
if(args.length >= 2) { if (args.length >= 2) {
//find item //find item
ItemStack stack = null; ItemStack stack;
if(args[1].contains(Main.getInstance().getName().toLowerCase())) { if (args[1].contains(Main.getInstance().getName().toLowerCase())) {
stack = WarItemRegistry.getInstance().getOrNullNamespace(args[1]); stack = WarItemRegistry.getInstance().getOrNullNamespace(args[1]);
} else { } else {
stack = WarItemRegistry.getInstance().getOrNull(args[1]); stack = WarItemRegistry.getInstance().getOrNull(args[1]);
} }
// item not real! // item not real!
if(stack == null) { if (stack == null) {
sender.sendMessage(Helper.chatLabel() + Helper.color("&cNot an AlathraWar item.")); sender.sendMessage(Helper.chatLabel() + Helper.color("&cNot an AlathraWar item."));
return true; return true;
} }
//amount parameter //amount parameter
int amt = stack.getAmount(); int amt = stack.getAmount();
if(args.length >= 3) { if (args.length >= 3) {
try { try {
amt = Integer.parseInt(args[2]); amt = Integer.parseInt(args[2]);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
@@ -175,8 +64,8 @@ public class AdminCommands implements CommandExecutor {
stack.setAmount(amt); stack.setAmount(amt);
//determine who gets the item //determine who gets the item
Player reciever = null; Player reciever;
if(args.length >= 4) { if (args.length >= 4) {
reciever = Bukkit.getPlayer(args[3]); reciever = Bukkit.getPlayer(args[3]);
} else { } else {
//console cant get item //console cant get item
@@ -208,7 +97,7 @@ public class AdminCommands implements CommandExecutor {
private static boolean purgebars(CommandSender sender, String[] args) { private static boolean purgebars(CommandSender sender, String[] args) {
for (Iterator<KeyedBossBar> it = Bukkit.getBossBars(); it.hasNext(); ) { for (Iterator<KeyedBossBar> it = Bukkit.getBossBars(); it.hasNext(); ) {
KeyedBossBar b = it.next(); KeyedBossBar b = it.next();
if(b.getKey().getNamespace().equalsIgnoreCase(Main.getInstance().getName())) { if (b.getKey().getNamespace().equalsIgnoreCase(Main.getInstance().getName())) {
b.setVisible(false); b.setVisible(false);
b.removeAll(); b.removeAll();
Bukkit.removeBossBar(b.getKey()); Bukkit.removeBossBar(b.getKey());
@@ -222,9 +111,9 @@ public class AdminCommands implements CommandExecutor {
} }
private static boolean save(CommandSender sender, String[] args) { private static boolean save(CommandSender sender, String[] args) {
if(args.length >= 2) { if (args.length >= 2) {
for (War w : WarData.getWars()) { for (War w : WarData.getWars()) {
if(w.getName().equalsIgnoreCase(args[2])) { if (w.getName().equalsIgnoreCase(args[2])) {
WarData.saveWar(w); WarData.saveWar(w);
sender.sendMessage(Helper.chatLabel() + Helper.color("&cForced Save of war: " + w.getName())); sender.sendMessage(Helper.chatLabel() + Helper.color("&cForced Save of war: " + w.getName()));
return true; return true;
@@ -276,7 +165,7 @@ public class AdminCommands implements CommandExecutor {
private static boolean loadAll(CommandSender sender, String[] args) { private static boolean loadAll(CommandSender sender, String[] args) {
if (args.length >= 2) { if (args.length >= 2) {
if(Boolean.parseBoolean(args[1])) { if (Boolean.parseBoolean(args[1])) {
for (War w : WarData.getWars()) { for (War w : WarData.getWars()) {
//kill raids //kill raids
for (Raid raid : w.getRaids()) { for (Raid raid : w.getRaids()) {
@@ -301,7 +190,6 @@ public class AdminCommands implements CommandExecutor {
return true; return true;
} }
/** /**
* //force make event or war, if owner isn't defined, idk haven't decided * //force make event or war, if owner isn't defined, idk haven't decided
* -create siege [war] [town] (owner) * -create siege [war] [town] (owner)
@@ -316,12 +204,11 @@ public class AdminCommands implements CommandExecutor {
//using same method so that this doesnt get fucked up if we go back and change original implementation //using same method so that this doesnt get fucked up if we go back and change original implementation
RaidCommands.startRaid(p, args, true); RaidCommands.startRaid(p, args, true);
p.sendMessage(Helper.color("&cForcefully started raid from the console.")); p.sendMessage(Helper.color("&cForcefully started raid from the console."));
return true;
} else { } else {
//defaultCode will bypass the custom gather town to force set owner //defaultCode will bypass the custom gather town to force set owner
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create raid [war] [raidTown] (gatherTown/\"defaultCode\") (owner) (override)")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create raid [war] [raidTown] (gatherTown/\"defaultCode\") (owner) (override)"));
return true;
} }
return true;
} else if (args[1].equalsIgnoreCase("siege")) { } else if (args[1].equalsIgnoreCase("siege")) {
//this exists to force a seige with a new owner //this exists to force a seige with a new owner
if (args.length >= 4) { if (args.length >= 4) {
@@ -329,16 +216,15 @@ public class AdminCommands implements CommandExecutor {
l.add("start"); l.add("start");
l.add(args[2]); l.add(args[2]);
l.add(args[3]); l.add(args[3]);
if(args.length >= 5) l.add(args[4]); if (args.length >= 5) l.add(args[4]);
if(args.length >= 6) l.add(args[5]); if (args.length >= 6) l.add(args[5]);
SiegeCommands.siegeStart(p, l.toArray(new String[]{}), true); SiegeCommands.siegeStart(p, l.toArray(new String[]{}), true);
// p.sendMessage(Helper.Chatlabel() + "Try again later!"); // p.sendMessage(Helper.Chatlabel() + "Try again later!");
p.sendMessage(Helper.color("&cForcefully started siege from the console.")); p.sendMessage(Helper.color("&cForcefully started siege from the console."));
return true;
} else { } else {
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create siege [war] [town] (owner) (force)")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create siege [war] [town] (owner) (force)"));
return true;
} }
return true;
} else if (args[1].equalsIgnoreCase("war")) { } else if (args[1].equalsIgnoreCase("war")) {
//this command basically is a copy or /war create //this command basically is a copy or /war create
if (args.length == 5) { if (args.length == 5) {
@@ -351,11 +237,10 @@ public class AdminCommands implements CommandExecutor {
}; };
WarCommands.warCreate(p, adjusted); WarCommands.warCreate(p, adjusted);
p.sendMessage(Helper.color("&cForcefully started war from the console.")); p.sendMessage(Helper.color("&cForcefully started war from the console."));
return true;
} else { } else {
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create war [name] [side1] [side2]")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin create war [name] [side1] [side2]"));
return true;
} }
return true;
} }
} else { } else {
return fail(p, args, "syntax"); return fail(p, args, "syntax");
@@ -375,7 +260,7 @@ public class AdminCommands implements CommandExecutor {
* -force leave raid [war] [player] (timeout) //kicks from raid party * -force leave raid [war] [player] (timeout) //kicks from raid party
* -force surrender war [name] [town] * -force surrender war [name] [town]
* *
* @param p player * @param p player
* @param args args * @param args args
* @return result * @return result
*/ */
@@ -541,11 +426,10 @@ public class AdminCommands implements CommandExecutor {
WarCommands.warJoin(p, adjusted, true); WarCommands.warJoin(p, adjusted, true);
p.sendMessage(Helper.color("&cForced " + args[3] + " to join the war " + args[4] + " on side " + args[5])); p.sendMessage(Helper.color("&cForced " + args[3] + " to join the war " + args[4] + " on side " + args[5]));
Main.warLogger.log("Forced " + args[3] + " to join the war " + args[4] + " on side " + args[5]); Main.warLogger.log("Forced " + args[3] + " to join the war " + args[4] + " on side " + args[5]);
return true;
} else { } else {
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin force join war [player] [war] [side]")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin force join war [player] [war] [side]"));
return true;
} }
return true;
} else { } else {
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin force join [raid/siege/war]")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin force join [raid/siege/war]"));
return true; return true;
@@ -627,7 +511,7 @@ public class AdminCommands implements CommandExecutor {
* <p> * <p>
* -info siege [war] [town] * -info siege [war] [town]
* *
* @param p player * @param p player
* @param args args * @param args args
* @return result * @return result
*/ */
@@ -658,8 +542,10 @@ public class AdminCommands implements CommandExecutor {
side1Players.append(", "); side1Players.append(", ");
} }
//cut off last two characters //cut off last two characters
if(side1Towns.length() > 2) side1Towns = new StringBuilder(side1Towns.substring(0, side1Towns.length() - 2)); if (side1Towns.length() > 2)
if(side1Players.length() > 2) side1Players = new StringBuilder(side1Players.substring(0, side1Players.length() - 2)); side1Towns = new StringBuilder(side1Towns.substring(0, side1Towns.length() - 2));
if (side1Players.length() > 2)
side1Players = new StringBuilder(side1Players.substring(0, side1Players.length() - 2));
p.sendMessage(Helper.chatLabel() + w.getSide1() + " Towns: " + side1Towns); p.sendMessage(Helper.chatLabel() + w.getSide1() + " Towns: " + side1Towns);
p.sendMessage(Helper.chatLabel() + w.getSide1() + " Players: " + side1Players); p.sendMessage(Helper.chatLabel() + w.getSide1() + " Players: " + side1Players);
@@ -675,19 +561,15 @@ public class AdminCommands implements CommandExecutor {
side2Players.append(", "); side2Players.append(", ");
} }
//cut off last two characters //cut off last two characters
if(side2Towns.length() > 2) side2Towns = new StringBuilder(side2Towns.substring(0, side2Towns.length() - 2)); if (side2Towns.length() > 2)
if(side2Players.length() > 2) side2Players = new StringBuilder(side2Players.substring(0, side2Players.length() - 2)); side2Towns = new StringBuilder(side2Towns.substring(0, side2Towns.length() - 2));
if (side2Players.length() > 2)
side2Players = new StringBuilder(side2Players.substring(0, side2Players.length() - 2));
p.sendMessage(Helper.chatLabel() + w.getSide2() + " Towns: " + side2Towns); p.sendMessage(Helper.chatLabel() + w.getSide2() + " Towns: " + side2Towns);
p.sendMessage(Helper.chatLabel() + w.getSide2() + " Players: " + side2Players); p.sendMessage(Helper.chatLabel() + w.getSide2() + " Players: " + side2Players);
p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo"); p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo");
StringBuilder surrenderedTowns = new StringBuilder(); final StringBuilder surrenderedTowns = getSurrenderedTowns(w);
for (String t : w.getSurrenderedTowns()) {
surrenderedTowns.append(t);
surrenderedTowns.append(", ");
}
//cut off last two characters
if(surrenderedTowns.length() > 2) surrenderedTowns = new StringBuilder(surrenderedTowns.substring(0, surrenderedTowns.length() - 2));
p.sendMessage(Helper.chatLabel() + "Surrendered Towns: " + surrenderedTowns); p.sendMessage(Helper.chatLabel() + "Surrendered Towns: " + surrenderedTowns);
return true; return true;
} }
@@ -718,23 +600,11 @@ public class AdminCommands implements CommandExecutor {
p.sendMessage(Helper.chatLabel() + "Gather Homeblock: " + (r.getHomeBlockGather() == null ? "NONE" : r.getHomeBlockGather().toString())); p.sendMessage(Helper.chatLabel() + "Gather Homeblock: " + (r.getHomeBlockGather() == null ? "NONE" : r.getHomeBlockGather().toString()));
p.sendMessage(Helper.chatLabel() + "Raided Homeblock: " + (r.getHomeBlockRaided() == null ? "NONE" : r.getHomeBlockRaided().toString())); p.sendMessage(Helper.chatLabel() + "Raided Homeblock: " + (r.getHomeBlockRaided() == null ? "NONE" : r.getHomeBlockRaided().toString()));
p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo"); p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo");
StringBuilder activeRaiders = new StringBuilder(); final StringBuilder activeRaiders = getActiveRaiders(r);
for (String pl : r.getActiveRaiders()) {
activeRaiders.append(pl);
activeRaiders.append(", ");
}
//cut off last two characters
if(activeRaiders.length() > 2) activeRaiders = new StringBuilder(activeRaiders.substring(0, activeRaiders.length() - 2));
p.sendMessage(Helper.chatLabel() + "Raiding Players: " + activeRaiders); p.sendMessage(Helper.chatLabel() + "Raiding Players: " + activeRaiders);
p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo"); p.sendMessage(Helper.chatLabel() + "oOo------------===------------oOo");
StringBuilder defenderPlayers = new StringBuilder(); final StringBuilder defenderPlayers = getDefenderPlayers(r);
for (String pl : r.getDefenderPlayers()) {
defenderPlayers.append(pl);
defenderPlayers.append(", ");
}
//cut off last two characters
if(defenderPlayers.length() > 2) defenderPlayers = new StringBuilder(defenderPlayers.substring(0, defenderPlayers.length() - 2));
p.sendMessage(Helper.chatLabel() + "Defending Players: " + defenderPlayers); p.sendMessage(Helper.chatLabel() + "Defending Players: " + defenderPlayers);
return true; return true;
} }
@@ -768,7 +638,8 @@ public class AdminCommands implements CommandExecutor {
attackers.append(", "); attackers.append(", ");
} }
//cut off last two characters //cut off last two characters
if(attackers.length() > 2) attackers = new StringBuilder(attackers.substring(0, attackers.length() - 2)); if (attackers.length() > 2)
attackers = new StringBuilder(attackers.substring(0, attackers.length() - 2));
p.sendMessage(Helper.chatLabel() + "Attacking Players: " + attackers); p.sendMessage(Helper.chatLabel() + "Attacking Players: " + attackers);
StringBuilder defenders = new StringBuilder(); StringBuilder defenders = new StringBuilder();
for (String pl : s.getDefenderPlayers()) { for (String pl : s.getDefenderPlayers()) {
@@ -776,7 +647,8 @@ public class AdminCommands implements CommandExecutor {
defenders.append(", "); defenders.append(", ");
} }
//cut off last two characters //cut off last two characters
if(defenders.length() > 2) defenders = new StringBuilder(defenders.substring(0, defenders.length() - 2)); if (defenders.length() > 2)
defenders = new StringBuilder(defenders.substring(0, defenders.length() - 2));
p.sendMessage(Helper.chatLabel() + "Defending Players: " + defenders); p.sendMessage(Helper.chatLabel() + "Defending Players: " + defenders);
return true; return true;
} }
@@ -793,6 +665,45 @@ public class AdminCommands implements CommandExecutor {
return fail(p, args, "syntax"); return fail(p, args, "syntax");
} }
@NotNull
private static StringBuilder getDefenderPlayers(Raid r) {
StringBuilder defenderPlayers = new StringBuilder();
for (String pl : r.getDefenderPlayers()) {
defenderPlayers.append(pl);
defenderPlayers.append(", ");
}
//cut off last two characters
if (defenderPlayers.length() > 2)
defenderPlayers = new StringBuilder(defenderPlayers.substring(0, defenderPlayers.length() - 2));
return defenderPlayers;
}
@NotNull
private static StringBuilder getActiveRaiders(Raid r) {
StringBuilder activeRaiders = new StringBuilder();
for (String pl : r.getActiveRaiders()) {
activeRaiders.append(pl);
activeRaiders.append(", ");
}
//cut off last two characters
if (activeRaiders.length() > 2)
activeRaiders = new StringBuilder(activeRaiders.substring(0, activeRaiders.length() - 2));
return activeRaiders;
}
@NotNull
private static StringBuilder getSurrenderedTowns(War w) {
StringBuilder surrenderedTowns = new StringBuilder();
for (String t : w.getSurrenderedTowns()) {
surrenderedTowns.append(t);
surrenderedTowns.append(", ");
}
//cut off last two characters
if (surrenderedTowns.length() > 2)
surrenderedTowns = new StringBuilder(surrenderedTowns.substring(0, surrenderedTowns.length() - 2));
return surrenderedTowns;
}
/** /**
* //edit war/event in real time, side can be "both" to effect both * //edit war/event in real time, side can be "both" to effect both
* -modify raid score [add/set] [war] [town] [value] * -modify raid score [add/set] [war] [town] [value]
@@ -820,7 +731,7 @@ public class AdminCommands implements CommandExecutor {
* -modify war surrender nation [war] [town] //adds all towns to surrender list * -modify war surrender nation [war] [town] //adds all towns to surrender list
* -modify war raidTime [add,set,reset] [war] [town] [amt] //set when last raid was * -modify war raidTime [add,set,reset] [war] [town] [amt] //set when last raid was
* *
* @param p player * @param p player
* @param args args * @param args args
* @return result * @return result
*/ */
@@ -832,8 +743,8 @@ public class AdminCommands implements CommandExecutor {
if (args.length >= 8) { if (args.length >= 8) {
for (Raid r : RaidData.getRaids()) { for (Raid r : RaidData.getRaids()) {
if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) { if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) {
if(args[6].equalsIgnoreCase(r.getWar().getSide1())) { if (args[6].equalsIgnoreCase(r.getWar().getSide1())) {
if(r.getSide1AreRaiders()) { if (r.getSide1AreRaiders()) {
if (args[5].equalsIgnoreCase("add")) { if (args[5].equalsIgnoreCase("add")) {
r.addPointsToRaiderScore(Integer.parseInt(args[7])); r.addPointsToRaiderScore(Integer.parseInt(args[7]));
p.sendMessage(Helper.chatLabel() + "Added " + args[7] + " points to the raid score in the war " + args[3] + " on town " + args[4]); p.sendMessage(Helper.chatLabel() + "Added " + args[7] + " points to the raid score in the war " + args[3] + " on town " + args[4]);
@@ -874,8 +785,8 @@ public class AdminCommands implements CommandExecutor {
return true; return true;
} }
} }
} else if(args[6].equalsIgnoreCase(r.getWar().getSide2())) { } else if (args[6].equalsIgnoreCase(r.getWar().getSide2())) {
if(!r.getSide1AreRaiders()) { if (!r.getSide1AreRaiders()) {
if (args[5].equalsIgnoreCase("add")) { if (args[5].equalsIgnoreCase("add")) {
r.addPointsToRaiderScore(Integer.parseInt(args[7])); r.addPointsToRaiderScore(Integer.parseInt(args[7]));
p.sendMessage(Helper.chatLabel() + "Added " + args[7] + " points to the raid score in the war " + args[3] + " on town " + args[4]); p.sendMessage(Helper.chatLabel() + "Added " + args[7] + " points to the raid score in the war " + args[3] + " on town " + args[4]);
@@ -937,7 +848,7 @@ public class AdminCommands implements CommandExecutor {
} }
Town t = r.getRaidedTown(); Town t = r.getRaidedTown();
if (args.length >= 8) { if (args.length >= 8) {
if(!(p instanceof Player runner)) { if (!(p instanceof Player runner)) {
p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!"); p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!");
return true; return true;
} }
@@ -949,7 +860,7 @@ public class AdminCommands implements CommandExecutor {
t.setSpawn(new Location(runner.getWorld(), Double.parseDouble(args[5]), Double.parseDouble(args[6]), Double.parseDouble(args[7]))); t.setSpawn(new Location(runner.getWorld(), Double.parseDouble(args[5]), Double.parseDouble(args[6]), Double.parseDouble(args[7])));
r.setHomeBlockRaided(tb.getTownBlock()); r.setHomeBlockRaided(tb.getTownBlock());
r.setTownSpawnRaided(t.getSpawn()); r.setTownSpawnRaided(t.getSpawn());
p.sendMessage(Helper.chatLabel() + "Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); p.sendMessage(Helper.chatLabel() + "Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
Main.warLogger.log("Set town spawn for raided town " + args[4] + " in war " + args[3] + " to [" + args[5] + "," + args[6] + "," + args[7] + "]"); Main.warLogger.log("Set town spawn for raided town " + args[4] + " in war " + args[3] + " to [" + args[5] + "," + args[6] + "," + args[7] + "]");
return finalizeRaid(r); return finalizeRaid(r);
} else { } else {
@@ -968,7 +879,7 @@ public class AdminCommands implements CommandExecutor {
return true; return true;
} }
} else { } else {
if(!(p instanceof Player runner)) { if (!(p instanceof Player runner)) {
p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!"); p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!");
return true; return true;
} }
@@ -980,8 +891,8 @@ public class AdminCommands implements CommandExecutor {
t.setSpawn(runner.getLocation()); t.setSpawn(runner.getLocation());
r.setHomeBlockRaided(tb.getTownBlock()); r.setHomeBlockRaided(tb.getTownBlock());
r.setTownSpawnRaided(t.getSpawn()); r.setTownSpawnRaided(t.getSpawn());
p.sendMessage(Helper.chatLabel() + "Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); p.sendMessage(Helper.chatLabel() + "Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
Main.warLogger.log("Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); Main.warLogger.log("Set town spawn for raided town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
return finalizeRaid(r); return finalizeRaid(r);
} else { } else {
p.sendMessage(Helper.color("&cTown does not contain town block at your location [" + (int) runner.getLocation().getX() + "," + (int) runner.getLocation().getZ() + "]")); p.sendMessage(Helper.color("&cTown does not contain town block at your location [" + (int) runner.getLocation().getX() + "," + (int) runner.getLocation().getZ() + "]"));
@@ -1069,7 +980,7 @@ public class AdminCommands implements CommandExecutor {
for (Raid r : RaidData.getRaids()) { for (Raid r : RaidData.getRaids()) {
if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) { if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) {
//parse phase //parse phase
if(!(p instanceof Player runner)) { if (!(p instanceof Player runner)) {
p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!"); p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!");
return true; return true;
} }
@@ -1082,7 +993,7 @@ public class AdminCommands implements CommandExecutor {
if (args[5].equalsIgnoreCase("value")) { if (args[5].equalsIgnoreCase("value")) {
WorldCoord wc = WorldCoord.parseWorldCoord(runner.getWorld().getName(), (int) Double.parseDouble(args[7]), (int) Double.parseDouble(args[8])); WorldCoord wc = WorldCoord.parseWorldCoord(runner.getWorld().getName(), (int) Double.parseDouble(args[7]), (int) Double.parseDouble(args[8]));
Raid.LootBlock lb = r.getLootedChunks().get(wc); Raid.LootBlock lb = r.getLootedChunks().get(wc);
if(lb == null) { if (lb == null) {
r.addLootedChunk(wc); r.addLootedChunk(wc);
lb = r.getLootedChunks().get(wc); lb = r.getLootedChunks().get(wc);
p.sendMessage(Helper.chatLabel() + "Created empty loot chunk data to modify"); p.sendMessage(Helper.chatLabel() + "Created empty loot chunk data to modify");
@@ -1095,7 +1006,7 @@ public class AdminCommands implements CommandExecutor {
WorldCoord wc = WorldCoord.parseWorldCoord(runner.getWorld().getName(), (int) Double.parseDouble(args[7]), (int) Double.parseDouble(args[8])); WorldCoord wc = WorldCoord.parseWorldCoord(runner.getWorld().getName(), (int) Double.parseDouble(args[7]), (int) Double.parseDouble(args[8]));
Raid.LootBlock lb = r.getLootedChunks().get(wc); Raid.LootBlock lb = r.getLootedChunks().get(wc);
//The base value can be abjusted //The base value can be abjusted
if(!lb.finished && Boolean.parseBoolean(args[6])) { if (!lb.finished && Boolean.parseBoolean(args[6])) {
lb.value = new Random().nextDouble() * 100; lb.value = new Random().nextDouble() * 100;
//score for looting //score for looting
r.addPointsToRaiderScore(10); r.addPointsToRaiderScore(10);
@@ -1205,7 +1116,7 @@ public class AdminCommands implements CommandExecutor {
if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) { if (r.getWar().getName().equalsIgnoreCase(args[3]) && r.getRaidedTown().getName().equalsIgnoreCase(args[4])) {
Player own = Bukkit.getPlayer(args[5]); Player own = Bukkit.getPlayer(args[5]);
if (own != null) { if (own != null) {
if(r.getActiveRaiders().contains(own.getName())) { if (r.getActiveRaiders().contains(own.getName())) {
r.setOwner(own); r.setOwner(own);
p.sendMessage(Helper.chatLabel() + "Set owner of raid against " + args[4] + " in war " + args[3] + " to " + own.getName()); p.sendMessage(Helper.chatLabel() + "Set owner of raid against " + args[4] + " in war " + args[3] + " to " + own.getName());
Main.warLogger.log("Set owner of raid against " + args[4] + " in war " + args[3] + " to " + own.getName()); Main.warLogger.log("Set owner of raid against " + args[4] + " in war " + args[3] + " to " + own.getName());
@@ -1317,7 +1228,7 @@ public class AdminCommands implements CommandExecutor {
} }
Town t = s.getTown(); Town t = s.getTown();
if (args.length >= 8) { if (args.length >= 8) {
if(!(p instanceof Player runner)) { if (!(p instanceof Player runner)) {
p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!"); p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!");
return true; return true;
} }
@@ -1329,7 +1240,7 @@ public class AdminCommands implements CommandExecutor {
t.setSpawn(new Location(runner.getWorld(), (int) Double.parseDouble(args[5]), (int) Double.parseDouble(args[6]), (int) Double.parseDouble(args[7]))); t.setSpawn(new Location(runner.getWorld(), (int) Double.parseDouble(args[5]), (int) Double.parseDouble(args[6]), (int) Double.parseDouble(args[7])));
s.setHomeBlock(tb.getTownBlock()); s.setHomeBlock(tb.getTownBlock());
s.setTownSpawn(t.getSpawn()); s.setTownSpawn(t.getSpawn());
p.sendMessage(Helper.chatLabel() + "Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); p.sendMessage(Helper.chatLabel() + "Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
Main.warLogger.log("Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to [" + args[5] + "," + args[6] + "," + args[7] + "]"); Main.warLogger.log("Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to [" + args[5] + "," + args[6] + "," + args[7] + "]");
return finalizeSiege(s); return finalizeSiege(s);
} else { } else {
@@ -1349,7 +1260,7 @@ public class AdminCommands implements CommandExecutor {
} }
} else { } else {
if(!(p instanceof Player runner)) { if (!(p instanceof Player runner)) {
p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!"); p.sendMessage(Helper.chatLabel() + "This command cannot be run through console!");
return true; return true;
} }
@@ -1361,8 +1272,8 @@ public class AdminCommands implements CommandExecutor {
t.setSpawn(runner.getLocation()); t.setSpawn(runner.getLocation());
s.setHomeBlock(tb.getTownBlock()); s.setHomeBlock(tb.getTownBlock());
s.setTownSpawn(t.getSpawn()); s.setTownSpawn(t.getSpawn());
p.sendMessage(Helper.chatLabel() + "Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); p.sendMessage(Helper.chatLabel() + "Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
Main.warLogger.log("Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation().toString()); Main.warLogger.log("Set town spawn for sieged town " + args[4] + " in war " + args[3] + " to " + runner.getLocation());
return finalizeSiege(s); return finalizeSiege(s);
} else { } else {
p.sendMessage(Helper.color("&cTown does not contain town block at your location [" + (int) runner.getLocation().getX() + "," + (int) runner.getLocation().getZ() + "]")); p.sendMessage(Helper.color("&cTown does not contain town block at your location [" + (int) runner.getLocation().getX() + "," + (int) runner.getLocation().getZ() + "]"));
@@ -1457,14 +1368,14 @@ public class AdminCommands implements CommandExecutor {
if (args.length >= 7) { if (args.length >= 7) {
for (War w : WarData.getWars()) { for (War w : WarData.getWars()) {
if (w.getName().equalsIgnoreCase(args[3])) { if (w.getName().equalsIgnoreCase(args[3])) {
if(args[4].equalsIgnoreCase(w.getSide1())) { if (args[4].equalsIgnoreCase(w.getSide1())) {
if (args[5].equalsIgnoreCase("add")) { if (args[5].equalsIgnoreCase("add")) {
w.addSide1Points(Integer.parseInt(args[6])); w.addSide1Points(Integer.parseInt(args[6]));
p.sendMessage(Helper.chatLabel() + "Added " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Added " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]);
Main.warLogger.log("Added " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]); Main.warLogger.log("Added " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]);
return finalizeWar(w); return finalizeWar(w);
} else if (args[5].equalsIgnoreCase("subtract")) { } else if (args[5].equalsIgnoreCase("subtract")) {
w.addSide1Points(- Integer.parseInt(args[6])); w.addSide1Points(-Integer.parseInt(args[6]));
p.sendMessage(Helper.chatLabel() + "Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]);
Main.warLogger.log("Subtracted " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]); Main.warLogger.log("Subtracted " + args[6] + " points to the raid war in the war " + args[3] + " on side " + args[4]);
return finalizeWar(w); return finalizeWar(w);
@@ -1477,14 +1388,14 @@ public class AdminCommands implements CommandExecutor {
p.sendMessage(Helper.color("&cUsage: /alathrawaradmin modify war score [war] [side] [add/subtract/set] [amt]")); p.sendMessage(Helper.color("&cUsage: /alathrawaradmin modify war score [war] [side] [add/subtract/set] [amt]"));
return true; return true;
} }
} else if(args[4].equalsIgnoreCase(w.getSide2())) { } else if (args[4].equalsIgnoreCase(w.getSide2())) {
if (args[5].equalsIgnoreCase("add")) { if (args[5].equalsIgnoreCase("add")) {
w.addSide2Points(Integer.parseInt(args[6])); w.addSide2Points(Integer.parseInt(args[6]));
p.sendMessage(Helper.chatLabel() + "Added " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Added " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]);
Main.warLogger.log("Added " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]); Main.warLogger.log("Added " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]);
return finalizeWar(w); return finalizeWar(w);
} else if (args[5].equalsIgnoreCase("subtract")) { } else if (args[5].equalsIgnoreCase("subtract")) {
w.addSide2Points(- Integer.parseInt(args[6])); w.addSide2Points(-Integer.parseInt(args[6]));
p.sendMessage(Helper.chatLabel() + "Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]);
Main.warLogger.log("Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]); Main.warLogger.log("Subtracted " + args[6] + " points to the war score in the war " + args[3] + " on side " + args[4]);
return finalizeWar(w); return finalizeWar(w);
@@ -1563,22 +1474,22 @@ public class AdminCommands implements CommandExecutor {
if (args[5].equalsIgnoreCase("town")) { if (args[5].equalsIgnoreCase("town")) {
Town t = TownyAPI.getInstance().getTown(args[6]); Town t = TownyAPI.getInstance().getTown(args[6]);
if (t != null) { if (t != null) {
if(args.length >= 8) { if (args.length >= 8) {
//forceful add, ignore surrender and override it if the town is //forceful add, ignore surrender and override it if the town is
if(Boolean.parseBoolean(args[7])) { if (Boolean.parseBoolean(args[7])) {
//if we already have surrendered //if we already have surrendered
if(w.getSurrenderedTowns().contains(args[6].toLowerCase())) { if (w.getSurrenderedTowns().contains(args[6].toLowerCase())) {
w.unSurrenderTown(args[6]); w.unSurrenderTown(args[6]);
p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + args[6]); p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + args[6]);
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]);
} }
if(w.getSide1().equalsIgnoreCase(args[4])) { if (w.getSide1().equalsIgnoreCase(args[4])) {
if(w.getSide2Towns().remove(args[6])) { if (w.getSide2Towns().remove(args[6])) {
p.sendMessage(Helper.chatLabel() + "Removed town " + args[6] + " from side " + w.getSide2()); p.sendMessage(Helper.chatLabel() + "Removed town " + args[6] + " from side " + w.getSide2());
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]);
} }
} else if(w.getSide2().equalsIgnoreCase(args[4])) { } else if (w.getSide2().equalsIgnoreCase(args[4])) {
if(w.getSide1Towns().remove(args[6])) { if (w.getSide1Towns().remove(args[6])) {
p.sendMessage(Helper.chatLabel() + "Removed town " + args[6] + " from side " + w.getSide2()); p.sendMessage(Helper.chatLabel() + "Removed town " + args[6] + " from side " + w.getSide2());
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[6]);
} }
@@ -1606,23 +1517,23 @@ public class AdminCommands implements CommandExecutor {
} else if (args[5].equalsIgnoreCase("nation")) { } else if (args[5].equalsIgnoreCase("nation")) {
Nation n = TownyAPI.getInstance().getNation(args[6]); Nation n = TownyAPI.getInstance().getNation(args[6]);
if (n != null) { if (n != null) {
if(args.length >= 8) { if (args.length >= 8) {
//forceful add, ignore surrender and override it if the town is //forceful add, ignore surrender and override it if the town is
if(Boolean.parseBoolean(args[7])) { if (Boolean.parseBoolean(args[7])) {
//if we already have surrendered //if we already have surrendered
for(Town t : n.getTowns()) { for (Town t : n.getTowns()) {
if(w.getSurrenderedTowns().contains(t.getName().toLowerCase())) { if (w.getSurrenderedTowns().contains(t.getName().toLowerCase())) {
w.unSurrenderTown(t.getName()); w.unSurrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Unsurrendered town " + t.getName()); p.sendMessage(Helper.chatLabel() + "Unsurrendered town " + t.getName());
Main.warLogger.log(Helper.chatLabel() + "Unsurrendered town " + t.getName()); Main.warLogger.log(Helper.chatLabel() + "Unsurrendered town " + t.getName());
} }
if(w.getSide1().equalsIgnoreCase(args[4])) { if (w.getSide1().equalsIgnoreCase(args[4])) {
if(w.getSide2Towns().remove(t.getName())) { if (w.getSide2Towns().remove(t.getName())) {
p.sendMessage(Helper.chatLabel() + "Removed town " + t.getName() + " from side " + w.getSide2()); p.sendMessage(Helper.chatLabel() + "Removed town " + t.getName() + " from side " + w.getSide2());
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + t.getName()); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + t.getName());
} }
} else if(w.getSide2().equalsIgnoreCase(args[4])) { } else if (w.getSide2().equalsIgnoreCase(args[4])) {
if(w.getSide1Towns().remove(t.getName())) { if (w.getSide1Towns().remove(t.getName())) {
p.sendMessage(Helper.chatLabel() + "Removed town " + t.getName() + " from side " + w.getSide2()); p.sendMessage(Helper.chatLabel() + "Removed town " + t.getName() + " from side " + w.getSide2());
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + t.getName()); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + t.getName());
} }
@@ -1631,7 +1542,7 @@ public class AdminCommands implements CommandExecutor {
} }
} }
for(Town t : n.getTowns()) { for (Town t : n.getTowns()) {
// Side checks // Side checks
int side = w.getSide(t.getName().toLowerCase()); int side = w.getSide(t.getName().toLowerCase());
if (side == -1) { if (side == -1) {
@@ -1671,7 +1582,7 @@ public class AdminCommands implements CommandExecutor {
if (args[4].equalsIgnoreCase("town")) { if (args[4].equalsIgnoreCase("town")) {
Town t = TownyAPI.getInstance().getTown(args[5]); Town t = TownyAPI.getInstance().getTown(args[5]);
if (t != null) { if (t != null) {
if(w.getSurrenderedTowns().contains(args[5].toLowerCase())) { if (w.getSurrenderedTowns().contains(args[5].toLowerCase())) {
w.unSurrenderTown(args[5]); w.unSurrenderTown(args[5]);
p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + args[5]); p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + args[5]);
Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[5]); Main.warLogger.log(Helper.chatLabel() + "Un-surrendered town " + args[5]);
@@ -1688,7 +1599,7 @@ public class AdminCommands implements CommandExecutor {
} else if (args[4].equalsIgnoreCase("nation")) { } else if (args[4].equalsIgnoreCase("nation")) {
Nation n = TownyAPI.getInstance().getNation(args[5]); Nation n = TownyAPI.getInstance().getNation(args[5]);
if (n != null) { if (n != null) {
for(Town t : n.getTowns()) { for (Town t : n.getTowns()) {
if (w.getSurrenderedTowns().contains(t.getName().toLowerCase())) { if (w.getSurrenderedTowns().contains(t.getName().toLowerCase())) {
w.unSurrenderTown(t.getName()); w.unSurrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + t.getName()); p.sendMessage(Helper.chatLabel() + "Un-surrendered town " + t.getName());
@@ -1729,12 +1640,12 @@ public class AdminCommands implements CommandExecutor {
if (args[5].equalsIgnoreCase("town")) { if (args[5].equalsIgnoreCase("town")) {
Town t = TownyAPI.getInstance().getTown(args[6]); Town t = TownyAPI.getInstance().getTown(args[6]);
if (t != null) { if (t != null) {
if(w.getSide1Towns().contains(t.getName().toLowerCase()) && w.getSide1().equalsIgnoreCase(args[4])) { if (w.getSide1Towns().contains(t.getName().toLowerCase()) && w.getSide1().equalsIgnoreCase(args[4])) {
w.surrenderTown(t.getName()); w.surrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]);
Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]); Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]);
return finalizeWar(w); return finalizeWar(w);
} else if(w.getSide2Towns().contains(t.getName().toLowerCase()) && w.getSide2().equalsIgnoreCase(args[4])) { } else if (w.getSide2Towns().contains(t.getName().toLowerCase()) && w.getSide2().equalsIgnoreCase(args[4])) {
w.surrenderTown(t.getName()); w.surrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]);
Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]); Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + args[6] + " war " + args[3] + " on side " + args[4]);
@@ -1757,12 +1668,12 @@ public class AdminCommands implements CommandExecutor {
Nation n = TownyAPI.getInstance().getNation(args[6]); Nation n = TownyAPI.getInstance().getNation(args[6]);
if (n != null) { if (n != null) {
for (Town t : n.getTowns()) { for (Town t : n.getTowns()) {
if(w.getSide1Towns().contains(t.getName().toLowerCase()) && w.getSide1().equalsIgnoreCase(args[4])) { if (w.getSide1Towns().contains(t.getName().toLowerCase()) && w.getSide1().equalsIgnoreCase(args[4])) {
w.surrenderTown(t.getName()); w.surrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]);
Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]); Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]);
} else if(w.getSide2Towns().contains(t.getName().toLowerCase()) && w.getSide2().equalsIgnoreCase(args[4])) { } else if (w.getSide2Towns().contains(t.getName().toLowerCase()) && w.getSide2().equalsIgnoreCase(args[4])) {
w.surrenderTown(t.getName()); w.surrenderTown(t.getName());
p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]); p.sendMessage(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]);
Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]); Main.warLogger.log(Helper.chatLabel() + "Forcefully surrendered town " + t.getName() + " war " + args[3] + " on side " + args[4]);
@@ -1940,7 +1851,7 @@ public class AdminCommands implements CommandExecutor {
p.chat("awa awa! ^.^ UwU"); p.chat("awa awa! ^.^ UwU");
return true; return true;
} }
if(sender instanceof Player) if (sender instanceof Player)
((Player) sender).chat("awa awa! ^.^ UwU"); ((Player) sender).chat("awa awa! ^.^ UwU");
return true; return true;
} }
@@ -1948,7 +1859,7 @@ public class AdminCommands implements CommandExecutor {
private static boolean fail(CommandSender p, String[] args, String type) { private static boolean fail(CommandSender p, String[] args, String type) {
switch (type) { switch (type) {
case "permissions" -> { case "permissions" -> {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou do not have permission to do this.")); p.sendMessage(Helper.chatLabel() + Helper.color("&cYou do not have permission to do this."));
return true; return true;
} }
case "syntax" -> { case "syntax" -> {
@@ -1977,4 +1888,116 @@ public class AdminCommands implements CommandExecutor {
return true; return true;
} }
/**
* //done
* //edit war/event in real time, side can be "both" to effect both
* -modify raid score [war] [town] [value]
* -modify raid townspawn [war] [town] (x) (Z)
* -modify raid gather [war] [town] [town]
* -modify raid phase [war] [town] [phase] //"next" to move to next phase
* -modify raid loot [war] [town] (x) (z) [value,looted,ticks,reset] [amt] //no coords just does current chunk, reset deletes it from the list
* -modify raid time [war] [town] [add/set] [value]
* -modify raid owner [war] [town] [add/set] [value]
* -modify raid move [war] [town] [newWar] //low priority, moves raid to other war
* -modify raid clearActive [war] [town] //low priority
* <p>
* -modify siege score [war] [town] [side] [amt]
* -modify siege homeblock [war] [town] (x) (Z)
* -modify siege time [war] [town] [add/set/max] [value] //max modified the max length
* -modify siege owner [war] [town] [add/set] [value]
* -modify siege move [war] [town] [newWar] //low priority, moves siege to other war
* <p>
* -modify war score [war] [side] [amt]
* -modify war side [war] [side] [name]
* -modify war name [war] [name]
* -modify war add town [war] [town]
* -modify war add nation [war] [nation]
* -modify war surrender town [war] [town] //adds town to surrender list
* -modify war surrender nation [war] [town] //adds all towns to surrender list
* -modify war raidTime [add,set,reset] [war] [town] [amt] //set when last raid was
* <p>
* // low priority idea
* -info war score [war]
* -info war surrenderedTowns [war]
* -info war raids [war]
* -info war sieges [war]
* -info war towns [war]
* -info war lastRaidTime [war]
* <p>
* -info raid homeblock [war] [town]
* -info raid lootedTownBlocks [war] [town]
* -info raid timeSinceLastRaid [town]
* <p>
* -info siege homeblock [war] [town]
* <p>
* //done
* //force make event or war, if owner isnt defined, idk havent decided
* -create siege [war] [town] (owner)
* -create raid [war] [raidTown] (gatherTown) (owner)
* -create war [name] [side1] [side2]
* <p>
* //force end a war/event, can declare winner side, or no winner
* -force end war [war] (side/victor)
* -force end siege [war] [town] (side/victor)
* -force end raid [war] [town] (side/victor)
* <p>
* //done
* //force player into or out of a war/event
* -force join war [player] [war] [side]
* -force join siege [player] [war] [town] (side)
* -force join raid [player] [war] [town] (side)
* <p>
* //done
* -force leave raid [war] [player] (timeout) //kicks from raid party
* <p>
* // Ultra low priority idea
* -rule raidersRespawnAtGatherTown [true/false]
* -rule siegersRespawnAtTown [true/false]
* -rule anyoneCanJoinRaid [true/false]
*
* @param sender Source of the command
* @param command Command which was executed
* @param label Alias of the command which was used
* @param args Passed command arguments
* @return Valid command
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
CommandHelper.logCommand(sender, label, args);
if (!sender.hasPermission("AlathraWar.admin")) {
return fail(sender, args, "permissions");
}
if (args.length == 0) {
return fail(sender, args, "syntax");
} else {
if (args[0].equalsIgnoreCase("create")) {
return create(sender, args);
} else if (args[0].equalsIgnoreCase("force")) {
return force(sender, args);
} else if (args[0].equalsIgnoreCase("help")) {
return help(sender, args);
} else if (args[0].equalsIgnoreCase("info")) {
return info(sender, args);
} else if (args[0].equalsIgnoreCase("modify")) {
return modify(sender, args);
} else if (args[0].equalsIgnoreCase("awa")) {
return awa(sender, args);
} else if (args[0].equalsIgnoreCase("purgebars")) {
return purgebars(sender, args);
} else if (args[0].equalsIgnoreCase("save")) {
return save(sender, args);
} else if (args[0].equalsIgnoreCase("save-all")) {
return saveAll(sender, args);
} else if (args[0].equalsIgnoreCase("load")) {
return load(sender, args);
} else if (args[0].equalsIgnoreCase("load-all")) {
return loadAll(sender, args);
} else if (args[0].equalsIgnoreCase("item")) {
return item(sender, args);
}
}
return true;
}
} }
@@ -11,8 +11,7 @@ import java.util.List;
public class AdminTabCompletion implements TabCompleter { public class AdminTabCompletion implements TabCompleter {
List<String> base = List.of(new String[]{ List<String> base = List.of("create",
"create",
"force", "force",
"help", "help",
"info", "info",
@@ -22,8 +21,7 @@ public class AdminTabCompletion implements TabCompleter {
"load-all", "load-all",
"save", "save",
"save-all", "save-all",
"item" "item");
});
List<String> type = List.of(new String[]{ List<String> type = List.of(new String[]{
"raid", "raid",
@@ -194,7 +192,7 @@ public class AdminTabCompletion implements TabCompleter {
if (args[0].equalsIgnoreCase("purgebars")) { if (args[0].equalsIgnoreCase("purgebars")) {
return empty; return empty;
} else if (args[0].equalsIgnoreCase("save")) { } else if (args[0].equalsIgnoreCase("save")) {
if(args.length > 2) { if (args.length > 2) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]);
@@ -202,7 +200,7 @@ public class AdminTabCompletion implements TabCompleter {
} else if (args[0].equalsIgnoreCase("save-all")) { } else if (args[0].equalsIgnoreCase("save-all")) {
return empty; return empty;
} else if (args[0].equalsIgnoreCase("load")) { } else if (args[0].equalsIgnoreCase("load")) {
if(args.length > 2) { if (args.length > 2) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]);
@@ -210,9 +208,9 @@ public class AdminTabCompletion implements TabCompleter {
} else if (args[0].equalsIgnoreCase("load-all")) { } else if (args[0].equalsIgnoreCase("load-all")) {
return empty; return empty;
} else if (args[0].equalsIgnoreCase("item")) { } else if (args[0].equalsIgnoreCase("item")) {
if(args.length > 2) { if (args.length > 2) {
if(args.length > 3) { if (args.length > 3) {
if(args.length > 4) { if (args.length > 4) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(CommandHelper.getPlayers(), args[3]); return NameUtil.filterByStart(CommandHelper.getPlayers(), args[3]);
@@ -223,7 +221,7 @@ public class AdminTabCompletion implements TabCompleter {
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarItems(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarItems(), args[1]);
} }
} else if (args[0].equalsIgnoreCase("create")) { } else if (args[0].equalsIgnoreCase("create")) {
if (args.length > 2) { if (args.length > 2) {
switch (args[1]) { switch (args[1]) {
case "raid" -> { case "raid" -> {
@@ -323,7 +321,7 @@ public class AdminTabCompletion implements TabCompleter {
if (args.length > 8) { if (args.length > 8) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(List.of(new String[] { "true","false" }), args[7]); return NameUtil.filterByStart(List.of(new String[]{"true", "false"}), args[7]);
} }
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[6]); return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[6]);
@@ -345,7 +343,7 @@ public class AdminTabCompletion implements TabCompleter {
if (args.length > 8) { if (args.length > 8) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(List.of(new String[] { "true","false" }), args[7]); return NameUtil.filterByStart(List.of(new String[]{"true", "false"}), args[7]);
} }
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[6]); return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[6]);
@@ -366,7 +364,7 @@ public class AdminTabCompletion implements TabCompleter {
if (args.length > 7) { if (args.length > 7) {
return empty; return empty;
} else { } else {
return NameUtil.filterByStart(List.of(new String[] { "true","false" }), args[6]); return NameUtil.filterByStart(List.of(new String[]{"true", "false"}), args[6]);
} }
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[5]); return NameUtil.filterByStart(CommandHelper.getWarSides(args[4]), args[5]);
@@ -488,19 +486,19 @@ public class AdminTabCompletion implements TabCompleter {
} }
} }
case "townspawn" -> { case "townspawn" -> {
if(sender instanceof Player) { if (sender instanceof Player) {
if (args.length > 6) { if (args.length > 6) {
if (args.length > 7) { if (args.length > 7) {
if (args.length > 8) { if (args.length > 8) {
return empty; return empty;
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getZ())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getZ())});
} }
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getY())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getY())});
} }
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getX())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getX())});
} }
} }
} }
@@ -525,10 +523,10 @@ public class AdminTabCompletion implements TabCompleter {
if (args.length > 9) { if (args.length > 9) {
return empty; return empty;
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getZ())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getZ())});
} }
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getX())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getX())});
} }
} else { } else {
return empty; return empty;
@@ -575,13 +573,13 @@ public class AdminTabCompletion implements TabCompleter {
if (args.length > 8) { if (args.length > 8) {
return empty; return empty;
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getZ())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getZ())});
} }
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getY())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getY())});
} }
} else { } else {
return List.of(new String[]{String.valueOf(((Player)sender).getLocation().getX())}); return List.of(new String[]{String.valueOf(((Player) sender).getLocation().getX())});
} }
} }
case "owner" -> { case "owner" -> {
@@ -650,7 +648,7 @@ public class AdminTabCompletion implements TabCompleter {
case "raidTimeWar" -> { case "raidTimeWar" -> {
if (args.length > 4) { if (args.length > 4) {
if (args.length > 5) { if (args.length > 5) {
if(args[3].equalsIgnoreCase("reset")) { if (args[3].equalsIgnoreCase("reset")) {
if (args.length > 6) { if (args.length > 6) {
return empty; return empty;
} else { } else {
@@ -25,6 +25,7 @@ public class CommandHelper {
/** /**
* Grabs list of all war names * Grabs list of all war names
*
* @return list of wars * @return list of wars
*/ */
public static List<String> getWarNames() { public static List<String> getWarNames() {
@@ -37,13 +38,14 @@ public class CommandHelper {
/** /**
* Grabs first matching war and lists the sides * Grabs first matching war and lists the sides
*
* @param name name of war * @param name name of war
* @return side of war * @return side of war
*/ */
public static List<String> getWarSides(String name) { public static List<String> getWarSides(String name) {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
for (War w : WarData.getWars()) { for (War w : WarData.getWars()) {
if(w.getName().equalsIgnoreCase(name)) { if (w.getName().equalsIgnoreCase(name)) {
out.add(w.getSide1()); out.add(w.getSide1());
out.add(w.getSide2()); out.add(w.getSide2());
break; break;
@@ -73,9 +75,9 @@ public class CommandHelper {
public static List<String> getTownyWarTowns(String war) { public static List<String> getTownyWarTowns(String war) {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
War w = WarData.getWar(war); War w = WarData.getWar(war);
if(w == null) return Collections.emptyList(); if (w == null) return Collections.emptyList();
for (Town t : TownyAPI.getInstance().getTowns()) { for (Town t : TownyAPI.getInstance().getTowns()) {
if(w.getSide2Towns().contains(t.getName().toLowerCase()) || w.getSide1Towns().contains(t.getName().toLowerCase())) { if (w.getSide2Towns().contains(t.getName().toLowerCase()) || w.getSide1Towns().contains(t.getName().toLowerCase())) {
out.add(t.getName()); out.add(t.getName());
} }
} }
@@ -90,10 +92,10 @@ public class CommandHelper {
public static List<String> getTownyWarNations(String war) { public static List<String> getTownyWarNations(String war) {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
War w = WarData.getWar(war); War w = WarData.getWar(war);
if(w == null) return Collections.emptyList(); if (w == null) return Collections.emptyList();
for (Town t : TownyAPI.getInstance().getTowns()) { for (Town t : TownyAPI.getInstance().getTowns()) {
if(w.getSide2Towns().contains(t.getName().toLowerCase()) || w.getSide1Towns().contains(t.getName().toLowerCase())) { if (w.getSide2Towns().contains(t.getName().toLowerCase()) || w.getSide1Towns().contains(t.getName().toLowerCase())) {
if(t.hasNation()) { if (t.hasNation()) {
try { try {
out.add(t.getNation().getName()); out.add(t.getNation().getName());
} catch (NotRegisteredException e) { } catch (NotRegisteredException e) {
@@ -113,14 +115,14 @@ public class CommandHelper {
public static List<String> getTownyWarTowns(String war, String side) { public static List<String> getTownyWarTowns(String war, String side) {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
War w = WarData.getWar(war); War w = WarData.getWar(war);
if(w == null) return Collections.emptyList(); if (w == null) return Collections.emptyList();
for (Town t : TownyAPI.getInstance().getTowns()) { for (Town t : TownyAPI.getInstance().getTowns()) {
if(side.equalsIgnoreCase(w.getSide1())) { if (side.equalsIgnoreCase(w.getSide1())) {
if(w.getSide1Towns().contains(t.getName().toLowerCase())) { if (w.getSide1Towns().contains(t.getName().toLowerCase())) {
out.add(t.getName()); out.add(t.getName());
} }
} else if(side.equalsIgnoreCase(w.getSide2())) { } else if (side.equalsIgnoreCase(w.getSide2())) {
if(w.getSide2Towns().contains(t.getName().toLowerCase())) { if (w.getSide2Towns().contains(t.getName().toLowerCase())) {
out.add(t.getName()); out.add(t.getName());
} }
} }
@@ -130,6 +132,7 @@ public class CommandHelper {
/** /**
* return list of all towns in a raid * return list of all towns in a raid
*
* @return list of all towns involved in a raid * @return list of all towns involved in a raid
*/ */
public static List<String> getRaidTowns() { public static List<String> getRaidTowns() {
@@ -142,6 +145,7 @@ public class CommandHelper {
/** /**
* return list of all towns in a siege * return list of all towns in a siege
*
* @return list of towns involved in a siege * @return list of towns involved in a siege
*/ */
public static List<String> getSiegeTowns() { public static List<String> getSiegeTowns() {
@@ -161,8 +165,8 @@ public class CommandHelper {
List<String> out = new ArrayList<>(); List<String> out = new ArrayList<>();
for (Town t : TownyAPI.getInstance().getTowns()) { for (Town t : TownyAPI.getInstance().getTowns()) {
Nation n = t.getNationOrNull(); Nation n = t.getNationOrNull();
if(n != null) { if (n != null) {
if(!out.contains(n.getName())) { if (!out.contains(n.getName())) {
out.add(n.getName()); out.add(n.getName());
} }
} }
@@ -172,6 +176,7 @@ public class CommandHelper {
/** /**
* get a list of all online players * get a list of all online players
*
* @return list of all players online * @return list of all players online
*/ */
public static List<String> getPlayers() { public static List<String> getPlayers() {
@@ -185,6 +190,7 @@ public class CommandHelper {
/** /**
* get a list of all raid phases * get a list of all raid phases
*
* @return list of all raid phases * @return list of all raid phases
*/ */
public static List<String> getRaidPhases() { public static List<String> getRaidPhases() {
@@ -196,24 +202,24 @@ public class CommandHelper {
} }
/** /**
*
* @param player player to check * @param player player to check
* @return 0, 1, 2 (good to go, insufficient join, insufficient playtime) * @return 0, 1, 2 (good to go, insufficient join, insufficient playtime)
*/ */
public static int isPlayerMinuteman(String player) { public static int isPlayerMinuteman(String player) {
Resident res = TownyAPI.getInstance().getResident(player); Resident res = TownyAPI.getInstance().getResident(player);
if(res != null) { if (res != null) {
//get registration time //get registration time
long regTime = res.getRegistered(); long regTime = res.getRegistered();
int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE); int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE);
int out = 0; int out = 0;
if(Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) { if (Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
//compare the join date, if they joined less that min age ago it is true //compare the join date, if they joined less that min age ago it is true
if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge")) out = 1; if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge"))
out = 1;
} }
if(Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) { if (Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
//check playtime, if its less than min its true //check playtime, if its less than min its true
if(playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2; if (playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2;
} }
return out; return out;
@@ -224,9 +230,10 @@ public class CommandHelper {
/** /**
* log the command * log the command
*
* @param sender sender * @param sender sender
* @param label command * @param label command
* @param args command args * @param args command args
* @return success * @return success
*/ */
protected static void logCommand(CommandSender sender, String label, String[] args) { protected static void logCommand(CommandSender sender, String label, String[] args) {
@@ -234,11 +241,12 @@ public class CommandHelper {
for (String s : args) { for (String s : args) {
log.append(" ").append(s); log.append(" ").append(s);
} }
Main.warLogger.log(Helper.chatLabel() + sender.getName() + " ran command: " + log.toString()); Main.warLogger.log(Helper.chatLabel() + sender.getName() + " ran command: " + log);
} }
/** /**
* return list of all alathrawar items with namespace * return list of all alathrawar items with namespace
*
* @return list of all alathrawar items namespaced * @return list of all alathrawar items namespaced
*/ */
public static List<String> getWarItems() { public static List<String> getWarItems() {
@@ -3,12 +3,14 @@ package me.ShermansWorld.AlathraWar.commands;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.exceptions.TownyException; import com.palmergames.bukkit.towny.exceptions.TownyException;
import com.palmergames.bukkit.towny.object.*; import com.palmergames.bukkit.towny.object.Town;
import com.palmergames.bukkit.towny.object.TownyWorld;
import com.palmergames.bukkit.towny.object.WorldCoord;
import me.ShermansWorld.AlathraWar.*; import me.ShermansWorld.AlathraWar.*;
import me.ShermansWorld.AlathraWar.data.RaidData;
import me.ShermansWorld.AlathraWar.data.RaidPhase; import me.ShermansWorld.AlathraWar.data.RaidPhase;
import me.ShermansWorld.AlathraWar.data.SiegeData; import me.ShermansWorld.AlathraWar.data.SiegeData;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import me.ShermansWorld.AlathraWar.data.RaidData;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@@ -22,40 +24,7 @@ import java.util.ArrayList;
public class RaidCommands implements CommandExecutor { public class RaidCommands implements CommandExecutor {
public RaidCommands(final Main plugin) { public RaidCommands(final Main plugin) {
plugin.getCommand("raid").setExecutor((CommandExecutor)this); plugin.getCommand("raid").setExecutor(this);
}
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
// final Player p = (Player) sender;
CommandHelper.logCommand(sender, label, args);
if (args.length == 0) {
fail(sender, args, "syntax");
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("list")) {
listRaids(sender, args);
} else if (args[0].equalsIgnoreCase("help")) {
raidHelp(sender, args);
} else {
fail(sender, args, "syntax");
}
}else if (args.length == 3) {
if (args[0].equalsIgnoreCase("start")) {
startRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("stop")) {
stopRaid(sender, args);
} else if (args[0].equalsIgnoreCase("join")) {
joinRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("leave")) {
leaveRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("abandon")) {
abandonRaid(sender, args);
} else {
fail(sender, args, "syntax");
}
} else {
fail(sender, args, "syntax");
}
return true;
} }
/** /**
@@ -73,12 +42,12 @@ public class RaidCommands implements CommandExecutor {
warFound = true; warFound = true;
Player raidOwner = null; Player raidOwner = null;
if((p instanceof Player)) { if ((p instanceof Player)) {
raidOwner = (Player) p; raidOwner = (Player) p;
} }
if(admin && args.length >= 6) { if (admin && args.length >= 6) {
raidOwner = Bukkit.getPlayer(args[5]); raidOwner = Bukkit.getPlayer(args[5]);
if(raidOwner == null) { if (raidOwner == null) {
p.sendMessage("Player Does not exist"); p.sendMessage("Player Does not exist");
return; return;
} }
@@ -92,13 +61,13 @@ public class RaidCommands implements CommandExecutor {
TownyWorld townyWorld; TownyWorld townyWorld;
townyWorld = WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownyWorld(); townyWorld = WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownyWorld();
String side = ""; String side;
if (war.getSide1Players().contains(raidOwner.getName())) { if (war.getSide1Players().contains(raidOwner.getName())) {
side = war.getSide1(); side = war.getSide1();
} else if (war.getSide2Players().contains(raidOwner.getName())) { } else if (war.getSide2Players().contains(raidOwner.getName())) {
side = war.getSide2(); side = war.getSide2();
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You are not in this war! Type /war join [war] [side]"); p.sendMessage(Helper.chatLabel() + "You are not in this war! Type /war join [war] [side]");
return; return;
} }
@@ -115,16 +84,18 @@ public class RaidCommands implements CommandExecutor {
} }
} }
//override? //override?
if(!override) { if (!override) {
if (minuteman != 0) { if (minuteman != 0) {
if (minuteman == 1) { if (minuteman == 1) {
//player has joined to recently //player has joined to recently
if (admin) p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); if (admin)
p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
raidOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); raidOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
return; return;
} else if (minuteman == 2) { } else if (minuteman == 2) {
//player has played too little //player has played too little
if (admin) p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); if (admin)
p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
raidOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); raidOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
return; return;
} }
@@ -133,31 +104,34 @@ public class RaidCommands implements CommandExecutor {
//check if in a town //check if in a town
//takes the command runners town as the gather point //takes the command runners town as the gather point
Town gatherTown = null; Town gatherTown;
try { try {
//if admin, and we have a gather town argument, use it //if admin, and we have a gather town argument, use it
if(admin && args.length >= 5) { if (admin && args.length >= 5) {
if(args[4].equalsIgnoreCase("defaultCode")) { if (args[4].equalsIgnoreCase("defaultCode")) {
//use default behavior //use default behavior
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock()); gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
} else if(TownyAPI.getInstance().getTown(args[4]) != null) { } else if (TownyAPI.getInstance().getTown(args[4]) != null) {
gatherTown = TownyAPI.getInstance().getTown(args[4]); gatherTown = TownyAPI.getInstance().getTown(args[4]);
} else { } else {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "No valid town set for gather town, defaulting to current location"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "No valid town set for gather town, defaulting to current location"); p.sendMessage(Helper.chatLabel() + "No valid town set for gather town, defaulting to current location");
raidOwner.sendMessage(Helper.chatLabel() + "No valid town set for gather town, defaulting to current location");
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock()); gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
} }
} else { } else {
gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock()); gatherTown = TownyAPI.getInstance().getTownOrNull(WorldCoord.parseWorldCoord(raidOwner.getLocation()).getTownBlock());
} }
} catch (NotRegisteredException e2) { } catch (NotRegisteredException e2) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town."); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town."); p.sendMessage(Helper.chatLabel() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
raidOwner.sendMessage(Helper.chatLabel() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
return; return;
} }
if (gatherTown == null) { if (gatherTown == null) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town."); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town."); p.sendMessage(Helper.chatLabel() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
raidOwner.sendMessage(Helper.chatLabel() + "You must be within a town's claim to begin a raid. That town you are in will be the gathering town.");
return; return;
} }
@@ -185,22 +159,25 @@ public class RaidCommands implements CommandExecutor {
} }
//check if the town were attempting to raid is in the war //check if the town were attempting to raid is in the war
if(!war.getSide1Towns().contains(raidedTown.getName().toLowerCase()) && !war.getSide2Towns().contains(raidedTown.getName().toLowerCase())) { if (!war.getSide1Towns().contains(raidedTown.getName().toLowerCase()) && !war.getSide2Towns().contains(raidedTown.getName().toLowerCase())) {
if (war.getSurrenderedTowns().contains(raidedTown.getName().toLowerCase())) { if (war.getSurrenderedTowns().contains(raidedTown.getName().toLowerCase())) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "The town you are trying to raid has already surrendered!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "The town you are trying to raid has already surrendered!"); p.sendMessage(Helper.chatLabel() + "The town you are trying to raid has already surrendered!");
raidOwner.sendMessage(Helper.chatLabel() + "The town you are trying to raid has already surrendered!");
return; return;
} }
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "The town you are trying to raid is not part of the war!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "The town you are trying to raid is not part of the war!"); p.sendMessage(Helper.chatLabel() + "The town you are trying to raid is not part of the war!");
raidOwner.sendMessage(Helper.chatLabel() + "The town you are trying to raid is not part of the war!");
return; return;
} }
// Is being sieged check // Is being sieged check
for (Siege s : SiegeData.getSieges()) { for (Siege s : SiegeData.getSieges()) {
if(s.getTown().getName().equalsIgnoreCase(raidedTown.getName())) { if (s.getTown().getName().equalsIgnoreCase(raidedTown.getName())) {
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "That town is already currently being sieged! Cannot raid at this time!"); raidOwner.sendMessage(Helper.chatLabel() + "That town is already currently being sieged! Cannot raid at this time!");
if(admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "That town is already currently being sieged! Cannot raid at this time!"); if (admin)
p.sendMessage(Helper.chatLabel() + "That town is already currently being sieged! Cannot raid at this time!");
} }
} }
@@ -214,22 +191,26 @@ public class RaidCommands implements CommandExecutor {
//if were admin, see if an owner arg exists, and if so then use it //if were admin, see if an owner arg exists, and if so then use it
raid2 = new Raid(war, raidedTown, gatherTown, true, raidOwner); raid2 = new Raid(war, raidedTown, gatherTown, true, raidOwner);
} else if (c == 1) { } else if (c == 1) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "This town is already being raided at this time!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "This town is already being raided at this time!"); p.sendMessage(Helper.chatLabel() + "This town is already being raided at this time!");
raidOwner.sendMessage(Helper.chatLabel() + "This town is already being raided at this time!");
return; return;
} else if (c == 0) { } else if (c == 0) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Your side has raided too recently!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "Your side has raided too recently!"); p.sendMessage(Helper.chatLabel() + "Your side has raided too recently!");
raidOwner.sendMessage(Helper.chatLabel() + "Your side has raided too recently!");
return; return;
} else if (c == -1) { } else if (c == -1) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "This town was raided too recently!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "This town was raided too recently!"); p.sendMessage(Helper.chatLabel() + "This town was raided too recently!");
raidOwner.sendMessage(Helper.chatLabel() + "This town was raided too recently!");
return; return;
} else if (c == -2) { } else if (c == -2) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "At least on member of the raided town must be online to defend it!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "At least on member of the raided town must be online to defend it!"); p.sendMessage(Helper.chatLabel() + "At least on member of the raided town must be online to defend it!");
raidOwner.sendMessage(Helper.chatLabel() + "At least on member of the raided town must be online to defend it!");
return; return;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} else { } else {
@@ -243,22 +224,26 @@ public class RaidCommands implements CommandExecutor {
if (c == 2) { if (c == 2) {
raid2 = new Raid(war, raidedTown, gatherTown, false, raidOwner); raid2 = new Raid(war, raidedTown, gatherTown, false, raidOwner);
} else if (c == 1) { } else if (c == 1) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "This town is already being raided at this time!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "This town is already being raided at this time!"); p.sendMessage(Helper.chatLabel() + "This town is already being raided at this time!");
raidOwner.sendMessage(Helper.chatLabel() + "This town is already being raided at this time!");
return; return;
} else if (c == 0) { } else if (c == 0) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Your side has raided too recently!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "Your side has raided too recently!"); p.sendMessage(Helper.chatLabel() + "Your side has raided too recently!");
raidOwner.sendMessage(Helper.chatLabel() + "Your side has raided too recently!");
return; return;
} else if (c == -1) { } else if (c == -1) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "This town was raided too recently!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "This town was raided too recently!"); p.sendMessage(Helper.chatLabel() + "This town was raided too recently!");
raidOwner.sendMessage(Helper.chatLabel() + "This town was raided too recently!");
return; return;
} else if (c == -2) { } else if (c == -2) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "At least on member of the raided town must be online to defend it!"); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "At least on member of the raided town must be online to defend it!"); p.sendMessage(Helper.chatLabel() + "At least on member of the raided town must be online to defend it!");
raidOwner.sendMessage(Helper.chatLabel() + "At least on member of the raided town must be online to defend it!");
return; return;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
@@ -286,8 +271,9 @@ public class RaidCommands implements CommandExecutor {
//check player balance //check player balance
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(raidOwner.getUniqueId()); final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(raidOwner.getUniqueId());
if (Main.econ.getBalance(offlinePlayer) <= 1000.0) { if (Main.econ.getBalance(offlinePlayer) <= 1000.0) {
if (admin) p.sendMessage(String.valueOf(Helper.chatLabel()) + "You must have at least $1000 to put up to start a raid."); if (admin)
raidOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "You must have at least $1000 to put up to start a raid."); p.sendMessage(Helper.chatLabel() + "You must have at least $1000 to put up to start a raid.");
raidOwner.sendMessage(Helper.chatLabel() + "You must have at least $1000 to put up to start a raid.");
return; return;
} }
@@ -299,15 +285,15 @@ public class RaidCommands implements CommandExecutor {
WarData.saveWar(raid2.getWar()); WarData.saveWar(raid2.getWar());
//broadcast //broadcast
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "As part of " + war.getName() + ", forces from " + raid2.getRaiderSide() + " are gathering to raid the town of " + raidedTown.getName() + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "As part of " + war.getName() + ", forces from " + raid2.getRaiderSide() + " are gathering to raid the town of " + raidedTown.getName() + "!");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "All players from the defending side have been drafted for the town's defense."); Bukkit.broadcastMessage(Helper.chatLabel() + "All players from the defending side have been drafted for the town's defense.");
Bukkit.broadcastMessage(Helper.chatLabel() + "The raid of " Bukkit.broadcastMessage(Helper.chatLabel() + "The raid of "
+ raidedTown.getName() + " will begin in " + (int) (RaidPhase.TRAVEL.startTick / 20 / 60) + " minutes!"); + raidedTown.getName() + " will begin in " + (RaidPhase.TRAVEL.startTick / 20 / 60) + " minutes!");
Bukkit.broadcastMessage(Helper.chatLabel() + Bukkit.broadcastMessage(Helper.chatLabel() +
"The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!"); "The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!");
Main.warLogger.log(raidOwner.getName() + " started a raid."); Main.warLogger.log(raidOwner.getName() + " started a raid.");
if(admin) Main.warLogger.log(raidOwner.getName() + " started a raid from admin interference."); if (admin) Main.warLogger.log(raidOwner.getName() + " started a raid from admin interference.");
Main.warLogger.log("As part of " + war.getName() + ", forces from " + raid2.getRaiderSide() + " are raiding the town of " + raidedTown.getName() + "!"); Main.warLogger.log("As part of " + war.getName() + ", forces from " + raid2.getRaiderSide() + " are raiding the town of " + raidedTown.getName() + "!");
Main.warLogger.log("The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!"); Main.warLogger.log("The Raiders are gathering at " + gatherTown.getName() + " before making the journey over!");
} }
@@ -346,8 +332,8 @@ public class RaidCommands implements CommandExecutor {
Raid raid = RaidData.getRaidOrNull(args[1] + "-" + args[2]); Raid raid = RaidData.getRaidOrNull(args[1] + "-" + args[2]);
if (raid != null) { if (raid != null) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "raid cancelled"); p.sendMessage(Helper.chatLabel() + "raid cancelled");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The raid of " + raid.getRaidedTown().getName() + " has been cancelled by an admin"); Bukkit.broadcastMessage(Helper.chatLabel() + "The raid of " + raid.getRaidedTown().getName() + " has been cancelled by an admin");
raid.stop(); //this purges itself from raids raid.stop(); //this purges itself from raids
} else { } else {
fail(p, args, "badName"); fail(p, args, "badName");
@@ -360,43 +346,43 @@ public class RaidCommands implements CommandExecutor {
if (raid != null) { if (raid != null) {
if (raid.getWar().getName().equalsIgnoreCase(args[1])) { if (raid.getWar().getName().equalsIgnoreCase(args[1])) {
Player joiner = null; Player joiner = null;
if(p instanceof Player) { if (p instanceof Player) {
joiner = (Player) p; joiner = (Player) p;
} }
if (admin) { if (admin) {
joiner = Bukkit.getPlayer(args[3]); joiner = Bukkit.getPlayer(args[3]);
if(joiner != null) { if (joiner != null) {
if (args[4] != null) { if (args[4] != null) {
if (args[4].equalsIgnoreCase(raid.getDefenderSide())) { if (args[4].equalsIgnoreCase(raid.getDefenderSide())) {
if (!raid.getDefenderPlayers().contains(joiner.getName())) if (!raid.getDefenderPlayers().contains(joiner.getName()))
raid.getDefenderPlayers().add(joiner.getName()); raid.getDefenderPlayers().add(joiner.getName());
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Player " + joiner.getName() + " added to defender side."); p.sendMessage(Helper.chatLabel() + "Player " + joiner.getName() + " added to defender side.");
Main.warLogger.log("Player " + joiner.getName() + " added to defender side."); Main.warLogger.log("Player " + joiner.getName() + " added to defender side.");
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You were forcefully added to the defender side against the raid party on " + raid.getRaidedTown() + " by an admin."); joiner.sendMessage(Helper.chatLabel() + "You were forcefully added to the defender side against the raid party on " + raid.getRaidedTown() + " by an admin.");
return; return;
} else { } else {
if (!raid.getRaiderPlayers().contains(joiner.getName())) if (!raid.getRaiderPlayers().contains(joiner.getName()))
raid.getRaiderPlayers().add(joiner.getName()); raid.getRaiderPlayers().add(joiner.getName());
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Player " + joiner.getName() + " added to raider side."); p.sendMessage(Helper.chatLabel() + "Player " + joiner.getName() + " added to raider side.");
Main.warLogger.log("Player " + joiner.getName() + " added to raider side."); Main.warLogger.log("Player " + joiner.getName() + " added to raider side.");
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You were forcefully added to the raid party on " + raid.getRaidedTown() + " by an admin. Leaving the gather town will remove you from the raid party."); joiner.sendMessage(Helper.chatLabel() + "You were forcefully added to the raid party on " + raid.getRaidedTown() + " by an admin. Leaving the gather town will remove you from the raid party.");
} }
} }
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Player " + args[3] + " not found!"); p.sendMessage(Helper.chatLabel() + "Player " + args[3] + " not found!");
return; return;
} }
} }
if(joiner == null) { if (joiner == null) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Player not found! Is something broken?"); p.sendMessage(Helper.chatLabel() + "Player not found! Is something broken?");
return; return;
} }
if (!raid.getWar().getSide1Players().contains(joiner.getName()) && !raid.getWar().getSide2Players().contains(joiner.getName())) { if (!raid.getWar().getSide1Players().contains(joiner.getName()) && !raid.getWar().getSide2Players().contains(joiner.getName())) {
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You are not in this war! Type /war join [war] [side]"); joiner.sendMessage(Helper.chatLabel() + "You are not in this war! Type /war join [war] [side]");
} }
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime //Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
@@ -412,16 +398,18 @@ public class RaidCommands implements CommandExecutor {
} }
} }
} }
if(!override) { if (!override) {
if (minuteman != 0) { if (minuteman != 0) {
if (minuteman == 1) { if (minuteman == 1) {
//player has joined to recently //player has joined to recently
if (admin) p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); if (admin)
p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
joiner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); joiner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
return; return;
} else if (minuteman == 2) { } else if (minuteman == 2) {
//player has played too little //player has played too little
if (admin) p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); if (admin)
p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
joiner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); joiner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
return; return;
} }
@@ -429,23 +417,23 @@ public class RaidCommands implements CommandExecutor {
} }
//check if gather phase //check if gather phase
if(!admin) { if (!admin) {
if (raid.getPhase() == RaidPhase.GATHER || raid.getPhase() == RaidPhase.START) { if (raid.getPhase() == RaidPhase.GATHER || raid.getPhase() == RaidPhase.START) {
try { try {
//check if the player is in the gather town //check if the player is in the gather town
ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord()); ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord());
if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) { if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) {
raid.addActiveRaider(joiner.getName()); raid.addActiveRaider(joiner.getName());
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You have joined the raid on " + raid.getRaidedTown().getName() + "!"); joiner.sendMessage(Helper.chatLabel() + "You have joined the raid on " + raid.getRaidedTown().getName() + "!");
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "Leaving " + raid.getGatherTown().getName() + " will cause you to leave the raid party."); joiner.sendMessage(Helper.chatLabel() + "Leaving " + raid.getGatherTown().getName() + " will cause you to leave the raid party.");
} else { } else {
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be in the gathering town to join the raid on " + raid.getRaidedTown().getName() + "."); joiner.sendMessage(Helper.chatLabel() + "You must be in the gathering town to join the raid on " + raid.getRaidedTown().getName() + ".");
} }
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} else { } else {
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You cannot join the raid on " + raid.getRaidedTown().getName() + "! It has already started!"); joiner.sendMessage(Helper.chatLabel() + "You cannot join the raid on " + raid.getRaidedTown().getName() + "! It has already started!");
} }
} else { } else {
try { try {
@@ -453,10 +441,10 @@ public class RaidCommands implements CommandExecutor {
ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord()); ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord());
if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) { if (cluster.contains(WorldCoord.parseWorldCoord(joiner))) {
raid.addActiveRaider(joiner.getName()); raid.addActiveRaider(joiner.getName());
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You have joined the raid on " + raid.getRaidedTown().getName() + "!"); joiner.sendMessage(Helper.chatLabel() + "You have joined the raid on " + raid.getRaidedTown().getName() + "!");
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "Leaving " + raid.getGatherTown().getName() + " will cause you to leave the raid party."); joiner.sendMessage(Helper.chatLabel() + "Leaving " + raid.getGatherTown().getName() + " will cause you to leave the raid party.");
} else { } else {
joiner.sendMessage(String.valueOf(Helper.chatLabel()) + "You must be in the gathering town to join the raid on " + raid.getRaidedTown().getName() + "."); joiner.sendMessage(Helper.chatLabel() + "You must be in the gathering town to join the raid on " + raid.getRaidedTown().getName() + ".");
} }
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -466,7 +454,7 @@ public class RaidCommands implements CommandExecutor {
raid.save(); raid.save();
} }
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "No raid is gathering in this town or this town does not exist!"); p.sendMessage(Helper.chatLabel() + "No raid is gathering in this town or this town does not exist!");
} }
} }
@@ -476,11 +464,11 @@ public class RaidCommands implements CommandExecutor {
if (admin) { if (admin) {
p = Bukkit.getPlayer(args[3]); p = Bukkit.getPlayer(args[3]);
if (p == null) { if (p == null) {
player.sendMessage(String.valueOf(Helper.chatLabel()) + "Error: player not found!"); player.sendMessage(Helper.chatLabel() + "Error: player not found!");
return; return;
} }
} }
if(p == null) { if (p == null) {
p = (Player) player; p = (Player) player;
} }
@@ -488,8 +476,9 @@ public class RaidCommands implements CommandExecutor {
if (raid != null) { if (raid != null) {
if (raid.getWar().getName().equalsIgnoreCase(args[1])) { if (raid.getWar().getName().equalsIgnoreCase(args[1])) {
if (!raid.getWar().getSide1Players().contains(p.getName()) && !raid.getWar().getSide2Players().contains(p.getName())) { if (!raid.getWar().getSide1Players().contains(p.getName()) && !raid.getWar().getSide2Players().contains(p.getName())) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You are not in this war! Type /war join [war] [side]"); p.sendMessage(Helper.chatLabel() + "You are not in this war! Type /war join [war] [side]");
if (admin) player.sendMessage(String.valueOf(Helper.chatLabel()) + "You are not in this war! Type /war join [war] [side]"); if (admin)
player.sendMessage(Helper.chatLabel() + "You are not in this war! Type /war join [war] [side]");
} }
//check if gather phase //check if gather phase
@@ -499,12 +488,14 @@ public class RaidCommands implements CommandExecutor {
ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord()); ArrayList<WorldCoord> cluster = Helper.getCluster(raid.getGatherTown().getHomeBlock().getWorldCoord());
if (cluster.contains(WorldCoord.parseWorldCoord(p))) { if (cluster.contains(WorldCoord.parseWorldCoord(p))) {
raid.removeActiveRaider(p.getName()); raid.removeActiveRaider(p.getName());
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You have left the raid on " + raid.getRaidedTown().getName() + "!"); p.sendMessage(Helper.chatLabel() + "You have left the raid on " + raid.getRaidedTown().getName() + "!");
if (admin) player.sendMessage(String.valueOf(Helper.chatLabel()) + "You have left the raid on " + raid.getRaidedTown().getName() + "!"); if (admin)
player.sendMessage(Helper.chatLabel() + "You have left the raid on " + raid.getRaidedTown().getName() + "!");
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You cannot leave the raid on " + raid.getRaidedTown().getName() + "! It has already started!"); p.sendMessage(Helper.chatLabel() + "You cannot leave the raid on " + raid.getRaidedTown().getName() + "! It has already started!");
if (admin) player.sendMessage(String.valueOf(Helper.chatLabel()) + "You cannot leave the raid on " + raid.getRaidedTown().getName() + "! It has already started!"); if (admin)
player.sendMessage(Helper.chatLabel() + "You cannot leave the raid on " + raid.getRaidedTown().getName() + "! It has already started!");
} }
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -514,8 +505,9 @@ public class RaidCommands implements CommandExecutor {
raid.save(); raid.save();
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "No raid is gathering in this town or this town does not exist!"); p.sendMessage(Helper.chatLabel() + "No raid is gathering in this town or this town does not exist!");
if (admin) player.sendMessage(String.valueOf(Helper.chatLabel()) + "No raid is gathering in this town or this town does not exist!"); if (admin)
player.sendMessage(Helper.chatLabel() + "No raid is gathering in this town or this town does not exist!");
} }
} }
@@ -531,7 +523,7 @@ public class RaidCommands implements CommandExecutor {
if (raid != null) { if (raid != null) {
if (raid.getWar().getName().equalsIgnoreCase(args[1])) { if (raid.getWar().getName().equalsIgnoreCase(args[1])) {
if (!raid.getWar().getSide1Players().contains(p.getName()) && !raid.getWar().getSide2Players().contains(p.getName())) { if (!raid.getWar().getSide1Players().contains(p.getName()) && !raid.getWar().getSide2Players().contains(p.getName())) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You are not in this war! Type /war join [war] [side]"); p.sendMessage(Helper.chatLabel() + "You are not in this war! Type /war join [war] [side]");
return; return;
} }
@@ -539,11 +531,11 @@ public class RaidCommands implements CommandExecutor {
//check if gather phase //check if gather phase
if (raid.getPhase() == RaidPhase.GATHER || raid.getPhase() == RaidPhase.START || raid.getPhase() == RaidPhase.TRAVEL || raid.getPhase() == RaidPhase.COMBAT) { if (raid.getPhase() == RaidPhase.GATHER || raid.getPhase() == RaidPhase.START || raid.getPhase() == RaidPhase.TRAVEL || raid.getPhase() == RaidPhase.COMBAT) {
//force defender victory //force defender victory
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The raid on " + raid.getRaidedTown().getName() + " has been abandoned by " + raid.getRaiderSide()); Bukkit.broadcastMessage(Helper.chatLabel() + "The raid on " + raid.getRaidedTown().getName() + " has been abandoned by " + raid.getRaiderSide());
Main.warLogger.log(p.getName() + " abandoned the raid on " + raid.getRaidedTown().getName() + " they started at " + raid.getGatherTown().getName()); Main.warLogger.log(p.getName() + " abandoned the raid on " + raid.getRaidedTown().getName() + " they started at " + raid.getGatherTown().getName());
raid.defendersWin(raid.getRaiderScore(), raid.getDefenderScore()); raid.defendersWin(raid.getRaiderScore(), raid.getDefenderScore());
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "You cannot abandon the raid on " + raid.getRaidedTown().getName() + "! It has a problem!"); p.sendMessage(Helper.chatLabel() + "You cannot abandon the raid on " + raid.getRaidedTown().getName() + "! It has a problem!");
} }
} else { } else {
fail(p, args, "owner"); fail(p, args, "owner");
@@ -551,15 +543,15 @@ public class RaidCommands implements CommandExecutor {
} }
} }
p.sendMessage(String.valueOf(Helper.chatLabel()) + "This raid does not exist!"); p.sendMessage(Helper.chatLabel() + "This raid does not exist!");
} }
private static void listRaids(CommandSender p, String[] args) { private static void listRaids(CommandSender p, String[] args) {
if (RaidData.getRaids().isEmpty()) { if (RaidData.getRaids().isEmpty()) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "There are currently no Raids in progress"); p.sendMessage(Helper.chatLabel() + "There are currently no Raids in progress");
return; return;
} }
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Raids currently in progress:"); p.sendMessage(Helper.chatLabel() + "Raids currently in progress:");
for (final Raid raid : RaidData.getRaids()) { for (final Raid raid : RaidData.getRaids()) {
p.sendMessage("Name: " + raid.getName()); p.sendMessage("Name: " + raid.getName());
p.sendMessage("War: " + raid.getWar().getName()); p.sendMessage("War: " + raid.getWar().getName());
@@ -589,12 +581,49 @@ public class RaidCommands implements CommandExecutor {
private static void fail(CommandSender p, String[] args, String type) { private static void fail(CommandSender p, String[] args, String type) {
switch (type) { switch (type) {
case "permissions" -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "&cYou do not have permission to do this"); case "permissions" ->
case "syntax" -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "Invalid Syntax. /raid help"); p.sendMessage(Helper.chatLabel() + "&cYou do not have permission to do this");
case "noRaids" -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "There are currently no Raids in progress"); case "syntax" -> p.sendMessage(Helper.chatLabel() + "Invalid Syntax. /raid help");
case "badName" -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "A raid could not be found with this Name! Type /raid list to view current raids"); case "noRaids" ->
case "owner" -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "Only the player who started the raid can abandon it."); p.sendMessage(Helper.chatLabel() + "There are currently no Raids in progress");
default -> p.sendMessage(String.valueOf(Helper.chatLabel()) + "Invalid Arguments. /raid help"); case "badName" ->
p.sendMessage(Helper.chatLabel() + "A raid could not be found with this Name! Type /raid list to view current raids");
case "owner" ->
p.sendMessage(Helper.chatLabel() + "Only the player who started the raid can abandon it.");
default -> p.sendMessage(Helper.chatLabel() + "Invalid Arguments. /raid help");
} }
} }
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
// final Player p = (Player) sender;
CommandHelper.logCommand(sender, label, args);
if (args.length == 0) {
fail(sender, args, "syntax");
} else if (args.length == 1) {
if (args[0].equalsIgnoreCase("list")) {
listRaids(sender, args);
} else if (args[0].equalsIgnoreCase("help")) {
raidHelp(sender, args);
} else {
fail(sender, args, "syntax");
}
} else if (args.length == 3) {
if (args[0].equalsIgnoreCase("start")) {
startRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("stop")) {
stopRaid(sender, args);
} else if (args[0].equalsIgnoreCase("join")) {
joinRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("leave")) {
leaveRaid(sender, args, false);
} else if (args[0].equalsIgnoreCase("abandon")) {
abandonRaid(sender, args);
} else {
fail(sender, args, "syntax");
}
} else {
fail(sender, args, "syntax");
}
return true;
}
} }
@@ -10,7 +10,7 @@ import java.util.List;
public class RaidTabCompletion implements TabCompleter { public class RaidTabCompletion implements TabCompleter {
private static final List<String> base = List.of(new String[] { private static final List<String> base = List.of(new String[]{
"abandon", "abandon",
"help", "help",
"join", "join",
@@ -19,7 +19,7 @@ public class RaidTabCompletion implements TabCompleter {
"start" "start"
}); });
private static final List<String> baseAdmin = List.of(new String[] { private static final List<String> baseAdmin = List.of(new String[]{
"abandon", "abandon",
"help", "help",
"join", "join",
@@ -34,7 +34,7 @@ public class RaidTabCompletion implements TabCompleter {
boolean flag = sender.hasPermission("AlathraWar.admin"); boolean flag = sender.hasPermission("AlathraWar.admin");
if (args.length > 0) { if (args.length > 0) {
if(args.length > 1) { if (args.length > 1) {
switch (args[0]) { switch (args[0]) {
case "abandon", "join", "leave", "start", "stop" -> { case "abandon", "join", "leave", "start", "stop" -> {
if (args.length > 2) { if (args.length > 2) {
@@ -1,31 +1,262 @@
package me.ShermansWorld.AlathraWar.commands; package me.ShermansWorld.AlathraWar.commands;
import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Town;
import me.ShermansWorld.AlathraWar.*; import me.ShermansWorld.AlathraWar.*;
import me.ShermansWorld.AlathraWar.data.RaidData; import me.ShermansWorld.AlathraWar.data.RaidData;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.OfflinePlayer;
import com.palmergames.bukkit.towny.TownyAPI;
import me.ShermansWorld.AlathraWar.data.SiegeData; import me.ShermansWorld.AlathraWar.data.SiegeData;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.palmergames.bukkit.towny.object.Town; import org.bukkit.entity.Player;
import java.util.HashSet; import java.util.HashSet;
import org.bukkit.command.CommandExecutor;
public class SiegeCommands implements CommandExecutor { public class SiegeCommands implements CommandExecutor {
public SiegeCommands(final Main plugin) { public SiegeCommands(final Main plugin) {
plugin.getCommand("siege").setExecutor((CommandExecutor) this); plugin.getCommand("siege").setExecutor(this);
}
protected static void siegeStart(CommandSender sender, String[] args, boolean admin) {
// if (!(sender instanceof Player)) return;
//if this is admin mode use the forth arg instad of sender.
//if player is null after this then force end
Player siegeOwner = null;
if ((sender instanceof Player)) {
siegeOwner = (Player) sender;
}
if (admin && args.length >= 5) {
siegeOwner = Bukkit.getPlayer(args[3]);
if (siegeOwner == null) {
sender.sendMessage("Player Does not exist");
return;
}
}
if (siegeOwner == null) {
sender.sendMessage("Owner is Null");
return;
}
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/war siege [war] [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
siegeOwner.sendMessage(Helper.chatLabel() + "That war does not exist! /siege start [war] [town]");
if (admin)
sender.sendMessage(Helper.chatLabel() + "That war does not exist! /siege start [war] [town]");
return;
}
// Player participance check
Town leaderTown = TownyAPI.getInstance().getResident(siegeOwner).getTownOrNull();
int side = war.getSide(leaderTown.getName().toLowerCase());
//DEBUG PRINT
Main.warLogger.log("Leader Town: " + leaderTown.getName());
Main.warLogger.log("Siege Owner: " + siegeOwner.getName());
sender.sendMessage("Leader Town: " + leaderTown.getName());
sender.sendMessage("Siege Owner: " + siegeOwner.getName());
//DEBUG PRINT
for (String t : war.getSide1Towns()) {
Main.warLogger.log("Side1 town: " + t);
sender.sendMessage("Side1 town: " + t);
}
for (String t : war.getSide2Towns()) {
Main.warLogger.log("Side2 town: " + t);
sender.sendMessage("Side2 town: " + t);
}
if (side == 0) {
siegeOwner.sendMessage(Helper.chatLabel() + "You are not in this war.");
if (admin) sender.sendMessage(Helper.chatLabel() + "You are not in this war.");
return;
} else if (side == -1) {
siegeOwner.sendMessage(Helper.chatLabel() + "You have surrendered.");
if (admin) sender.sendMessage(Helper.chatLabel() + "You have surrendered.");
return;
}
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
//Minuteman countermeasures
int minuteman = CommandHelper.isPlayerMinuteman(siegeOwner.getName());
boolean override = false;
if (admin) {
if (args.length >= 6) {
if (Boolean.parseBoolean(args[5])) {
//player has joined to recently
sender.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
override = true;
}
}
}
//override?
if (!override) {
if (minuteman != 0) {
if (minuteman == 1) {
//player has joined to recently
if (admin)
sender.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
siegeOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
return;
} else if (minuteman == 2) {
//player has played too little
if (admin)
sender.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
siegeOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
return;
}
}
}
// Town check
Town town = TownyAPI.getInstance().getTown(args[2]);
if (town == null) {
siegeOwner.sendMessage(Helper.chatLabel() + "That town does not exist! /siege start [war] [town]");
if (admin)
sender.sendMessage(Helper.chatLabel() + "That town does not exist! /siege start [war] [town]");
return;
}
Main.warLogger.log("Attacked Town: " + town.getName().toLowerCase());
sender.sendMessage("Attacked Town: " + town.getName().toLowerCase());
// Is being raided check
for (Raid r : RaidData.getRaids()) {
if (r.getRaidedTown().getName().equalsIgnoreCase(town.getName())) {
siegeOwner.sendMessage(Helper.chatLabel() + "That town is already currently being raided! Cannot siege at this time!");
if (admin)
sender.sendMessage(Helper.chatLabel() + "That town is already currently being raided! Cannot siege at this time!");
return;
}
}
// Attacking own side
if (war.getSide(town) == side) {
siegeOwner.sendMessage(Helper.chatLabel() + "You cannot attack your own towns.");
if (admin) sender.sendMessage(Helper.chatLabel() + "You cannot attack your own towns.");
return;
}
Siege siege = new Siege(war, town, siegeOwner);
SiegeData.addSiege(siege);
war.addSiege(siege);
Bukkit.broadcastMessage(Helper.chatLabel() + "A siege has been laid on " + siege.getTown() + " by " + siege.getAttackerSide() + "!");
war.save();
siege.start();
}
private static void siegeStop(CommandSender sender, String[] args) {
if (!sender.hasPermission("AlathraWar.admin")) {
sender.sendMessage(Helper.chatLabel() + Helper.color("&cYou do not have permission to do this"));
return;
}
HashSet<Siege> sieges = SiegeData.getSieges();
if (sieges.isEmpty()) {
sender.sendMessage(Helper.chatLabel() + "There are currently no sieges in progress");
return;
}
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/siege stop [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
sender.sendMessage(Helper.chatLabel() + "That war does not exist! /siege stop [war] [town]");
return;
}
for (Siege siege : sieges) {
if (siege.getTown().getName().equalsIgnoreCase(args[2])) {
sender.sendMessage(Helper.chatLabel() + "siege cancelled");
Bukkit.broadcastMessage(Helper.chatLabel() + "The siege at " + siege.getTown().getName() + " has been cancelled by an admin");
//siege.clearBeacon();
siege.stop();
return;
}
}
sender.sendMessage(Helper.chatLabel() + "A siege could not be found with this town name! Type /siege list to view current sieges");
}
private static void siegeAbandon(CommandSender sender, String[] args) {
if (!(sender instanceof Player p)) return;
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/siege abandon [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
p.sendMessage(Helper.chatLabel() + "That war does not exist! /siege abandon [war] [town]");
return;
}
Siege siege = SiegeData.getSiege(args[2]);
if (siege == null) {
p.sendMessage(Helper.chatLabel() + "Invalid siege");
return;
}
OfflinePlayer oPlayer = siege.getSiegeLeader();
if (oPlayer != p) {
p.sendMessage(Helper.chatLabel() + "You are not the leader of this siege.");
return;
}
Bukkit.broadcastMessage(Helper.chatLabel() + "The siege at " + siege.getTown().getName() + " has been abandoned.");
Main.warLogger.log(p.getName() + " abandoned the siege they started at " + siege.getTown().getName());
siege.defendersWin();
}
private static void siegeList(CommandSender sender, String[] args) {
HashSet<Siege> sieges = SiegeData.getSieges();
if (sieges.isEmpty()) {
sender.sendMessage(Helper.chatLabel() + "There are currently no sieges in progress");
return;
}
sender.sendMessage(Helper.chatLabel() + "Sieges currently in progress:");
for (Siege siege : sieges) {
War war = siege.getWar();
String color = (siege.getSide1AreAttackers() && (war.getSide(siege.getTown().getName().toLowerCase()) == 1)) ? "§c" : "§9";
sender.sendMessage(war.getName() + " - " + color + siege.getTown().getName().toLowerCase());
sender.sendMessage(war.getSide1() + " - " + (siege.getSide1AreAttackers() ? siege.getAttackerPoints() : siege.getDefenderPoints()));
sender.sendMessage(war.getSide2() + " - " + (siege.getSide1AreAttackers() ? siege.getDefenderPoints() : siege.getAttackerPoints()));
sender.sendMessage("Time Left: " + (Siege.maxSiegeTicks - siege.getSiegeTicks()) / 1200 + " minutes");
sender.sendMessage("-=-=-=-=-=-=-=-=-=-=-=-");
}
}
private static void siegeHelp(CommandSender sender, String[] args) {
if (sender.hasPermission("AlathraWar.admin")) {
sender.sendMessage(Helper.chatLabel() + "/siege stop [war] [town]");
}
sender.sendMessage(Helper.chatLabel() + "/siege start [war] [town]");
sender.sendMessage(Helper.chatLabel() + "/siege abandon [war] [town]");
sender.sendMessage(Helper.chatLabel() + "/siege list");
} }
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
CommandHelper.logCommand(sender, label, args); CommandHelper.logCommand(sender, label, args);
if (args.length == 0) { if (args.length == 0) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "Invalid Arguments. /siege help"); sender.sendMessage(Helper.chatLabel() + "Invalid Arguments. /siege help");
return true; return true;
} }
@@ -59,232 +290,4 @@ public class SiegeCommands implements CommandExecutor {
} }
return false; return false;
} }
protected static void siegeStart(CommandSender sender, String[] args, boolean admin) {
// if (!(sender instanceof Player)) return;
//if this is admin mode use the forth arg instad of sender.
//if player is null after this then force end
Player siegeOwner = null;
if((sender instanceof Player)) {
siegeOwner = (Player) sender;
}
if(admin && args.length >= 5) {
siegeOwner = Bukkit.getPlayer(args[3]);
if(siegeOwner == null) {
sender.sendMessage("Player Does not exist");
return;
}
}
if (siegeOwner == null) {
sender.sendMessage("Owner is Null");
return;
}
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/war siege [war] [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
siegeOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "That war does not exist! /siege start [war] [town]");
if(admin) sender.sendMessage(String.valueOf(Helper.chatLabel()) + "That war does not exist! /siege start [war] [town]");
return;
}
// Player participance check
Town leaderTown = TownyAPI.getInstance().getResident(siegeOwner).getTownOrNull();
int side = war.getSide(leaderTown.getName().toLowerCase());
//DEBUG PRINT
Main.warLogger.log("Leader Town: " + leaderTown.getName());
Main.warLogger.log("Siege Owner: " + siegeOwner.getName());
sender.sendMessage("Leader Town: " + leaderTown.getName());
sender.sendMessage("Siege Owner: " + siegeOwner.getName());
//DEBUG PRINT
for (String t : war.getSide1Towns()) {
Main.warLogger.log("Side1 town: " + t);
sender.sendMessage("Side1 town: " + t);
}
for (String t : war.getSide2Towns()) {
Main.warLogger.log("Side2 town: " + t);
sender.sendMessage("Side2 town: " + t);
}
if (side == 0) {
siegeOwner.sendMessage(Helper.chatLabel() + "You are not in this war.");
if(admin) sender.sendMessage(Helper.chatLabel() + "You are not in this war.");
return;
} else if (side == -1) {
siegeOwner.sendMessage(Helper.chatLabel() + "You have surrendered.");
if(admin) sender.sendMessage(Helper.chatLabel() + "You have surrendered.");
return;
}
//Minutemen countermeasures, 86400 * 4 time. 86400 seconds in a day, 4 days min playtime
//Minuteman countermeasures
int minuteman = CommandHelper.isPlayerMinuteman(siegeOwner.getName());
boolean override = false;
if (admin) {
if (args.length >= 6) {
if (Boolean.parseBoolean(args[5])) {
//player has joined to recently
sender.sendMessage(ChatColor.RED + "Warning! Ignoring Minuteman Countermeasure!");
override = true;
}
}
}
//override?
if(!override) {
if (minuteman != 0) {
if (minuteman == 1) {
//player has joined to recently
if (admin) sender.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
siegeOwner.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
return;
} else if (minuteman == 2) {
//player has played too little
if (admin) sender.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
siegeOwner.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
return;
}
}
}
// Town check
Town town = TownyAPI.getInstance().getTown(args[2]);
if (town == null) {
siegeOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "That town does not exist! /siege start [war] [town]");
if(admin) sender.sendMessage(String.valueOf(Helper.chatLabel()) + "That town does not exist! /siege start [war] [town]");
return;
}
Main.warLogger.log("Attacked Town: " + town.getName().toLowerCase());
sender.sendMessage("Attacked Town: " + town.getName().toLowerCase());
// Is being raided check
for ( Raid r : RaidData.getRaids()) {
if(r.getRaidedTown().getName().equalsIgnoreCase(town.getName())) {
siegeOwner.sendMessage(String.valueOf(Helper.chatLabel()) + "That town is already currently being raided! Cannot siege at this time!");
if(admin) sender.sendMessage(String.valueOf(Helper.chatLabel()) + "That town is already currently being raided! Cannot siege at this time!");
return;
}
}
// Attacking own side
if (war.getSide(town) == side) {
siegeOwner.sendMessage(Helper.chatLabel() + "You cannot attack your own towns.");
if(admin) sender.sendMessage(Helper.chatLabel() + "You cannot attack your own towns.");
return;
}
Siege siege = new Siege(war, town, siegeOwner);
SiegeData.addSiege(siege);
war.addSiege(siege);
Bukkit.broadcastMessage(Helper.chatLabel() + "A siege has been laid on " + siege.getTown() + " by " + siege.getAttackerSide() + "!");
war.save();
siege.start();
}
private static void siegeStop(CommandSender sender, String[] args) {
if (!sender.hasPermission("AlathraWar.admin")) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou do not have permission to do this"));
return;
}
HashSet<Siege> sieges = SiegeData.getSieges();
if (sieges.isEmpty()) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "There are currently no sieges in progress");
return;
}
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/siege stop [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "That war does not exist! /siege stop [war] [town]");
return;
}
for (Siege siege : sieges) {
if (siege.getTown().getName().equalsIgnoreCase(args[2])) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "siege cancelled");
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The siege at " + siege.getTown().getName() + " has been cancelled by an admin");
//siege.clearBeacon();
siege.stop();
return;
}
}
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "A siege could not be found with this town name! Type /siege list to view current sieges");
}
private static void siegeAbandon(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) return;
final Player p = (Player) sender;
if (args.length < 3) {
sender.sendMessage(Helper.chatLabel() + "/siege abandon [town]");
return;
}
// War check
War war = WarData.getWar(args[1]);
if (war == null) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "That war does not exist! /siege abandon [war] [town]");
return;
}
Siege siege = SiegeData.getSiege(args[2]);
if (siege == null) {
p.sendMessage(Helper.chatLabel() + "Invalid siege");
return;
}
OfflinePlayer oPlayer = siege.getSiegeLeader();
if (oPlayer != (OfflinePlayer) p) {
p.sendMessage(Helper.chatLabel() + "You are not the leader of this siege.");
return;
}
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "The siege at " + siege.getTown().getName() + " has been abandoned.");
Main.warLogger.log(p.getName() + " abandoned the siege they started at " + siege.getTown().getName());
siege.defendersWin();
}
private static void siegeList(CommandSender sender, String[] args) {
HashSet<Siege> sieges = SiegeData.getSieges();
if (sieges.isEmpty()) {
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "There are currently no sieges in progress");
return;
}
sender.sendMessage(String.valueOf(Helper.chatLabel()) + "Sieges currently in progress:");
for (Siege siege : sieges) {
War war = siege.getWar();
String color = (siege.getSide1AreAttackers() && (war.getSide(siege.getTown().getName().toLowerCase()) == 1) ) ? "§c" : "§9";
sender.sendMessage(war.getName() + " - " + color + siege.getTown().getName().toLowerCase());
sender.sendMessage(war.getSide1() + " - " + (siege.getSide1AreAttackers() ? siege.getAttackerPoints() : siege.getDefenderPoints()));
sender.sendMessage(war.getSide2() + " - " + (siege.getSide1AreAttackers() ? siege.getDefenderPoints() : siege.getAttackerPoints()));
sender.sendMessage("Time Left: " + (Siege.maxSiegeTicks - siege.getSiegeTicks())/1200 + " minutes");
sender.sendMessage("-=-=-=-=-=-=-=-=-=-=-=-");
}
}
private static void siegeHelp(CommandSender sender, String[] args) {
if (sender.hasPermission("AlathraWar.admin")) {
sender.sendMessage(Helper.chatLabel() + "/siege stop [war] [town]");
}
sender.sendMessage(Helper.chatLabel() + "/siege start [war] [town]");
sender.sendMessage(Helper.chatLabel() + "/siege abandon [war] [town]");
sender.sendMessage(Helper.chatLabel() + "/siege list");
}
} }
@@ -11,50 +11,50 @@ import java.util.List;
public class SiegeTabCompletion implements TabCompleter { public class SiegeTabCompletion implements TabCompleter {
private static final List<String> baseAdmin = List.of(new String[] { private static final List<String> baseAdmin = List.of(new String[]{
"abandon", "abandon",
"help", "help",
"list", "list",
"start", "start",
"stop" "stop"
}); });
private static final List<String> base = List.of(new String[] { private static final List<String> base = List.of(new String[]{
"abandon", "abandon",
"help", "help",
"list", "list",
"start" "start"
}); });
@Override @Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
boolean flag = sender.hasPermission("AlathraWar.admin"); boolean flag = sender.hasPermission("AlathraWar.admin");
if (args.length > 0) { if (args.length > 0) {
if(args.length > 1) { if (args.length > 1) {
switch (args[0]) { switch (args[0]) {
case "abandon", "start", "stop" -> { case "abandon", "start", "stop" -> {
if (args.length > 2) { if (args.length > 2) {
if (args.length > 3) { if (args.length > 3) {
return Collections.emptyList(); return Collections.emptyList();
} else { } else {
return NameUtil.filterByStart(CommandHelper.getTownyWarTowns(args[1]), args[2]); return NameUtil.filterByStart(CommandHelper.getTownyWarTowns(args[1]), args[2]);
} }
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]);
} }
} }
//help, list, debug //help, list, debug
default -> { default -> {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
} else { } else {
return NameUtil.filterByStart(flag ? baseAdmin : base, args[0]); return NameUtil.filterByStart(flag ? baseAdmin : base, args[0]);
} }
} else { } else {
return flag ? baseAdmin : base; return flag ? baseAdmin : base;
} }
} }
} }
@@ -1,69 +1,23 @@
package me.ShermansWorld.AlathraWar.commands; package me.ShermansWorld.AlathraWar.commands;
import me.ShermansWorld.AlathraWar.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Resident; import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.Town;
import me.ShermansWorld.AlathraWar.*;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
public class WarCommands implements CommandExecutor { public class WarCommands implements CommandExecutor {
public WarCommands(final Main plugin) { public WarCommands(final Main plugin) {
plugin.getCommand("war").setExecutor((CommandExecutor) this); plugin.getCommand("war").setExecutor(this);
}
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
CommandHelper.logCommand(sender, label, args);
if (!(sender instanceof Player)) {
consoleCommand(sender, args);
return true;
}
final Player p = (Player) sender;
if (args.length == 0) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Invalid Arguments. /war help");
return true;
} else if (args.length >= 1) {
switch(args[0].toLowerCase()) {
case "create":
warCreate(p, args);
return true;
case "delete":
warDelete(p, args);
return true;
case "join":
warJoin(p, args, false);
return true;
case "surrender":
warSurrender(p, args, false);
return true;
case "list":
warList(p, args);
return true;
case "info":
warInfo(p, args);
return true;
case "help":
warHelp(p, args);
return true;
default:
p.sendMessage(String.valueOf(Helper.chatLabel()) + "Invalid Arguments. /war help");
return true;
}
}
return false;
} }
protected static void warCreate(CommandSender p, String[] args) { protected static void warCreate(CommandSender p, String[] args) {
@@ -76,13 +30,12 @@ public class WarCommands implements CommandExecutor {
WarData.addWar(war); WarData.addWar(war);
war.save(); war.save();
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "War created with the name " + args[1] + ", " Bukkit.broadcastMessage(Helper.chatLabel() + "War created with the name " + args[1] + ", "
+ args[2] + " vs. " + args[3]); + args[2] + " vs. " + args[3]);
Main.warLogger.log(p.getName() + " created a new war with the name " + args[1] + ", " + args[2] Main.warLogger.log(p.getName() + " created a new war with the name " + args[1] + ", " + args[2]
+ " vs. " + args[3]); + " vs. " + args[3]);
return;
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) p.sendMessage(Helper.chatLabel()
+ "Invalid Arguments. /war create [name] [side1] [side2]"); + "Invalid Arguments. /war create [name] [side1] [side2]");
} }
@@ -104,27 +57,25 @@ public class WarCommands implements CommandExecutor {
return; return;
} }
for(Siege s : war.getSieges()) { for (Siege s : war.getSieges()) {
s.stop(); s.stop();
} }
for(Raid r : war.getRaids()) { for (Raid r : war.getRaids()) {
r.stop(); r.stop();
} }
WarData.removeWar(war); WarData.removeWar(war);
Bukkit.broadcastMessage(String.valueOf(Helper.chatLabel()) + "War " + args[1] + " deleted."); Bukkit.broadcastMessage(Helper.chatLabel() + "War " + args[1] + " deleted.");
Main.warLogger.log(p.getName() + " deleted " + args[1]); Main.warLogger.log(p.getName() + " deleted " + args[1]);
return;
} else { } else {
p.sendMessage(String.valueOf(Helper.chatLabel()) p.sendMessage(Helper.chatLabel()
+ "Invalid Arguments. /war delete [name]"); + "Invalid Arguments. /war delete [name]");
} }
} }
/** /**
* * @param p - executor
* @param p - executor
* @param args * @param args
* @param admin - admin behavior * @param admin - admin behavior
*/ */
@@ -145,14 +96,14 @@ public class WarCommands implements CommandExecutor {
} }
Player player = null; Player player = null;
if (admin){ if (admin) {
player = Bukkit.getPlayer(args[3]); player = Bukkit.getPlayer(args[3]);
if(player == null) { if (player == null) {
p.sendMessage(Helper.chatLabel() + "Player " + args[3] + " not found!"); p.sendMessage(Helper.chatLabel() + "Player " + args[3] + " not found!");
return; return;
} }
} }
if(player == null) { if (player == null) {
player = (Player) p; player = (Player) p;
} }
@@ -180,16 +131,18 @@ public class WarCommands implements CommandExecutor {
} }
} }
//override? //override?
if(!override) { if (!override) {
if (minuteman != 0) { if (minuteman != 0) {
if (minuteman == 1) { if (minuteman == 1) {
//player has joined to recently //player has joined to recently
if (admin) p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); if (admin)
p.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
player.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining."); player.sendMessage(ChatColor.RED + "You have joined the server too recently! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayerAge") + " days from joining.");
return; return;
} else if (minuteman == 2) { } else if (minuteman == 2) {
//player has played too little //player has played too little
if (admin) p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); if (admin)
p.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
player.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play."); player.sendMessage(ChatColor.RED + "You have not played enough! You can only join a raid after " + Main.getInstance().getConfig().getInt("minimumPlayTime") + " hours of play.");
return; return;
} }
@@ -207,18 +160,16 @@ public class WarCommands implements CommandExecutor {
} }
if (res.hasNation()) { if (res.hasNation()) {
if(res.getPlayer().hasPermission("AlathraWar.nationjoin" )|| res.isKing()) { if (res.getPlayer().hasPermission("AlathraWar.nationjoin") || res.isKing()) {
// Has nation declaration permission // Has nation declaration permission
war.addNation(res.getNationOrNull(), args[2]); war.addNation(res.getNationOrNull(), args[2]);
res.getPlayer().sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getNationOrNull().getName()); res.getPlayer().sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getNationOrNull().getName());
p.sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getNationOrNull().getName()); p.sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getNationOrNull().getName());
Bukkit.broadcastMessage(Helper.chatLabel() + "The nation of " + res.getNationOrNull().getName() + " has joined the war on the side of " + args[2] + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The nation of " + res.getNationOrNull().getName() + " has joined the war on the side of " + args[2] + "!");
war.save(); war.save();
return;
} else { } else {
// Cannot declare nation involvement // Cannot declare nation involvement
p.sendMessage(Helper.chatLabel() + "You cannot declare war for your nation."); p.sendMessage(Helper.chatLabel() + "You cannot declare war for your nation.");
return;
} }
} else if (res.hasTown()) { } else if (res.hasTown()) {
if (res.getPlayer().hasPermission("AlathraWar.townjoin") || res.isMayor()) { if (res.getPlayer().hasPermission("AlathraWar.townjoin") || res.isMayor()) {
@@ -228,11 +179,9 @@ public class WarCommands implements CommandExecutor {
p.sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getTownOrNull().getName()); p.sendMessage(Helper.chatLabel() + "You have joined the war for " + res.getTownOrNull().getName());
Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + res.getTownOrNull().getName() + " has joined the war on the side of " + args[2] + "!"); Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + res.getTownOrNull().getName() + " has joined the war on the side of " + args[2] + "!");
war.save(); war.save();
return;
} else { } else {
// No perms // No perms
p.sendMessage(Helper.chatLabel() + "You cannot declare war for your town."); p.sendMessage(Helper.chatLabel() + "You cannot declare war for your town.");
return;
} }
} }
} }
@@ -264,17 +213,15 @@ public class WarCommands implements CommandExecutor {
} }
if (res.hasNation()) { if (res.hasNation()) {
if(p.hasPermission("AlathraWar.nationsurrender" )|| res.isKing()) { if (p.hasPermission("AlathraWar.nationsurrender") || res.isKing()) {
// Has nation surrender permission // Has nation surrender permission
war.surrenderNation(res.getNationOrNull()); war.surrenderNation(res.getNationOrNull());
p.sendMessage(Helper.chatLabel() + "You have surrendered the war for " + res.getNationOrNull().getName()); p.sendMessage(Helper.chatLabel() + "You have surrendered the war for " + res.getNationOrNull().getName());
Bukkit.broadcastMessage(Helper.chatLabel() + "The nation of " + res.getNationOrNull().getName() + " has surrendered! They were fighting for " + args[2] + "."); Bukkit.broadcastMessage(Helper.chatLabel() + "The nation of " + res.getNationOrNull().getName() + " has surrendered! They were fighting for " + args[2] + ".");
war.save(); war.save();
return;
} else { } else {
// Cannot surrender nation involvement // Cannot surrender nation involvement
p.sendMessage(Helper.chatLabel() + "You cannot surrender war for your nation."); p.sendMessage(Helper.chatLabel() + "You cannot surrender war for your nation.");
return;
} }
} else if (res.hasTown()) { } else if (res.hasTown()) {
if (p.hasPermission("AlathraWar.townsurrender") || res.isMayor()) { if (p.hasPermission("AlathraWar.townsurrender") || res.isMayor()) {
@@ -283,20 +230,18 @@ public class WarCommands implements CommandExecutor {
p.sendMessage(Helper.chatLabel() + "You have surrendered the war for " + res.getTownOrNull().getName()); p.sendMessage(Helper.chatLabel() + "You have surrendered the war for " + res.getTownOrNull().getName());
Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + res.getTownOrNull().getName() + " has surrendered! They were fighting for " + args[2] + "."); Bukkit.broadcastMessage(Helper.chatLabel() + "The town of " + res.getTownOrNull().getName() + " has surrendered! They were fighting for " + args[2] + ".");
war.save(); war.save();
return;
} else { } else {
// No perms // No perms
p.sendMessage(Helper.chatLabel() + "You cannot surrender war for your town."); p.sendMessage(Helper.chatLabel() + "You cannot surrender war for your town.");
return;
} }
} }
} }
private static void warList(Player p, String[] args) { private static void warList(Player p, String[] args) {
p.sendMessage(Helper.chatLabel()+ "Wars:"); p.sendMessage(Helper.chatLabel() + "Wars:");
ArrayList<War> wars = WarData.getWars(); ArrayList<War> wars = WarData.getWars();
if (wars.size() < 1) { if (wars.isEmpty()) {
p.sendMessage("There are no current wars."); p.sendMessage("There are no current wars.");
} else { } else {
for (War war : wars) { for (War war : wars) {
@@ -320,11 +265,11 @@ public class WarCommands implements CommandExecutor {
int side = war.getSide(args[1]); int side = war.getSide(args[1]);
if (side != 0) { if (side != 0) {
if (side == -1) { if (side == -1) {
p.sendMessage(war.getName() + " - Surrendered"); p.sendMessage(war.getName() + " - Surrendered");
} else if (side == 1) { } else if (side == 1) {
p.sendMessage(war.getName() + " - " + war.getSide1()); p.sendMessage(war.getName() + " - " + war.getSide1());
} else if (side == 2) { } else if (side == 2) {
p.sendMessage(war.getName() + " - " + war.getSide2()); p.sendMessage(war.getName() + " - " + war.getSide2());
} }
} }
} }
@@ -336,6 +281,7 @@ public class WarCommands implements CommandExecutor {
/** /**
* Method for console access * Method for console access
*
* @param sender * @param sender
* @param args * @param args
*/ */
@@ -351,4 +297,30 @@ public class WarCommands implements CommandExecutor {
} }
} }
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
CommandHelper.logCommand(sender, label, args);
if (!(sender instanceof Player p)) {
consoleCommand(sender, args);
return true;
}
if (args.length == 0) {
p.sendMessage(Helper.chatLabel() + "Invalid Arguments. /war help");
} else {
switch (args[0].toLowerCase()) {
case "create" -> warCreate(p, args);
case "delete" -> warDelete(p, args);
case "join" -> warJoin(p, args, false);
case "surrender" -> warSurrender(p, args, false);
case "list" -> warList(p, args);
case "info" -> warInfo(p, args);
case "help" -> warHelp(p, args);
default -> p.sendMessage(Helper.chatLabel() + "Invalid Arguments. /war help");
}
}
return true;
}
} }
@@ -8,65 +8,65 @@ import org.bukkit.command.TabCompleter;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class WarTabCompletion implements TabCompleter{ public class WarTabCompletion implements TabCompleter {
private static final List<String> baseAdmin = List.of(new String[]{ private static final List<String> baseAdmin = List.of(new String[]{
"create", "create",
"delete", "delete",
"help", "help",
"info", "info",
"join", "join",
"list", "list",
"surrender" "surrender"
}); });
private static final List<String> base = List.of(new String[]{ private static final List<String> base = List.of(new String[]{
"help", "help",
"info", "info",
"join", "join",
"list", "list",
"surrender" "surrender"
}); });
@Override @Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) { public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
boolean flag = sender.hasPermission("AlathraWar.admin"); boolean flag = sender.hasPermission("AlathraWar.admin");
if (args.length > 0) { if (args.length > 0) {
if(args.length > 1) { if (args.length > 1) {
switch (args[0]) { switch (args[0]) {
case "join" -> { case "join" -> {
if (args.length > 2) { if (args.length > 2) {
if (args.length > 3) { if (args.length > 3) {
return Collections.emptyList(); return Collections.emptyList();
} }
return NameUtil.filterByStart(CommandHelper.getWarSides(args[1]), args[2]); return NameUtil.filterByStart(CommandHelper.getWarSides(args[1]), args[2]);
} else { } else {
return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]);
} }
} }
case "info" -> { case "info" -> {
if (args.length > 2) { if (args.length > 2) {
return Collections.emptyList(); return Collections.emptyList();
} }
return NameUtil.filterByStart(CommandHelper.getPlayers(), args[1]); return NameUtil.filterByStart(CommandHelper.getPlayers(), args[1]);
} }
case "delete", "surrender" -> { case "delete", "surrender" -> {
if (args.length > 2) { if (args.length > 2) {
return Collections.emptyList(); return Collections.emptyList();
} }
return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]); return NameUtil.filterByStart(CommandHelper.getWarNames(), args[1]);
} }
//create, list, help //create, list, help
default -> { default -> {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
} else { } else {
return NameUtil.filterByStart(flag ? baseAdmin : base, args[0]); return NameUtil.filterByStart(flag ? baseAdmin : base, args[0]);
} }
} else { } else {
return flag ? baseAdmin : base; return flag ? baseAdmin : base;
} }
} }
} }
@@ -1,40 +1,34 @@
package me.ShermansWorld.AlathraWar.data; package me.ShermansWorld.AlathraWar.data;
import java.io.File; import me.ShermansWorld.AlathraWar.Main;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import me.ShermansWorld.AlathraWar.Main; import java.io.*;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.logging.Level;
/** /**
* Manages file IO & Deletion for other data classes. * Manages file IO & Deletion for other data classes.
*/ */
public class DataManager { public class DataManager {
private static DumperOptions options; private static DumperOptions options;
private static final String dataFolder = "plugins" + File.separator + "AlathraWar" + File.separator + "data";
public DataManager() { public DataManager() {
} }
private static String dataFolder = "plugins" + File.separator + "AlathraWar" + File.separator + "data"; /**
* Saves data into a .yml format
/** *
* Saves data into a .yml format * @param filePath - File's path after <PLUGIN>/Data/
* @param filePath - File's path after <PLUGIN>/Data/ * @param map - Map to be saved
* @param map - Map to be saved */
*/ public static void saveData(String filePath, HashMap<String, Object> map) {
public static void saveData(String filePath, HashMap<String,Object> map) { File file = getFile(filePath);
File file = getFile(filePath);
if (file == null) return; if (file == null) return;
Bukkit.getLogger().log(Level.WARNING, "scoreboard.yml printout"); Bukkit.getLogger().log(Level.WARNING, "scoreboard.yml printout");
@@ -45,7 +39,7 @@ public class DataManager {
Bukkit.getLogger().log(Level.WARNING, "Error Print canRead: " + (file == null ? "" : file.canRead())); Bukkit.getLogger().log(Level.WARNING, "Error Print canRead: " + (file == null ? "" : file.canRead()));
Bukkit.getLogger().log(Level.WARNING, "Error Print isHidden: " + (file == null ? "" : file.isHidden())); Bukkit.getLogger().log(Level.WARNING, "Error Print isHidden: " + (file == null ? "" : file.isHidden()));
Bukkit.getLogger().log(Level.WARNING, "Error Print path: " + (file == null ? "" : file.getPath())); Bukkit.getLogger().log(Level.WARNING, "Error Print path: " + (file == null ? "" : file.getPath()));
PrintWriter writer = null; PrintWriter writer;
try { try {
file.setWritable(true); file.setWritable(true);
writer = new PrintWriter(file); writer = new PrintWriter(file);
@@ -70,30 +64,32 @@ public class DataManager {
yaml.dump(map, writer); yaml.dump(map, writer);
writer.flush(); writer.flush();
writer.close(); writer.close();
} }
/**
* Gets the data back as a HashMap
* @param filePath - FilePath of data
* @return HashMap of data or null
*/
public static HashMap<String,Object> getData(String filePath) {
File file = getFile(filePath);
return getData(file);
}
/** /**
* Gets the data back as a HashMap * Gets the data back as a HashMap
*
* @param filePath - FilePath of data
* @return HashMap of data or null
*/
public static HashMap<String, Object> getData(String filePath) {
File file = getFile(filePath);
return getData(file);
}
/**
* Gets the data back as a HashMap
*
* @param file - Data file * @param file - Data file
* @return HashMap of data or null * @return HashMap of data or null
*/ */
public static HashMap<String,Object> getData(File file) { public static HashMap<String, Object> getData(File file) {
if (!file.exists()) { if (!file.exists()) {
Main.warLogger.log("Attempted to retrieve non-existant file: " + file.getPath()); Main.warLogger.log("Attempted to retrieve non-existant file: " + file.getPath());
return null; return null;
} }
InputStream inputStream = null; InputStream inputStream;
try { try {
inputStream = new FileInputStream(file); inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@@ -113,13 +109,14 @@ public class DataManager {
/** /**
* Deletes the specified file * Deletes the specified file
*
* @param filePath - FilePath of deletion * @param filePath - FilePath of deletion
* @return Boolean of success * @return Boolean of success
*/ */
public static boolean deleteFile(String filePath) { public static boolean deleteFile(String filePath) {
File file = getFile(filePath); File file = getFile(filePath);
if (!file.exists()) { if (!file.exists()) {
Main.warLogger.log("Attempted to retrieve non-existant file: " + filePath + ".yml"); Main.warLogger.log("Attempted to retrieve non-existant file: " + filePath + ".yml");
return false; return false;
} }
@@ -131,14 +128,15 @@ public class DataManager {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
} }
/** /**
* Converts filePath into File * Converts filePath into File
* @param path - File's path within data folder *
* @return File or null * @param path - File's path within data folder
*/ * @return File or null
private static File getFile(String path) { */
private static File getFile(String path) {
path = dataFolder + File.separator + path; path = dataFolder + File.separator + path;
File file = new File(path); File file = new File(path);
@@ -11,21 +11,25 @@ import me.ShermansWorld.AlathraWar.Raid;
import me.ShermansWorld.AlathraWar.War; import me.ShermansWorld.AlathraWar.War;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.*; import java.util.*;
public class RaidData { public class RaidData {
// Static Raid list for all active raids // Static Raid list for all active raids
private static ArrayList<Raid> raids = new ArrayList<Raid>(); private static final ArrayList<Raid> raids = new ArrayList<>();
public static ArrayList<Raid> getRaids() { public static ArrayList<Raid> getRaids() {
return raids; return raids;
} }
public static void setRaids(ArrayList<Raid> raids) {
for (Raid raid : raids) {
addRaid(raid);
}
}
/** /**
* Gets a raid with a specific name * Gets a raid with a specific name
@@ -40,12 +44,6 @@ public class RaidData {
return null; return null;
} }
public static void setRaids(ArrayList<Raid> raids) {
for (Raid raid : raids) {
addRaid(raid);
}
}
public static void addRaid(Raid raid) { public static void addRaid(Raid raid) {
if (raid == null) { if (raid == null) {
Main.warLogger.log("Attempted to add NULL to raid list."); Main.warLogger.log("Attempted to add NULL to raid list.");
@@ -80,7 +78,7 @@ public class RaidData {
//THIS MAY OR MAY NOT WORK //THIS MAY OR MAY NOT WORK
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("owner"))); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("owner")));
if(raidedTown == null || gatherTown == null) { if (raidedTown == null || gatherTown == null) {
return null; return null;
} }
Raid raid = new Raid(war, raidedTown, gatherTown, attackBoolean, offlinePlayer); Raid raid = new Raid(war, raidedTown, gatherTown, attackBoolean, offlinePlayer);
@@ -119,7 +117,7 @@ public class RaidData {
} }
public static ArrayList<Raid> createRaids(War war, Collection<HashMap<String, Object>> raidMaps) { public static ArrayList<Raid> createRaids(War war, Collection<HashMap<String, Object>> raidMaps) {
ArrayList<Raid> returnList = new ArrayList<Raid>(); ArrayList<Raid> returnList = new ArrayList<>();
for (HashMap<String, Object> map : raidMaps) { for (HashMap<String, Object> map : raidMaps) {
Town town = TownyAPI.getInstance().getTown((String) map.get("raidedTown")); Town town = TownyAPI.getInstance().getTown((String) map.get("raidedTown"));
if (town == null) continue; if (town == null) continue;
@@ -143,9 +141,9 @@ public class RaidData {
war.save(); war.save();
} }
/** // /**
* deletes raid, unused // * deletes raid, unused
*/ // */
// private static void deleteRaid(War war) { // private static void deleteRaid(War war) {
// File[] files = new File(dataFolderPath + File.separator + "wars").listFiles(ymlFilter); // File[] files = new File(dataFolderPath + File.separator + "wars").listFiles(ymlFilter);
// //
@@ -163,7 +161,7 @@ public class RaidData {
* @return Map * @return Map
*/ */
public static HashMap<String, Object> raidToMap(Raid raid) { public static HashMap<String, Object> raidToMap(Raid raid) {
HashMap<String, Object> returnMap = new HashMap<String, Object>(); HashMap<String, Object> returnMap = new HashMap<>();
// Shoves everything into a map. // Shoves everything into a map.
returnMap.put("name", raid.getName()); returnMap.put("name", raid.getName());
returnMap.put("raidedTown", raid.getRaidedTown().getName()); returnMap.put("raidedTown", raid.getRaidedTown().getName());
@@ -178,11 +176,20 @@ public class RaidData {
returnMap.put("owner", raid.getOwner().getUniqueId().toString()); returnMap.put("owner", raid.getOwner().getUniqueId().toString());
//create a list from the looted chunks //create a list from the looted chunks
List<Object> chunkList = new ArrayList<Object>(); final List<Object> chunkList = getChunkList(raid);
returnMap.put("lootedChunks", chunkList);
return returnMap;
}
@NotNull
private static List<Object> getChunkList(Raid raid) {
List<Object> chunkList = new ArrayList<>();
for (Raid.LootBlock b : raid.getLootedChunks().values()) { for (Raid.LootBlock b : raid.getLootedChunks().values()) {
HashMap<String, Object> blockMap = new HashMap<String, Object>(); HashMap<String, Object> blockMap = new HashMap<>();
//worldcoord //worldcoord
HashMap<String, Object> wcMap = new HashMap<String, Object>(); HashMap<String, Object> wcMap = new HashMap<>();
wcMap.put("world", b.worldCoord.getWorldName()); wcMap.put("world", b.worldCoord.getWorldName());
wcMap.put("x", b.worldCoord.getCoord().getX()); wcMap.put("x", b.worldCoord.getCoord().getX());
wcMap.put("z", b.worldCoord.getCoord().getZ()); wcMap.put("z", b.worldCoord.getCoord().getZ());
@@ -193,10 +200,7 @@ public class RaidData {
blockMap.put("finished", b.finished); blockMap.put("finished", b.finished);
chunkList.add(blockMap); chunkList.add(blockMap);
} }
return chunkList;
returnMap.put("lootedChunks", chunkList);
return returnMap;
} }
/** /**
@@ -206,7 +210,7 @@ public class RaidData {
* @return Map of Maps * @return Map of Maps
*/ */
public static HashMap<String, Object> getRaidMap(War war) { public static HashMap<String, Object> getRaidMap(War war) {
HashMap<String, Object> returnMap = new HashMap<String, Object>(); HashMap<String, Object> returnMap = new HashMap<>();
for (Raid raid : war.getRaids()) { for (Raid raid : war.getRaids()) {
returnMap.put(raid.getRaidedTown().getName(), raidToMap(raid)); returnMap.put(raid.getRaidedTown().getName(), raidToMap(raid));
} }
@@ -253,12 +257,12 @@ public class RaidData {
//make sure a player is online in the raided town //make sure a player is online in the raided town
boolean onlinePlayer = false; boolean onlinePlayer = false;
for(Resident r : town.getResidents()) { for (Resident r : town.getResidents()) {
if(r.isOnline()) { if (r.isOnline()) {
onlinePlayer = true; onlinePlayer = true;
} }
} }
if(!onlinePlayer) return -2; if (!onlinePlayer) return -2;
//check if being raided //check if being raided
for (Raid raid : war.getRaids()) { for (Raid raid : war.getRaids()) {
@@ -16,50 +16,52 @@ public enum RaidPhase {
public final int id; public final int id;
public final int startTick; public final int startTick;
private RaidPhase(int id, int startTick) { RaidPhase(int id, int startTick) {
this.id = id; this.id = id;
this.startTick = startTick; this.startTick = startTick;
} }
/** /**
* Grabs the phase by name, ignores case * Grabs the phase by name, ignores case
*
* @param name * @param name
* @return * @return
*/ */
public static RaidPhase getByName(String name) { public static RaidPhase getByName(String name) {
for(RaidPhase p : RaidPhase.values()) { for (RaidPhase p : RaidPhase.values()) {
if(p.name().equalsIgnoreCase(name)) return p; if (p.name().equalsIgnoreCase(name)) return p;
} }
return null; return null;
} }
/** /**
* Grabs phase by id number for easy storage reading * Grabs phase by id number for easy storage reading
*
* @param id * @param id
* @return * @return
*/ */
public static RaidPhase getByID(int id) { public static RaidPhase getByID(int id) {
for(RaidPhase p : RaidPhase.values()) { for (RaidPhase p : RaidPhase.values()) {
if(p.id == id) return p; if (p.id == id) return p;
} }
return null; return null;
} }
public static RaidPhase getNext(RaidPhase phase) { public static RaidPhase getNext(RaidPhase phase) {
switch (phase) { switch (phase) {
case START: { case START -> {
return GATHER; return GATHER;
} }
case GATHER: { case GATHER -> {
return TRAVEL; return TRAVEL;
} }
case TRAVEL: { case TRAVEL -> {
return COMBAT; return COMBAT;
} }
case COMBAT: { case COMBAT -> {
return END; return END;
} }
default: { default -> {
return null; return null;
} }
} }
@@ -1,31 +1,33 @@
package me.ShermansWorld.AlathraWar.data; package me.ShermansWorld.AlathraWar.data;
import java.util.*;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.Town;
import me.ShermansWorld.AlathraWar.Main; import me.ShermansWorld.AlathraWar.Main;
import me.ShermansWorld.AlathraWar.War;
import me.ShermansWorld.AlathraWar.Siege; import me.ShermansWorld.AlathraWar.Siege;
import me.ShermansWorld.AlathraWar.War;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
public class SiegeData import java.util.*;
{
public class SiegeData {
// Static Siege list for all active sieges // Static Siege list for all active sieges
private static HashSet<Siege> sieges = new HashSet<Siege>(); private static final HashSet<Siege> sieges = new HashSet<>();
public static HashSet<Siege> getSieges() { public static HashSet<Siege> getSieges() {
return sieges; return sieges;
} }
public static void setSieges(ArrayList<Siege> sieges) {
for (Siege siege : sieges) {
addSiege(siege);
}
}
/** /**
* Gets a siege with a specific name * Gets a siege with a specific name
*
* @param name - Name to check * @param name - Name to check
* @return Siege or Null * @return Siege or Null
*/ */
@@ -36,12 +38,6 @@ public class SiegeData
return null; return null;
} }
public static void setSieges(ArrayList<Siege> sieges) {
for (Siege siege : sieges) {
addSiege(siege);
}
}
public static void addSiege(Siege siege) { public static void addSiege(Siege siege) {
if (siege == null) { if (siege == null) {
Main.warLogger.log("Attempted to add NULL to siege list."); Main.warLogger.log("Attempted to add NULL to siege list.");
@@ -57,6 +53,7 @@ public class SiegeData
/** /**
* Creates a siege object from a provided HashMap * Creates a siege object from a provided HashMap
*
* @param fileData data * @param fileData data
* @return Siege object * @return Siege object
*/ */
@@ -69,14 +66,12 @@ public class SiegeData
Town town = TownyAPI.getInstance().getTown((String) fileData.get("town")); Town town = TownyAPI.getInstance().getTown((String) fileData.get("town"));
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("siegeLeader"))); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString((String) fileData.get("siegeLeader")));
Siege siege = new Siege(war, town, offlinePlayer); return new Siege(war, town, offlinePlayer);
return siege;
} }
/** /**
* Saves the war into files. * Saves the war into files.
*
* @param siege - Siege to be saved. * @param siege - Siege to be saved.
*/ */
public static void saveSiege(Siege siege) { public static void saveSiege(Siege siege) {
@@ -86,11 +81,12 @@ public class SiegeData
/** /**
* Turns a siege into a map * Turns a siege into a map
*
* @param siege - Siege * @param siege - Siege
* @return Map * @return Map
*/ */
public static HashMap<String, Object> siegeToMap(Siege siege) { public static HashMap<String, Object> siegeToMap(Siege siege) {
HashMap<String, Object> returnMap = new HashMap<String, Object>(); HashMap<String, Object> returnMap = new HashMap<>();
// Shoves everything into a map. // Shoves everything into a map.
returnMap.put("town", siege.getTown().getName()); returnMap.put("town", siege.getTown().getName());
returnMap.put("siegeTicks", siege.getSiegeTicks()); returnMap.put("siegeTicks", siege.getSiegeTicks());
@@ -104,11 +100,12 @@ public class SiegeData
/** /**
* Creates a map of siege maps * Creates a map of siege maps
*
* @param war - War to map * @param war - War to map
* @return Map of Maps * @return Map of Maps
*/ */
public static HashMap<String, Object> getSiegeMap(War war) { public static HashMap<String, Object> getSiegeMap(War war) {
HashMap<String, Object> returnMap = new HashMap<String, Object>(); HashMap<String, Object> returnMap = new HashMap<>();
for (Siege siege : war.getSieges()) { for (Siege siege : war.getSieges()) {
returnMap.put(siege.getTown().getName(), siegeToMap(siege)); returnMap.put(siege.getTown().getName(), siegeToMap(siege));
} }
@@ -116,7 +113,7 @@ public class SiegeData
} }
public static ArrayList<Siege> createSieges(War war, Collection<HashMap<String, Object>> siegeMaps) { public static ArrayList<Siege> createSieges(War war, Collection<HashMap<String, Object>> siegeMaps) {
ArrayList<Siege> returnList = new ArrayList<Siege>(); ArrayList<Siege> returnList = new ArrayList<>();
for (HashMap<String, Object> map : siegeMaps) { for (HashMap<String, Object> map : siegeMaps) {
Town town = TownyAPI.getInstance().getTown((String) map.get("town")); Town town = TownyAPI.getInstance().getTown((String) map.get("town"));
if (town == null) continue; if (town == null) continue;
@@ -1,9 +1,5 @@
package me.ShermansWorld.AlathraWar.data; package me.ShermansWorld.AlathraWar.data;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import me.ShermansWorld.AlathraWar.Main; import me.ShermansWorld.AlathraWar.Main;
import me.ShermansWorld.AlathraWar.Raid; import me.ShermansWorld.AlathraWar.Raid;
import me.ShermansWorld.AlathraWar.Siege; import me.ShermansWorld.AlathraWar.Siege;
@@ -11,36 +7,37 @@ import me.ShermansWorld.AlathraWar.War;
import java.io.File; import java.io.File;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
public class WarData public class WarData {
{
// Static War list for all active wars
private static ArrayList<War> wars = new ArrayList<War>();
private final static String dataFolderPath = "plugins" + File.separator + "AlathraWar" + File.separator + "data"; private final static String dataFolderPath = "plugins" + File.separator + "AlathraWar" + File.separator + "data";
// Static War list for all active wars
private static ArrayList<War> wars = new ArrayList<>();
// Filter for only accessing yml files // Filter for only accessing yml files
private static FilenameFilter ymlFilter = new FilenameFilter() { private static final FilenameFilter ymlFilter = (dir, name) -> name.endsWith(".yml");
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".yml");
}
};
// Constructor used to initialise folder. // Constructor used to initialise folder.
public WarData(final Main plugin) { public WarData(final Main plugin) {
File userDataFolder = new File(dataFolderPath + File.separator + "wars"); File userDataFolder = new File(dataFolderPath + File.separator + "wars");
if (!userDataFolder.exists()) { if (!userDataFolder.exists()) {
userDataFolder.mkdirs(); userDataFolder.mkdirs();
} }
} }
public static ArrayList<War> getWars() { public static ArrayList<War> getWars() {
return wars; return wars;
} }
public static void setWars(ArrayList<War> wars) {
WarData.wars = wars;
}
/** /**
* Gets a war with a specific name * Gets a war with a specific name
*
* @param name - Name to check * @param name - Name to check
* @return War or Null * @return War or Null
*/ */
@@ -51,10 +48,6 @@ public class WarData
return null; return null;
} }
public static void setWars(ArrayList<War> wars) {
WarData.wars = wars;
}
public static void addWar(War war) { public static void addWar(War war) {
if (war == null) { if (war == null) {
Main.warLogger.log("Attempted to add NULL to war list."); Main.warLogger.log("Attempted to add NULL to war list.");
@@ -70,12 +63,13 @@ public class WarData
/** /**
* Gets the wars currently saved in files as an ArrayList of War Objects * Gets the wars currently saved in files as an ArrayList of War Objects
*
* @return War Object ArrayList * @return War Object ArrayList
*/ */
public static ArrayList<War> createWars() { public static ArrayList<War> createWars() {
File[] files = new File(dataFolderPath + File.separator + "wars").listFiles(ymlFilter); File[] files = new File(dataFolderPath + File.separator + "wars").listFiles(ymlFilter);
ArrayList<War> returnList = new ArrayList<War>(); ArrayList<War> returnList = new ArrayList<>();
for (File file : files) { for (File file : files) {
try { try {
HashMap<String, Object> fileData = DataManager.getData(file); HashMap<String, Object> fileData = DataManager.getData(file);
@@ -92,6 +86,7 @@ public class WarData
/** /**
* Creates a war object from a provided HashMap * Creates a war object from a provided HashMap
*
* @param fileData * @param fileData
* @return War object * @return War object
*/ */
@@ -99,8 +94,8 @@ public class WarData
public static War fromMap(HashMap<String, Object> fileData) { public static War fromMap(HashMap<String, Object> fileData) {
War war = new War((String) fileData.get("name"), War war = new War((String) fileData.get("name"),
(String) fileData.get("side1"), (String) fileData.get("side1"),
(String) fileData.get("side2") (String) fileData.get("side2")
); );
war.setSide1Towns((ArrayList<String>) fileData.get("side1Towns")); war.setSide1Towns((ArrayList<String>) fileData.get("side1Towns"));
@@ -110,14 +105,14 @@ public class WarData
war.addSide1Points((int) fileData.get("side1Points")); war.addSide1Points((int) fileData.get("side1Points"));
war.addSide2Points((int) fileData.get("side2Points")); war.addSide2Points((int) fileData.get("side2Points"));
if(fileData.get("lastRaidTimeSide1") != null && fileData.get("lastRaidTimeSide2") != null) { if (fileData.get("lastRaidTimeSide1") != null && fileData.get("lastRaidTimeSide2") != null) {
war.setLastRaidTimeSide1((int) fileData.get("lastRaidTimeSide1")); war.setLastRaidTimeSide1((int) fileData.get("lastRaidTimeSide1"));
war.setLastRaidTimeSide2((int) fileData.get("lastRaidTimeSide2")); war.setLastRaidTimeSide2((int) fileData.get("lastRaidTimeSide2"));
} }
// Siege adding from map. // Siege adding from map.
Collection<HashMap<String, Object>> siegeMaps = ((HashMap<String,HashMap<String, Object>>) fileData.get("sieges")).values(); Collection<HashMap<String, Object>> siegeMaps = ((HashMap<String, HashMap<String, Object>>) fileData.get("sieges")).values();
ArrayList<Siege> sieges = SiegeData.createSieges(war, siegeMaps); ArrayList<Siege> sieges = SiegeData.createSieges(war, siegeMaps);
for (Siege siege : sieges) { for (Siege siege : sieges) {
war.addSiege(siege); war.addSiege(siege);
@@ -125,7 +120,7 @@ public class WarData
} }
// Raid adding from map. // Raid adding from map.
Collection<HashMap<String, Object>> raidMaps = ((HashMap<String,HashMap<String, Object>>) fileData.get("raids")).values(); Collection<HashMap<String, Object>> raidMaps = ((HashMap<String, HashMap<String, Object>>) fileData.get("raids")).values();
ArrayList<Raid> raids = RaidData.createRaids(war, raidMaps); ArrayList<Raid> raids = RaidData.createRaids(war, raidMaps);
for (Raid raid : raids) { for (Raid raid : raids) {
war.addRaid(raid); war.addRaid(raid);
@@ -136,18 +131,19 @@ public class WarData
/** /**
* Saves the war into files. * Saves the war into files.
*
* @param war - War to be saved. * @param war - War to be saved.
*/ */
public static void saveWar(War war) { public static void saveWar(War war) {
HashMap<String, Object> sHashMap = new HashMap<String,Object>(); HashMap<String, Object> sHashMap = new HashMap<>();
// Shoves everything into a map. // Shoves everything into a map.
sHashMap.put("name", war.getName()); sHashMap.put("name", war.getName());
sHashMap.put("side1", war.getSide1()); sHashMap.put("side1", war.getSide1());
sHashMap.put("side2", war.getSide2()); sHashMap.put("side2", war.getSide2());
sHashMap.put("side1Towns", (List<String>) war.getSide1Towns()); sHashMap.put("side1Towns", war.getSide1Towns());
sHashMap.put("side2Towns", (List<String>) war.getSide2Towns()); sHashMap.put("side2Towns", war.getSide2Towns());
sHashMap.put("surrenderedTowns", (List<String>) war.getSurrenderedTowns()); sHashMap.put("surrenderedTowns", war.getSurrenderedTowns());
sHashMap.put("side1Points", war.getSide1Points()); sHashMap.put("side1Points", war.getSide1Points());
sHashMap.put("side2Points", war.getSide2Points()); sHashMap.put("side2Points", war.getSide2Points());
@@ -1,96 +1,92 @@
package me.ShermansWorld.AlathraWar.hooks; package me.ShermansWorld.AlathraWar.hooks;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import me.ShermansWorld.AlathraWar.Helper; import me.ShermansWorld.AlathraWar.Helper;
import me.ShermansWorld.AlathraWar.War; import me.ShermansWorld.AlathraWar.War;
import me.neznamy.tab.api.TabAPI; import me.neznamy.tab.api.TabAPI;
import me.neznamy.tab.api.TabPlayer; import me.neznamy.tab.api.TabPlayer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
public class TABHook { public class TABHook {
public static boolean init = false; public static boolean init = false;
public static TabAPI tabAPI; public static TabAPI tabAPI;
public static void init() { public static void init() {
tabAPI = TabAPI.getInstance(); tabAPI = TabAPI.getInstance();
init = true; init = true;
} }
public static void assignSide1WarSuffix(Player p, War war) { public static void assignSide1WarSuffix(Player p, War war) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().setSuffix(tabPlayer, tabAPI.getTablistFormatManager().setSuffix(tabPlayer,
Helper.color("&c[") + war.getSide1() + "]&r"); Helper.color("&c[") + war.getSide1() + "]&r");
} }
public static void assignSide2WarSuffix(Player p, War war) { public static void assignSide2WarSuffix(Player p, War war) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().setSuffix(tabPlayer, tabAPI.getTablistFormatManager().setSuffix(tabPlayer,
Helper.color("&9[") + war.getSide2() + "]&r"); Helper.color("&9[") + war.getSide2() + "]&r");
} }
public static void assignSide1WarSuffixMerc(Player p, War war) { public static void assignSide1WarSuffixMerc(Player p, War war) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().setSuffix(tabPlayer, tabAPI.getTablistFormatManager().setSuffix(tabPlayer,
Helper.color("&a[M]&c[") + war.getSide1() + "]&r"); Helper.color("&a[M]&c[") + war.getSide1() + "]&r");
} }
public static void assignSide2WarSuffixMerc(Player p, War war) { public static void assignSide2WarSuffixMerc(Player p, War war) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().setSuffix(tabPlayer, tabAPI.getTablistFormatManager().setSuffix(tabPlayer,
Helper.color("&a[M]&9[") + war.getSide2() + "]&r"); Helper.color("&a[M]&9[") + war.getSide2() + "]&r");
} }
public static void resetSuffix(Player p) { public static void resetSuffix(Player p) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().resetSuffix(tabPlayer); tabAPI.getTablistFormatManager().resetSuffix(tabPlayer);
} }
public static void resetSuffix(String playername) { public static void resetSuffix(String playername) {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
OfflinePlayer op = Bukkit.getOfflinePlayer(playername); OfflinePlayer op = Bukkit.getOfflinePlayer(playername);
try { try {
if (op.isOnline()) { if (op.isOnline()) {
TabPlayer tabPlayer = tabAPI.getPlayer(playername); TabPlayer tabPlayer = tabAPI.getPlayer(playername);
tabAPI.getTablistFormatManager().resetSuffix(tabPlayer); tabAPI.getTablistFormatManager().resetSuffix(tabPlayer);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
return; }
} }
}
public static void resetPrefix(Player p) { public static void resetPrefix(Player p) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
tabAPI.getTablistFormatManager().resetPrefix(tabPlayer); tabAPI.getTablistFormatManager().resetPrefix(tabPlayer);
} }
public static void resetPrefix(String playername) { public static void resetPrefix(String playername) {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
OfflinePlayer op = Bukkit.getOfflinePlayer(playername); OfflinePlayer op = Bukkit.getOfflinePlayer(playername);
try { try {
if (op.isOnline()) { if (op.isOnline()) {
TabPlayer tabPlayer = tabAPI.getPlayer(playername); TabPlayer tabPlayer = tabAPI.getPlayer(playername);
tabAPI.getTablistFormatManager().resetPrefix(tabPlayer); tabAPI.getTablistFormatManager().resetPrefix(tabPlayer);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
return; }
} }
}
public static void removeColorPrefix(Player p, String prefix) { public static void removeColorPrefix(Player p, String prefix) {
TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId()); TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
if(prefix.length() > 2) { if (prefix.length() > 2) {
prefix = prefix.substring(0, prefix.length() - 2); prefix = prefix.substring(0, prefix.length() - 2);
} } else {
else{ Bukkit.getLogger().info("There is an error when removing a color prefix, prefix not long enough:");
Bukkit.getLogger().info("There is an error when removing a color prefix, prefix not long enough:"); Bukkit.getLogger().info("Player: " + p.getDisplayName());
Bukkit.getLogger().info("Player: " + p.getDisplayName()); Bukkit.getLogger().info("Prefix: " + prefix);
Bukkit.getLogger().info("Prefix: " + prefix); Bukkit.getLogger().info("------");
Bukkit.getLogger().info("------"); }
} tabAPI.getTablistFormatManager().setPrefix(tabPlayer, Helper.color(prefix));
tabAPI.getTablistFormatManager().setPrefix(tabPlayer, Helper.color(prefix)); }
}
} }
@@ -5,8 +5,8 @@ import org.bukkit.inventory.Recipe;
public interface IWarItem { public interface IWarItem {
public ItemStack getItemStack(); ItemStack getItemStack();
public Recipe getRecipe(); Recipe getRecipe();
} }
@@ -4,17 +4,16 @@ import me.ShermansWorld.AlathraWar.Helper;
import me.ShermansWorld.AlathraWar.Main; import me.ShermansWorld.AlathraWar.Main;
import me.ShermansWorld.AlathraWar.items.item.RamItem; import me.ShermansWorld.AlathraWar.items.item.RamItem;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class WarItemRegistry { public class WarItemRegistry {
private static WarItemRegistry instance;
private static final HashMap<String, IWarItem> itemRegistry = new HashMap<>();
public static final String namespace = Main.getInstance().getName().toLowerCase(); public static final String namespace = Main.getInstance().getName().toLowerCase();
private static final HashMap<String, IWarItem> itemRegistry = new HashMap<>();
private static WarItemRegistry instance;
/** /**
* loads all items into the plugin registry list * loads all items into the plugin registry list
@@ -37,6 +36,7 @@ public class WarItemRegistry {
/** /**
* generate a registry name * generate a registry name
*
* @param item * @param item
* @return * @return
*/ */
@@ -55,6 +55,7 @@ public class WarItemRegistry {
/** /**
* returns the associated itemstack with the item key, use for finding without namespace * returns the associated itemstack with the item key, use for finding without namespace
*
* @param registryName * @param registryName
* @return * @return
*/ */
@@ -65,6 +66,7 @@ public class WarItemRegistry {
/** /**
* returns the associated itemstack with the item key, use for finding with namespace * returns the associated itemstack with the item key, use for finding with namespace
*
* @param registryName * @param registryName
* @return * @return
*/ */
@@ -74,6 +76,7 @@ public class WarItemRegistry {
/** /**
* returns the associated IWarItem with the item key, use for finding with namespace * returns the associated IWarItem with the item key, use for finding with namespace
*
* @param registryName * @param registryName
* @return * @return
*/ */
@@ -9,9 +9,8 @@ import java.util.Set;
public class WarRecipeRegistry { public class WarRecipeRegistry {
private static WarRecipeRegistry instance;
private static final HashMap<String, Recipe> recipeRegistry = new HashMap<>(); private static final HashMap<String, Recipe> recipeRegistry = new HashMap<>();
private static WarRecipeRegistry instance;
public WarRecipeRegistry() { public WarRecipeRegistry() {
instance = this; instance = this;
@@ -23,6 +22,10 @@ public class WarRecipeRegistry {
Main.warLogger.log(Helper.chatLabel() + "Registered AlathraWar recipes."); Main.warLogger.log(Helper.chatLabel() + "Registered AlathraWar recipes.");
} }
public static WarRecipeRegistry getInstance() {
return instance;
}
public void register(String name, Set<Recipe> recipes) { public void register(String name, Set<Recipe> recipes) {
for (Recipe recipe : recipes) { for (Recipe recipe : recipes) {
// Bukkit.getServer().addRecipe(recipe); // Bukkit.getServer().addRecipe(recipe);
@@ -30,16 +33,13 @@ public class WarRecipeRegistry {
} }
} }
public static WarRecipeRegistry getInstance() {
return instance;
}
public HashMap<String, Recipe> getRecipeRegistry() { public HashMap<String, Recipe> getRecipeRegistry() {
return recipeRegistry; return recipeRegistry;
} }
/** /**
* returns the associated itemstack with the item key, use for finding without namespace * returns the associated itemstack with the item key, use for finding without namespace
*
* @param registryName recipe name without namespace * @param registryName recipe name without namespace
* @return recipe * @return recipe
*/ */
@@ -50,6 +50,7 @@ public class WarRecipeRegistry {
/** /**
* returns the associated itemstack with the item key, use for finding with namespace * returns the associated itemstack with the item key, use for finding with namespace
*
* @param registryName registry name including namespace * @param registryName registry name including namespace
* @return recipe * @return recipe
*/ */
@@ -22,7 +22,7 @@ public class RamItem implements IWarItem {
ItemMeta meta = ram.getItemMeta(); ItemMeta meta = ram.getItemMeta();
meta.setDisplayName("Door Ram"); meta.setDisplayName("Door Ram");
ArrayList<String> lore = new ArrayList<String>(); ArrayList<String> lore = new ArrayList<>();
meta.setLore(lore); meta.setLore(lore);
meta.setCustomModelData(14700); meta.setCustomModelData(14700);
@@ -1,102 +1,98 @@
package me.ShermansWorld.AlathraWar.listeners; package me.ShermansWorld.AlathraWar.listeners;
import com.palmergames.bukkit.towny.object.WorldCoord;
import me.ShermansWorld.AlathraWar.Helper;
import me.ShermansWorld.AlathraWar.Raid; import me.ShermansWorld.AlathraWar.Raid;
import me.ShermansWorld.AlathraWar.Siege;
import me.ShermansWorld.AlathraWar.data.RaidData; import me.ShermansWorld.AlathraWar.data.RaidData;
import me.ShermansWorld.AlathraWar.data.SiegeData;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import com.palmergames.bukkit.towny.object.WorldCoord;
import me.ShermansWorld.AlathraWar.Helper;
import me.ShermansWorld.AlathraWar.Siege;
import me.ShermansWorld.AlathraWar.data.SiegeData;
import org.bukkit.event.Listener;
public class BlockBreakListener implements Listener { public class BlockBreakListener implements Listener {
private static final Set<Material> allowedBlocks = new HashSet<>(); private static final Set<Material> allowedBlocks = new HashSet<>();
static { static {
allowedBlocks.add(Material.TNT); allowedBlocks.add(Material.TNT);
} }
@EventHandler @EventHandler
public void onBlockBreak(final BlockBreakEvent event) { public void onBlockBreak(final BlockBreakEvent event) {
final Block block = event.getBlock(); final Block block = event.getBlock();
if (SiegeData.getSieges().isEmpty() && RaidData.getRaids().isEmpty()) { if (SiegeData.getSieges().isEmpty() && RaidData.getRaids().isEmpty()) {
return; return;
} }
for (final Siege siege : SiegeData.getSieges()) { for (final Siege siege : SiegeData.getSieges()) {
if (siege.beaconLocs.contains(block.getLocation())) { if (siege.beaconLocs.contains(block.getLocation())) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
if (allowedBlocks.contains(block.getType())) { if (allowedBlocks.contains(block.getType())) {
return; return;
} }
Player p = event.getPlayer(); Player p = event.getPlayer();
if(p.hasPermission("AlathraWar.break")) { if (p.hasPermission("AlathraWar.break")) {
return; return;
} }
if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) { if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) {
for (final Siege siege : SiegeData.getSieges()) { for (final Siege siege : SiegeData.getSieges()) {
if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) { if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
p.sendMessage(Helper.color("&cYou can not break blocks during sieges")); p.sendMessage(Helper.color("&cYou can not break blocks during sieges"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
for (final Raid raid : RaidData.getRaids()) { for (final Raid raid : RaidData.getRaids()) {
if (raid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) { if (raid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
p.sendMessage(Helper.color("&cYou can not break blocks during raids")); p.sendMessage(Helper.color("&cYou can not break blocks during raids"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
} }
} }
@EventHandler @EventHandler
public void onBlockPlace(final BlockPlaceEvent event) { public void onBlockPlace(final BlockPlaceEvent event) {
final Block block = event.getBlock(); final Block block = event.getBlock();
if (SiegeData.getSieges().isEmpty() && RaidData.getRaids().isEmpty()) { if (SiegeData.getSieges().isEmpty() && RaidData.getRaids().isEmpty()) {
return; return;
} }
if (allowedBlocks.contains(block.getType())) { if (allowedBlocks.contains(block.getType())) {
return; return;
} }
Player p = event.getPlayer(); Player p = event.getPlayer();
if(p.hasPermission("AlathraWar.place")) { if (p.hasPermission("AlathraWar.place")) {
return; return;
} }
if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) { if (WorldCoord.parseWorldCoord(block).getTownOrNull() != null) {
for (final Siege siege : SiegeData.getSieges()) { for (final Siege siege : SiegeData.getSieges()) {
if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) { if (siege.getTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
p.sendMessage(Helper.color("&cYou can not place blocks during sieges")); p.sendMessage(Helper.color("&cYou can not place blocks during sieges"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
for (final Raid raid : RaidData.getRaids()) { for (final Raid raid : RaidData.getRaids()) {
if (raid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) { if (raid.getRaidedTown() == WorldCoord.parseWorldCoord(block).getTownOrNull()) {
p.sendMessage(Helper.color("&cYou can not place blocks during raids")); p.sendMessage(Helper.color("&cYou can not place blocks during raids"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
} }
} }
} }
@@ -72,81 +72,81 @@ public class CommandsListener implements Listener {
for (String prefix : prefixesTowny) { for (String prefix : prefixesTowny) {
//payment check //payment check
for (String cmd : blacklistedXLong) { for (String cmd : blacklistedXLong) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot modify this property during a raid!")); p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot modify this property during a raid!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
}
} }
} }
} }
//n spawn and t spawn }
if (args.length >= 2) { //n spawn and t spawn
//parse what we have, remove the starting sslash if (args.length >= 2) {
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1]; //parse what we have, remove the starting sslash
for (String prefix : prefixesTowny) { String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
//payment check for (String prefix : prefixesTowny) {
for (String cmd : payment) { //payment check
//check for each prefix for (String cmd : payment) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { //check for each prefix
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot withdraw money whilst in a raid!")); if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
event.setCancelled(true); p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot withdraw money whilst in a raid!"));
return; event.setCancelled(true);
} return;
} }
}
for (String cmd : blacklistedLong) { for (String cmd : blacklistedLong) {
//check for each prefix //check for each prefix
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
//check if in spawn //check if in spawn
if (p.getWorld().getName().equalsIgnoreCase("world")) { if (p.getWorld().getName().equalsIgnoreCase("world")) {
if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn") if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn")
|| parse.equalsIgnoreCase("t spawn") || parse.equalsIgnoreCase("town 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:n spawn") || parse.equalsIgnoreCase("towny:nat spawn") || parse.equalsIgnoreCase("towny:nation spawn")
|| parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) { || parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation.")); p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
return;
}
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eUse /t spawn, or /n spawn"));
event.setCancelled(true);
return; return;
} }
p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
//else p.sendMessage(Helper.chatLabel() + Helper.color("&eUse /t spawn, or /n spawn"));
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot teleport whilst in a raid!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
//else
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot teleport whilst in a raid!"));
event.setCancelled(true);
return;
} }
} }
} }
//random tp commands }
if (args.length >= 1) { //random tp commands
//parse what we have, remove the starting slash if (args.length >= 1) {
String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]; //parse what we have, remove the starting slash
for (String prefix : prefixes) { String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0];
for (String cmd : blacklistedShort) { for (String prefix : prefixes) {
//check for each prefix for (String cmd : blacklistedShort) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { //check for each prefix
//spawn world check if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
if (p.getWorld().getName().equalsIgnoreCase("world")) { //spawn world check
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation.")); if (p.getWorld().getName().equalsIgnoreCase("world")) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eUse /t spawn, or /n spawn")); p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
event.setCancelled(true); p.sendMessage(Helper.chatLabel() + Helper.color("&eUse /t spawn, or /n spawn"));
return;
}
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot teleport whilst in a raid!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot teleport whilst in a raid!"));
event.setCancelled(true);
return;
} }
} }
} }
} }
} }
} }
}
/* /*
Prevent players from teleporting during a siege Prevent players from teleporting during a siege
@@ -162,80 +162,80 @@ public class CommandsListener implements Listener {
for (String prefix : prefixesTowny) { for (String prefix : prefixesTowny) {
//payment check //payment check
for (String cmd : blacklistedXLong) { for (String cmd : blacklistedXLong) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot modify this property during a siege!")); p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot modify this property during a siege!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
}
} }
} }
} }
//n spawn and t spawn }
if (args.length >= 2) { //n spawn and t spawn
//parse what we have, remove the starting sslash if (args.length >= 2) {
String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1]; //parse what we have, remove the starting sslash
for (String prefix : prefixesTowny) { String parse = (args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]) + " " + args[1];
//payment check for (String prefix : prefixesTowny) {
for (String cmd : payment) { //payment check
//check for each prefix for (String cmd : payment) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { //check for each prefix
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot withdraw money whilst in a siege!")); if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
event.setCancelled(true); p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot withdraw money whilst in a siege!"));
return; event.setCancelled(true);
} return;
} }
}
for (String cmd : blacklistedLong) { for (String cmd : blacklistedLong) {
//check for each prefix //check for each prefix
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
//check if in spawn //check if in spawn
if (p.getWorld().getName().equalsIgnoreCase("world")) { if (p.getWorld().getName().equalsIgnoreCase("world")) {
if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn") if (parse.equalsIgnoreCase("n spawn") || parse.equalsIgnoreCase("nat spawn") || parse.equalsIgnoreCase("nation spawn")
|| parse.equalsIgnoreCase("t spawn") || parse.equalsIgnoreCase("town 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:n spawn") || parse.equalsIgnoreCase("towny:nat spawn") || parse.equalsIgnoreCase("towny:nation spawn")
|| parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) { || parse.equalsIgnoreCase("towny:t spawn") || parse.equalsIgnoreCase("towny:town spawn")) {
p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
return;
}
p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation.")); p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
p.sendMessage(Helper.chatLabel() + Helper.color("&eUse /t spawn, or /n spawn"));
event.setCancelled(true);
return; return;
} }
p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
//else p.sendMessage(Helper.chatLabel() + Helper.color("&eUse /t spawn, or /n spawn"));
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot teleport whilst in a siege!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
//else
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot teleport whilst in a siege!"));
event.setCancelled(true);
return;
} }
} }
} }
//random tp commands }
if (args.length >= 1) { //random tp commands
//parse what we have, remove the starting slash if (args.length >= 1) {
String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0]; //parse what we have, remove the starting slash
for (String prefix : prefixes) { String parse = args[0].charAt(0) == '/' ? args[0].substring(1) : args[0];
for (String cmd : blacklistedShort) { for (String prefix : prefixes) {
//check for each prefix for (String cmd : blacklistedShort) {
if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) { //check for each prefix
//spawn world check if (parse.equalsIgnoreCase(prefix + (prefix.isEmpty() ? "" : ":") + cmd)) {
if (p.getWorld().getName().equalsIgnoreCase("world")) { //spawn world check
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation.")); if (p.getWorld().getName().equalsIgnoreCase("world")) {
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&eUse /t spawn, or /n spawn")); p.sendMessage(Helper.chatLabel() + Helper.color("&eYou are stuck in spawn and are allowed to teleport to your town or nation."));
event.setCancelled(true); p.sendMessage(Helper.chatLabel() + Helper.color("&eUse /t spawn, or /n spawn"));
return;
}
p.sendMessage(String.valueOf(Helper.chatLabel()) + Helper.color("&cYou cannot teleport whilst in a siege!"));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
p.sendMessage(Helper.chatLabel() + Helper.color("&cYou cannot teleport whilst in a siege!"));
event.setCancelled(true);
return;
} }
} }
} }
} }
} }
}
} }
} }
@@ -1,27 +1,18 @@
package me.ShermansWorld.AlathraWar.listeners; package me.ShermansWorld.AlathraWar.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.TownyAPI;
import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.Town;
import me.ShermansWorld.AlathraWar.Main; import me.ShermansWorld.AlathraWar.Main;
import me.ShermansWorld.AlathraWar.War; import me.ShermansWorld.AlathraWar.War;
import me.ShermansWorld.AlathraWar.data.WarData; import me.ShermansWorld.AlathraWar.data.WarData;
import me.ShermansWorld.AlathraWar.hooks.TABHook; import me.ShermansWorld.AlathraWar.hooks.TABHook;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class JoinListener implements Listener { public class JoinListener implements Listener {
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final Player p = event.getPlayer();
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> checkPlayer(p), 60L); // 20 Tick (1 Second) delay before run() is called
}
public static void checkPlayer(Player p) { public static void checkPlayer(Player p) {
Town town = TownyAPI.getInstance().getResident(p).getTownOrNull(); Town town = TownyAPI.getInstance().getResident(p).getTownOrNull();
if (town == null) return; if (town == null) return;
@@ -40,4 +31,10 @@ public class JoinListener implements Listener {
TABHook.resetPrefix(p); TABHook.resetPrefix(p);
} }
} }
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final Player p = event.getPlayer();
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), () -> checkPlayer(p), 60L); // 20 Tick (1 Second) delay before run() is called
}
} }
@@ -21,8 +21,7 @@ import org.bukkit.event.player.PlayerRespawnEvent;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
public final class KillsListener implements Listener public final class KillsListener implements Listener {
{
public static final HashMap<UUID, Raid> respawnqueue = new HashMap<>(); public static final HashMap<UUID, Raid> respawnqueue = new HashMap<>();
@@ -34,8 +33,7 @@ public final class KillsListener implements Listener
Town town = null; Town town = null;
try { try {
town = WorldCoord.parseWorldCoord(killed).getTownBlock().getTown(); town = WorldCoord.parseWorldCoord(killed).getTownBlock().getTown();
} } catch (NotRegisteredException ex2) {
catch (NotRegisteredException ex2) {
ex2.printStackTrace(); ex2.printStackTrace();
} }
boolean playerCloseToHomeBlockSiege = false; boolean playerCloseToHomeBlockSiege = false;
@@ -82,7 +80,7 @@ public final class KillsListener implements Listener
respawnqueue.put(killed.getUniqueId(), raid); respawnqueue.put(killed.getUniqueId(), raid);
return; return;
} }
//teleport back to gather town spawn, without damaged gear //teleport back to gather town spawn, without damaged gear
//this is to disincentive people prekilling //this is to disincentive people prekilling
this.oocKill(killed, event); this.oocKill(killed, event);
raid.raiderKilledOutofCombat(event); raid.raiderKilledOutofCombat(event);
@@ -96,7 +94,7 @@ public final class KillsListener implements Listener
} }
if(killer == null) return; if (killer == null) return;
for (final Siege siege : SiegeData.getSieges()) { for (final Siege siege : SiegeData.getSieges()) {
final int homeBlockXCoord = siege.getTown().getHomeBlock().getCoord().getX() * 16; final int homeBlockXCoord = siege.getTown().getHomeBlock().getCoord().getX() * 16;
@@ -110,18 +108,18 @@ public final class KillsListener implements Listener
for (final String playerName : siege.getAttackerPlayers()) { for (final String playerName : siege.getAttackerPlayers()) {
try { try {
Player p = Bukkit.getPlayer(playerName); Player p = Bukkit.getPlayer(playerName);
if (p != null) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed! + 20 Attacker Points"); if (p != null)
} p.sendMessage(Helper.chatLabel() + "Defender killed! + 20 Attacker Points");
catch (NullPointerException ignored) { } catch (NullPointerException ignored) {
ignored.printStackTrace(); ignored.printStackTrace();
} }
} }
for (final String playerName : siege.getDefenderPlayers()) { for (final String playerName : siege.getDefenderPlayers()) {
try { try {
Player p = Bukkit.getPlayer(playerName); Player p = Bukkit.getPlayer(playerName);
if (p != null) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Defender killed! + 20 Attacker Points"); if (p != null)
} p.sendMessage(Helper.chatLabel() + "Defender killed! + 20 Attacker Points");
catch (NullPointerException ignored) { } catch (NullPointerException ignored) {
ignored.printStackTrace(); ignored.printStackTrace();
} }
} }
@@ -135,18 +133,18 @@ public final class KillsListener implements Listener
for (final String playerName : siege.getAttackerPlayers()) { for (final String playerName : siege.getAttackerPlayers()) {
try { try {
Player p = Bukkit.getPlayer(playerName); Player p = Bukkit.getPlayer(playerName);
if (p != null) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Attacker killed! + 20 Defender Points"); if (p != null)
} p.sendMessage(Helper.chatLabel() + "Attacker killed! + 20 Defender Points");
catch (NullPointerException ex3) { } catch (NullPointerException ex3) {
ex3.printStackTrace(); ex3.printStackTrace();
} }
} }
for (final String playerName : siege.getDefenderPlayers()) { for (final String playerName : siege.getDefenderPlayers()) {
try { try {
Player p = Bukkit.getPlayer(playerName); Player p = Bukkit.getPlayer(playerName);
if (p != null) p.sendMessage(String.valueOf(Helper.chatLabel()) + "Attacker killed! + 20 Defender Points"); if (p != null)
} p.sendMessage(Helper.chatLabel() + "Attacker killed! + 20 Defender Points");
catch (NullPointerException ex4) { } catch (NullPointerException ex4) {
ex4.printStackTrace(); ex4.printStackTrace();
} }
} }
@@ -154,13 +152,12 @@ public final class KillsListener implements Listener
this.siegeKill(killed, event); this.siegeKill(killed, event);
return; return;
} }
if ( (town != null && town.equals(siege.getTown()) || playerCloseToHomeBlockSiege) ) { if ((town != null && town.equals(siege.getTown()) || playerCloseToHomeBlockSiege)) {
this.siegeKill(killed, event); this.siegeKill(killed, event);
} }
} }
} } catch (NullPointerException | TownyException ignored) {
catch (NullPointerException | TownyException ignored) {
ignored.printStackTrace(); ignored.printStackTrace();
} }
} }
@@ -172,18 +169,18 @@ public final class KillsListener implements Listener
*/ */
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onRespawn(PlayerRespawnEvent event) { public void onRespawn(PlayerRespawnEvent event) {
if(respawnqueue.containsKey(event.getPlayer().getUniqueId())) { if (respawnqueue.containsKey(event.getPlayer().getUniqueId())) {
Raid raid = respawnqueue.get(event.getPlayer().getUniqueId()); Raid raid = respawnqueue.get(event.getPlayer().getUniqueId());
if (raid == null) return; if (raid == null) return;
if(raid.getActiveRaiders().contains(event.getPlayer().getName())) { if (raid.getActiveRaiders().contains(event.getPlayer().getName())) {
//do raider respawn //do raider respawn
try { try {
event.setRespawnLocation(raid.getGatherTown().getSpawn()); event.setRespawnLocation(raid.getGatherTown().getSpawn());
event.getPlayer().sendMessage(String.valueOf(Helper.chatLabel()) + "You died " + (raid.getPhase().equals(RaidPhase.COMBAT) ? "raiding" : "before combat") + " and have been teleported back to the gather point."); event.getPlayer().sendMessage(Helper.chatLabel() + "You died " + (raid.getPhase().equals(RaidPhase.COMBAT) ? "raiding" : "before combat") + " and have been teleported back to the gather point.");
} catch (TownyException e) { } catch (TownyException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} else if(raid.getDefenderSide().contains(event.getPlayer().getName())) { } else if (raid.getDefenderSide().contains(event.getPlayer().getName())) {
//do defender respawn ? //do defender respawn ?
} else { } else {
//invalid code //invalid code
@@ -196,8 +193,9 @@ public final class KillsListener implements Listener
/** /**
* Damage all gear held by the player (and then send them to spawn?) * Damage all gear held by the player (and then send them to spawn?)
* They don't lose items from death. * They don't lose items from death.
*
* @param killed killed player * @param killed killed player
* @param event event * @param event event
*/ */
private void siegeKill(final Player killed, final PlayerDeathEvent event) { private void siegeKill(final Player killed, final PlayerDeathEvent event) {
//Helper //Helper
@@ -215,7 +213,7 @@ public final class KillsListener implements Listener
* They don't lose items from death. * They don't lose items from death.
* *
* @param killed killed player * @param killed killed player
* @param event event * @param event event
*/ */
private void raidKill(final Player killed, final PlayerDeathEvent event) { private void raidKill(final Player killed, final PlayerDeathEvent event) {
//Helper //Helper
@@ -233,7 +231,7 @@ public final class KillsListener implements Listener
* They don't lose items from death. * They don't lose items from death.
* *
* @param killed killed player * @param killed killed player
* @param event event * @param event event
*/ */
private void oocKill(final Player killed, final PlayerDeathEvent event) { private void oocKill(final Player killed, final PlayerDeathEvent event) {
//Siege specific //Siege specific
@@ -31,24 +31,24 @@ import java.util.Set;
public class PlayerInteractListener implements Listener { public class PlayerInteractListener implements Listener {
//predefined foor materials //predefined foor materials
private static Set<Material> doors = new HashSet<Material>(); private static final Set<Material> doors = new HashSet<>();
static { static {
doors.add(Material.ACACIA_DOOR); doors.add(Material.ACACIA_DOOR);
doors.add(Material.BIRCH_DOOR); doors.add(Material.BIRCH_DOOR);
doors.add(Material.CRIMSON_DOOR); doors.add(Material.CRIMSON_DOOR);
doors.add(Material.DARK_OAK_DOOR); doors.add(Material.DARK_OAK_DOOR);
doors.add(Material.IRON_DOOR); doors.add(Material.IRON_DOOR);
doors.add(Material.JUNGLE_DOOR); doors.add(Material.JUNGLE_DOOR);
doors.add(Material.MANGROVE_DOOR); doors.add(Material.MANGROVE_DOOR);
doors.add(Material.OAK_DOOR); doors.add(Material.OAK_DOOR);
doors.add(Material.SPRUCE_DOOR); doors.add(Material.SPRUCE_DOOR);
doors.add(Material.WARPED_DOOR); doors.add(Material.WARPED_DOOR);
} }
//map of broken doors //map of broken doors
public Map<Location, Long> brokenDoors = new HashMap<Location, Long>(); public Map<Location, Long> brokenDoors = new HashMap<>();
/** /**
* @param event event * @param event event
@@ -106,17 +106,17 @@ public class PlayerInteractListener implements Listener {
door.setOpen(!door.isOpen()); door.setOpen(!door.isOpen());
clicked.setBlockData(door); clicked.setBlockData(door);
player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount() - 1); player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount() - 1);
Main.warLogger.log("User " + player.getName() + " has broken down door" + clicked.getLocation().toString()); Main.warLogger.log("User " + player.getName() + " has broken down door" + clicked.getLocation());
} else { } else {
player.sendMessage(Helper.chatLabel() + Helper.color("&cThis item can only be used in a siege or raid!")); player.sendMessage(Helper.chatLabel() + Helper.color("&cThis item can only be used in a siege or raid!"));
} }
event.setCancelled(true); event.setCancelled(true);
return;
} }
} }
} }
} }
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRClick(final PlayerItemDamageEvent event) { public void onPlayerRClick(final PlayerItemDamageEvent event) {
ItemStack item = event.getItem(); ItemStack item = event.getItem();
@@ -158,7 +158,6 @@ public class PlayerInteractListener implements Listener {
|| clicked.getType().name().equals("ROOTED_DIRT") || clicked.getType().name().equals("ROOTED_DIRT")
|| clicked.getType().name().equals("DIRT_PATH")) { || clicked.getType().name().equals("DIRT_PATH")) {
event.setCancelled(true); event.setCancelled(true);
return;
} }
} }
} }
@@ -166,21 +165,21 @@ public class PlayerInteractListener implements Listener {
} }
private Location getDoorPos(Block clicked, Door door) { private Location getDoorPos(Block clicked, Door door) {
if(door.getHalf() == Bisected.Half.BOTTOM) { if (door.getHalf() == Bisected.Half.BOTTOM) {
return clicked.getLocation().clone(); return clicked.getLocation().clone();
} else if(door.getHalf() == Bisected.Half.TOP) { } else if (door.getHalf() == Bisected.Half.TOP) {
return clicked.getLocation().subtract(0.0, 1.0, 0.0).clone(); return clicked.getLocation().subtract(0.0, 1.0, 0.0).clone();
} }
return clicked.getLocation().clone(); return clicked.getLocation().clone();
} }
private boolean doorBroken(@Nonnull Block clicked, Door door) { private boolean doorBroken(@Nonnull Block clicked, Door door) {
if(door.getHalf() == Bisected.Half.BOTTOM) { if (door.getHalf() == Bisected.Half.BOTTOM) {
if(brokenDoors.get(clicked.getLocation()) != null) { if (brokenDoors.get(clicked.getLocation()) != null) {
return brokenDoors.get(clicked.getLocation()) > System.currentTimeMillis(); return brokenDoors.get(clicked.getLocation()) > System.currentTimeMillis();
} }
} else if(door.getHalf() == Bisected.Half.TOP) { } else if (door.getHalf() == Bisected.Half.TOP) {
if(brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) != null) { 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 brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) > System.currentTimeMillis();
} }
} }