Strip trailing whitespace; add missing newlines.

This promiscuous commit goes around touching almost every file in the
repository with the intention of removing trailing whitespace and adding
newlines to files missing them.

Trailing whitespace has been a pain for along time, especially in terms
of contributing to the project without accidentally littering commits
with whitespace stripping, so this commit is long overdue.

As for the newlines, well, the script I found on StackOverflow to strip
trailing whitespace also happened to add missing newlines, which is
something I wanted to tackle anyway, but in a different commit. It's all
good though.
This commit is contained in:
Andreas Troelsen
2020-08-21 00:23:14 +02:00
parent 043d970593
commit 514c03dad0
113 changed files with 1198 additions and 1198 deletions
@@ -33,7 +33,7 @@ public class ArenaClass
public ArenaClass(String name, Thing price, boolean unbreakableWeapons, boolean unbreakableArmor) { public ArenaClass(String name, Thing price, boolean unbreakableWeapons, boolean unbreakableArmor) {
this.configName = name; this.configName = name;
this.lowercaseName = name.toLowerCase().replace(" ", ""); this.lowercaseName = name.toLowerCase().replace(" ", "");
this.items = new ArrayList<>(); this.items = new ArrayList<>();
this.armor = new ArrayList<>(4); this.armor = new ArrayList<>(4);
this.effects = new ArrayList<>(); this.effects = new ArrayList<>();
@@ -45,7 +45,7 @@ public class ArenaClass
this.price = price; this.price = price;
} }
/** /**
* Get the name of the arena class as it appears in the config-file. * Get the name of the arena class as it appears in the config-file.
* @return the class name as it appears in the config-file * @return the class name as it appears in the config-file
@@ -53,7 +53,7 @@ public class ArenaClass
public String getConfigName() { public String getConfigName() {
return configName; return configName;
} }
/** /**
* Get the lowercase class name. * Get the lowercase class name.
* @return the lowercase class name * @return the lowercase class name
@@ -61,7 +61,7 @@ public class ArenaClass
public String getLowercaseName() { public String getLowercaseName() {
return lowercaseName; return lowercaseName;
} }
/** /**
* Set the helmet slot for the class. * Set the helmet slot for the class.
* @param helmet a Thing * @param helmet a Thing
@@ -69,7 +69,7 @@ public class ArenaClass
public void setHelmet(Thing helmet) { public void setHelmet(Thing helmet) {
this.helmet = helmet; this.helmet = helmet;
} }
/** /**
* Set the chestplate slot for the class. * Set the chestplate slot for the class.
* @param chestplate a Thing * @param chestplate a Thing
@@ -77,7 +77,7 @@ public class ArenaClass
public void setChestplate(Thing chestplate) { public void setChestplate(Thing chestplate) {
this.chestplate = chestplate; this.chestplate = chestplate;
} }
/** /**
* Set the leggings slot for the class. * Set the leggings slot for the class.
* @param leggings a Thing * @param leggings a Thing
@@ -85,7 +85,7 @@ public class ArenaClass
public void setLeggings(Thing leggings) { public void setLeggings(Thing leggings) {
this.leggings = leggings; this.leggings = leggings;
} }
/** /**
* Set the boots slot for the class. * Set the boots slot for the class.
* @param boots a Thing * @param boots a Thing
@@ -93,7 +93,7 @@ public class ArenaClass
public void setBoots(Thing boots) { public void setBoots(Thing boots) {
this.boots = boots; this.boots = boots;
} }
/** /**
* Set the off-hand slot for the class. * Set the off-hand slot for the class.
* @param offhand a Thing * @param offhand a Thing
@@ -111,7 +111,7 @@ public class ArenaClass
items.add(item); items.add(item);
} }
} }
/** /**
* Replace the current items list with a new list of all the items in the given list. * Replace the current items list with a new list of all the items in the given list.
* This method uses the addItem() method for each item to ensure consistency. * This method uses the addItem() method for each item to ensure consistency.
@@ -121,7 +121,7 @@ public class ArenaClass
this.items = new ArrayList<>(items.size()); this.items = new ArrayList<>(items.size());
items.forEach(this::addItem); items.forEach(this::addItem);
} }
/** /**
* Replace the current armor list with the given list. * Replace the current armor list with the given list.
* @param armor a list of Things * @param armor a list of Things
@@ -133,7 +133,7 @@ public class ArenaClass
public void setEffects(List<Thing> effects) { public void setEffects(List<Thing> effects) {
this.effects = effects; this.effects = effects;
} }
public boolean hasPermission(Player p) { public boolean hasPermission(Player p) {
String perm = "mobarena.classes." + configName; String perm = "mobarena.classes." + configName;
return !p.isPermissionSet(perm) || p.hasPermission(perm); return !p.isPermissionSet(perm) || p.hasPermission(perm);
@@ -144,7 +144,7 @@ public class ArenaClass
* The normal items will be added to the inventory normally, while the * The normal items will be added to the inventory normally, while the
* armor items will be verified as armor items and placed in their * armor items will be verified as armor items and placed in their
* appropriate slots. If any specific armor slots are specified, they * appropriate slots. If any specific armor slots are specified, they
* will overwrite any items in the armor list. * will overwrite any items in the armor list.
* @param p a player * @param p a player
*/ */
public void grantItems(Player p) { public void grantItems(Player p) {
@@ -152,7 +152,7 @@ public class ArenaClass
// Fork over the items. // Fork over the items.
items.forEach(item -> item.giveTo(p)); items.forEach(item -> item.giveTo(p));
// Check for legacy armor-node items // Check for legacy armor-node items
armor.forEach(thing -> thing.giveTo(p)); armor.forEach(thing -> thing.giveTo(p));
@@ -167,7 +167,7 @@ public class ArenaClass
public void grantPotionEffects(Player p) { public void grantPotionEffects(Player p) {
effects.forEach(thing -> thing.giveTo(p)); effects.forEach(thing -> thing.giveTo(p));
} }
/** /**
* Add a permission value to the class. * Add a permission value to the class.
*/ */
@@ -212,17 +212,17 @@ public class ArenaClass
public Thing getPrice() { public Thing getPrice() {
return price; return price;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null) return false; if (o == null) return false;
if (this == o) return true; if (this == o) return true;
if (!this.getClass().equals(o.getClass())) return false; if (!this.getClass().equals(o.getClass())) return false;
ArenaClass other = (ArenaClass) o; ArenaClass other = (ArenaClass) o;
return other.lowercaseName.equals(this.lowercaseName); return other.lowercaseName.equals(this.lowercaseName);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return lowercaseName.hashCode(); return lowercaseName.hashCode();
@@ -75,57 +75,57 @@ public class ArenaImpl implements Arena
private String name; private String name;
private World world; private World world;
private Messenger messenger; private Messenger messenger;
// Settings section of the config-file for this arena. // Settings section of the config-file for this arena.
private ConfigurationSection settings; private ConfigurationSection settings;
// Run-time settings and critical config settings // Run-time settings and critical config settings
private boolean enabled, protect, running, edit; private boolean enabled, protect, running, edit;
// World stuff // World stuff
private boolean allowMonsters, allowAnimals; private boolean allowMonsters, allowAnimals;
//private Difficulty spawnMonsters; //private Difficulty spawnMonsters;
// Warps, points and locations // Warps, points and locations
private ArenaRegion region; private ArenaRegion region;
private Leaderboard leaderboard; private Leaderboard leaderboard;
// Player stuff // Player stuff
private InventoryManager inventoryManager; private InventoryManager inventoryManager;
private RewardManager rewardManager; private RewardManager rewardManager;
private ClassLimitManager limitManager; private ClassLimitManager limitManager;
private Map<Player,ArenaPlayer> arenaPlayerMap; private Map<Player,ArenaPlayer> arenaPlayerMap;
private Set<Player> arenaPlayers, lobbyPlayers, readyPlayers, specPlayers, deadPlayers; private Set<Player> arenaPlayers, lobbyPlayers, readyPlayers, specPlayers, deadPlayers;
private Set<Player> movingPlayers; private Set<Player> movingPlayers;
private Set<Player> leavingPlayers; private Set<Player> leavingPlayers;
private Set<Player> randoms; private Set<Player> randoms;
// Classes stuff // Classes stuff
private ArenaClass defaultClass; private ArenaClass defaultClass;
private Map<String,ArenaClass> classes; private Map<String,ArenaClass> classes;
// Blocks and pets // Blocks and pets
private PriorityBlockingQueue<Repairable> repairQueue; private PriorityBlockingQueue<Repairable> repairQueue;
private Set<Block> blocks; private Set<Block> blocks;
private LinkedList<Repairable> repairables, containables; private LinkedList<Repairable> repairables, containables;
// Monster stuff // Monster stuff
private MonsterManager monsterManager; private MonsterManager monsterManager;
// Wave stuff // Wave stuff
private WaveManager waveManager; private WaveManager waveManager;
private MASpawnThread spawnThread; private MASpawnThread spawnThread;
private SheepBouncer sheepBouncer; private SheepBouncer sheepBouncer;
private Map<Integer,List<Thing>> everyWaveMap, afterWaveMap; private Map<Integer,List<Thing>> everyWaveMap, afterWaveMap;
// Misc // Misc
private ArenaListener eventListener; private ArenaListener eventListener;
private List<Thing> entryFee; private List<Thing> entryFee;
private AutoStartTimer autoStartTimer; private AutoStartTimer autoStartTimer;
private StartDelayTimer startDelayTimer; private StartDelayTimer startDelayTimer;
private boolean isolatedChat; private boolean isolatedChat;
// Warp offsets // Warp offsets
private double arenaWarpOffset; private double arenaWarpOffset;
@@ -134,7 +134,7 @@ public class ArenaImpl implements Arena
// Last player standing // Last player standing
private Player lastStanding; private Player lastStanding;
// Actions // Actions
private Map<Player, Step> histories; private Map<Player, Step> histories;
private StepFactory playerJoinArena; private StepFactory playerJoinArena;
@@ -148,13 +148,13 @@ public class ArenaImpl implements Arena
public ArenaImpl(MobArena plugin, ConfigurationSection section, String name, World world) { public ArenaImpl(MobArena plugin, ConfigurationSection section, String name, World world) {
if (world == null) if (world == null)
throw new NullPointerException("[MobArena] ERROR! World for arena '" + name + "' does not exist!"); throw new NullPointerException("[MobArena] ERROR! World for arena '" + name + "' does not exist!");
this.name = name; this.name = name;
this.world = world; this.world = world;
this.plugin = plugin; this.plugin = plugin;
this.settings = makeSection(section, "settings"); this.settings = makeSection(section, "settings");
this.region = new ArenaRegion(section, this); this.region = new ArenaRegion(section, this);
this.enabled = settings.getBoolean("enabled", false); this.enabled = settings.getBoolean("enabled", false);
this.protect = settings.getBoolean("protect", true); this.protect = settings.getBoolean("protect", true);
this.running = false; this.running = false;
@@ -185,21 +185,21 @@ public class ArenaImpl implements Arena
if (defaultClassName != null) { if (defaultClassName != null) {
this.defaultClass = classes.get(defaultClassName); this.defaultClass = classes.get(defaultClassName);
} }
// Blocks and pets // Blocks and pets
this.repairQueue = new PriorityBlockingQueue<>(100, new RepairableComparator()); this.repairQueue = new PriorityBlockingQueue<>(100, new RepairableComparator());
this.blocks = new HashSet<>(); this.blocks = new HashSet<>();
this.repairables = new LinkedList<>(); this.repairables = new LinkedList<>();
this.containables = new LinkedList<>(); this.containables = new LinkedList<>();
// Monster stuff // Monster stuff
this.monsterManager = new MonsterManager(); this.monsterManager = new MonsterManager();
// Wave stuff // Wave stuff
this.waveManager = new WaveManager(this, section.getConfigurationSection("waves")); this.waveManager = new WaveManager(this, section.getConfigurationSection("waves"));
this.everyWaveMap = MAUtils.getArenaRewardMap(plugin, section, name, "every"); this.everyWaveMap = MAUtils.getArenaRewardMap(plugin, section, name, "every");
this.afterWaveMap = MAUtils.getArenaRewardMap(plugin, section, name, "after"); this.afterWaveMap = MAUtils.getArenaRewardMap(plugin, section, name, "after");
// Misc // Misc
this.eventListener = new ArenaListener(this, plugin); this.eventListener = new ArenaListener(this, plugin);
this.allowMonsters = world.getAllowMonsters(); this.allowMonsters = world.getAllowMonsters();
@@ -222,7 +222,7 @@ public class ArenaImpl implements Arena
this.startDelayTimer = new StartDelayTimer(this, autoStartTimer); this.startDelayTimer = new StartDelayTimer(this, autoStartTimer);
this.isolatedChat = settings.getBoolean("isolated-chat", false); this.isolatedChat = settings.getBoolean("isolated-chat", false);
this.arenaWarpOffset = settings.getDouble("arena-warp-offset", 0.0); this.arenaWarpOffset = settings.getDouble("arena-warp-offset", 0.0);
// Scoreboards // Scoreboards
@@ -239,15 +239,15 @@ public class ArenaImpl implements Arena
this.spawnsPets = plugin.getArenaMaster().getSpawnsPets(); this.spawnsPets = plugin.getArenaMaster().getSpawnsPets();
} }
/*///////////////////////////////////////////////////////////////////////// /*/////////////////////////////////////////////////////////////////////////
// //
// NEW METHODS IN REFACTORING // NEW METHODS IN REFACTORING
// //
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
@Override @Override
public ConfigurationSection getSettings() { public ConfigurationSection getSettings() {
return settings; return settings;
@@ -312,7 +312,7 @@ public class ArenaImpl implements Arena
public int getMaxPlayers() { public int getMaxPlayers() {
return settings.getInt("max-players"); return settings.getInt("max-players");
} }
private int getJoinDistance() { private int getJoinDistance() {
return settings.getInt("max-join-distance"); return settings.getInt("max-join-distance");
} }
@@ -421,25 +421,25 @@ public class ArenaImpl implements Arena
public MonsterManager getMonsterManager() { public MonsterManager getMonsterManager() {
return monsterManager; return monsterManager;
} }
@Override @Override
public ClassLimitManager getClassLimitManager() { public ClassLimitManager getClassLimitManager() {
return limitManager; return limitManager;
} }
@Override @Override
public ScoreboardManager getScoreboard() { public ScoreboardManager getScoreboard() {
return scoreboard; return scoreboard;
} }
@Override @Override
public Messenger getMessenger() { public Messenger getMessenger() {
@@ -492,26 +492,26 @@ public class ArenaImpl implements Arena
// Store all chest contents. // Store all chest contents.
storeContainerContents(); storeContainerContents();
// Populate arenaPlayers and clear the lobby. // Populate arenaPlayers and clear the lobby.
arenaPlayers.addAll(lobbyPlayers); arenaPlayers.addAll(lobbyPlayers);
lobbyPlayers.clear(); lobbyPlayers.clear();
readyPlayers.clear(); readyPlayers.clear();
// Assign random classes. // Assign random classes.
for (Player p : randoms) { for (Player p : randoms) {
assignRandomClass(p); assignRandomClass(p);
} }
randoms.clear(); randoms.clear();
// Then check if there are still players left. // Then check if there are still players left.
if (arenaPlayers.isEmpty()) { if (arenaPlayers.isEmpty()) {
return false; return false;
} }
// Initialize scoreboards // Initialize scoreboards
scoreboard.initialize(); scoreboard.initialize();
// Teleport players, give full health, initialize map // Teleport players, give full health, initialize map
for (Player p : arenaPlayers) { for (Player p : arenaPlayers) {
// Remove player from spec list to avoid invincibility issues // Remove player from spec list to avoid invincibility issues
@@ -520,7 +520,7 @@ public class ArenaImpl implements Arena
System.out.println("[MobArena] Player " + p.getName() + " joined the arena from the spec area!"); System.out.println("[MobArena] Player " + p.getName() + " joined the arena from the spec area!");
System.out.println("[MobArena] Invincibility glitch attempt stopped!"); System.out.println("[MobArena] Invincibility glitch attempt stopped!");
} }
movingPlayers.add(p); movingPlayers.add(p);
if (arenaWarpOffset > 0.01) { if (arenaWarpOffset > 0.01) {
Location warp = region.getArenaWarp(); Location warp = region.getArenaWarp();
@@ -541,35 +541,35 @@ public class ArenaImpl implements Arena
if (price != null) { if (price != null) {
price.takeFrom(p); price.takeFrom(p);
} }
scoreboard.addPlayer(p); scoreboard.addPlayer(p);
} }
// Start spawning monsters (must happen before 'running = true;') // Start spawning monsters (must happen before 'running = true;')
startSpawner(); startSpawner();
startBouncingSheep(); startBouncingSheep();
// Set the boolean. // Set the boolean.
running = true; running = true;
// Spawn pets (must happen after 'running = true;') // Spawn pets (must happen after 'running = true;')
spawnsPets.spawn(this); spawnsPets.spawn(this);
// Spawn mounts // Spawn mounts
spawnMounts(); spawnMounts();
// Clear the classes in use map, as they're no longer needed // Clear the classes in use map, as they're no longer needed
limitManager.clearClassesInUse(); limitManager.clearClassesInUse();
// Reset rewards // Reset rewards
rewardManager.reset(); rewardManager.reset();
// Initialize leaderboards and start displaying info. // Initialize leaderboards and start displaying info.
leaderboard.initialize(); leaderboard.initialize();
leaderboard.startTracking(); leaderboard.startTracking();
announce(Msg.ARENA_START); announce(Msg.ARENA_START);
return true; return true;
} }
@@ -589,16 +589,16 @@ public class ArenaImpl implements Arena
// Reset last standing // Reset last standing
lastStanding = null; lastStanding = null;
// Set the running boolean and disable arena if not disabled. // Set the running boolean and disable arena if not disabled.
boolean en = enabled; boolean en = enabled;
enabled = false; enabled = false;
running = false; running = false;
// Stop tracking leaderboards // Stop tracking leaderboards
leaderboard.stopTracking(); leaderboard.stopTracking();
leaderboard.update(); leaderboard.update();
// Stop spawning. // Stop spawning.
stopSpawner(); stopSpawner();
stopBouncingSheep(); stopBouncingSheep();
@@ -612,18 +612,18 @@ public class ArenaImpl implements Arena
announce(Msg.ARENA_END); announce(Msg.ARENA_END);
} }
cleanup(); cleanup();
// Restore region. // Restore region.
if (settings.getBoolean("soft-restore", false)) { if (settings.getBoolean("soft-restore", false)) {
restoreRegion(); restoreRegion();
} }
// Restore chests // Restore chests
restoreContainerContents(); restoreContainerContents();
// Restore enabled status. // Restore enabled status.
enabled = en; enabled = en;
return true; return true;
} }
@@ -632,12 +632,12 @@ public class ArenaImpl implements Arena
{ {
if (running) if (running)
return; return;
// Set operations. // Set operations.
Set<Player> tmp = new HashSet<>(); Set<Player> tmp = new HashSet<>();
tmp.addAll(lobbyPlayers); tmp.addAll(lobbyPlayers);
tmp.removeAll(readyPlayers); tmp.removeAll(readyPlayers);
// Force leave. // Force leave.
for (Player p : tmp) { for (Player p : tmp) {
playerLeave(p); playerLeave(p);
@@ -655,7 +655,7 @@ public class ArenaImpl implements Arena
if (players.isEmpty()) { if (players.isEmpty()) {
return; return;
} }
players.forEach(this::playerLeave); players.forEach(this::playerLeave);
cleanup(); cleanup();
} }
@@ -713,17 +713,17 @@ public class ArenaImpl implements Arena
lobbyPlayers.add(p); lobbyPlayers.add(p);
plugin.getArenaMaster().addPlayer(p, this); plugin.getArenaMaster().addPlayer(p, this);
arenaPlayerMap.put(p, new ArenaPlayer(p, this, plugin)); arenaPlayerMap.put(p, new ArenaPlayer(p, this, plugin));
// Start the start-delay-timer if applicable // Start the start-delay-timer if applicable
if (!autoStartTimer.isRunning()) { if (!autoStartTimer.isRunning()) {
startDelayTimer.start(); startDelayTimer.start();
} }
// Notify player of joining // Notify player of joining
messenger.tell(p, Msg.JOIN_PLAYER_JOINED); messenger.tell(p, Msg.JOIN_PLAYER_JOINED);
// Notify player of time left // Notify player of time left
if (startDelayTimer.isRunning()) { if (startDelayTimer.isRunning()) {
messenger.tell(p, Msg.ARENA_START_DELAY, "" + startDelayTimer.getRemaining() / 20l); messenger.tell(p, Msg.ARENA_START_DELAY, "" + startDelayTimer.getRemaining() / 20l);
@@ -738,7 +738,7 @@ public class ArenaImpl implements Arena
messenger.tell(p, Msg.LOBBY_CLASS_PICKED, defaultClass.getConfigName()); messenger.tell(p, Msg.LOBBY_CLASS_PICKED, defaultClass.getConfigName());
} }
} }
movingPlayers.remove(p); movingPlayers.remove(p);
return true; return true;
} }
@@ -753,14 +753,14 @@ public class ArenaImpl implements Arena
} }
readyPlayers.add(p); readyPlayers.add(p);
int minPlayers = getMinPlayers(); int minPlayers = getMinPlayers();
if (minPlayers > 0 && lobbyPlayers.size() < minPlayers) if (minPlayers > 0 && lobbyPlayers.size() < minPlayers)
{ {
messenger.tell(p, Msg.LOBBY_NOT_ENOUGH_PLAYERS, "" + minPlayers); messenger.tell(p, Msg.LOBBY_NOT_ENOUGH_PLAYERS, "" + minPlayers);
return; return;
} }
startArena(); startArena();
} }
@@ -785,10 +785,10 @@ public class ArenaImpl implements Arena
unmount(p); unmount(p);
clearInv(p); clearInv(p);
} }
removePermissionAttachments(p); removePermissionAttachments(p);
removePotionEffects(p); removePotionEffects(p);
boolean refund = inLobby(p); boolean refund = inLobby(p);
if (inLobby(p)) { if (inLobby(p)) {
@@ -802,13 +802,13 @@ public class ArenaImpl implements Arena
startDelayTimer.stop(); startDelayTimer.stop();
} }
} }
discardPlayer(p); discardPlayer(p);
if (refund) { if (refund) {
refund(p); refund(p);
} }
endArena(); endArena();
leavingPlayers.remove(p); leavingPlayers.remove(p);
@@ -841,7 +841,7 @@ public class ArenaImpl implements Arena
unmount(p); unmount(p);
clearInv(p); clearInv(p);
} }
deadPlayers.add(p); deadPlayers.add(p);
endArena(); endArena();
} }
@@ -874,7 +874,7 @@ public class ArenaImpl implements Arena
public void revivePlayer(Player p) { public void revivePlayer(Player p) {
removePermissionAttachments(p); removePermissionAttachments(p);
removePotionEffects(p); removePotionEffects(p);
specPlayers.add(p); specPlayers.add(p);
if (settings.getBoolean("spectate-on-death", true)) { if (settings.getBoolean("spectate-on-death", true)) {
@@ -897,7 +897,7 @@ public class ArenaImpl implements Arena
} }
movingPlayers.add(p); movingPlayers.add(p);
rollback(p); rollback(p);
Step step = playerSpecArena.create(p); Step step = playerSpecArena.create(p);
@@ -911,7 +911,7 @@ public class ArenaImpl implements Arena
specPlayers.add(p); specPlayers.add(p);
plugin.getArenaMaster().addPlayer(p, this); plugin.getArenaMaster().addPlayer(p, this);
messenger.tell(p, Msg.SPEC_PLAYER_SPECTATE); messenger.tell(p, Msg.SPEC_PLAYER_SPECTATE);
movingPlayers.remove(p); movingPlayers.remove(p);
} }
@@ -1000,7 +1000,7 @@ public class ArenaImpl implements Arena
default: return null; default: return null;
} }
} }
private void startSpawner() { private void startSpawner() {
if (spawnThread != null) { if (spawnThread != null) {
spawnThread.stop(); spawnThread.stop();
@@ -1012,7 +1012,7 @@ public class ArenaImpl implements Arena
spawnThread = new MASpawnThread(plugin, this); spawnThread = new MASpawnThread(plugin, this);
spawnThread.start(); spawnThread.start();
} }
/** /**
* Schedule a Runnable to be executed after the given delay in * Schedule a Runnable to be executed after the given delay in
* server ticks. The method is used by the MASpawnThread to * server ticks. The method is used by the MASpawnThread to
@@ -1023,7 +1023,7 @@ public class ArenaImpl implements Arena
public void scheduleTask(Runnable r, int delay) { public void scheduleTask(Runnable r, int delay) {
Bukkit.getScheduler().runTaskLater(plugin, r, delay); Bukkit.getScheduler().runTaskLater(plugin, r, delay);
} }
private void stopSpawner() { private void stopSpawner() {
if (spawnThread == null) { if (spawnThread == null) {
plugin.getLogger().warning("Can't stop non-existent spawner in arena " + configName() + ". This should never happen."); plugin.getLogger().warning("Can't stop non-existent spawner in arena " + configName() + ". This should never happen.");
@@ -1035,7 +1035,7 @@ public class ArenaImpl implements Arena
world.setSpawnFlags(allowMonsters, allowAnimals); world.setSpawnFlags(allowMonsters, allowAnimals);
} }
private void startBouncingSheep() { private void startBouncingSheep() {
if (sheepBouncer != null) { if (sheepBouncer != null) {
sheepBouncer.stop(); sheepBouncer.stop();
@@ -1082,7 +1082,7 @@ public class ArenaImpl implements Arena
plugin.getArenaMaster().removePlayer(p); plugin.getArenaMaster().removePlayer(p);
clearPlayer(p); clearPlayer(p);
} }
private void clearPlayer(Player p) private void clearPlayer(Player p)
{ {
// Remove from boss health bar // Remove from boss health bar
@@ -1092,20 +1092,20 @@ public class ArenaImpl implements Arena
boss.getHealthBar().removePlayer(p); boss.getHealthBar().removePlayer(p);
} }
}); });
// Remove pets. // Remove pets.
monsterManager.removePets(p); monsterManager.removePets(p);
// readyPlayers before lobbyPlayers because of startArena sanity-checks // readyPlayers before lobbyPlayers because of startArena sanity-checks
readyPlayers.remove(p); readyPlayers.remove(p);
specPlayers.remove(p); specPlayers.remove(p);
arenaPlayers.remove(p); arenaPlayers.remove(p);
lobbyPlayers.remove(p); lobbyPlayers.remove(p);
arenaPlayerMap.remove(p); arenaPlayerMap.remove(p);
scoreboard.removePlayer(p); scoreboard.removePlayer(p);
} }
@Override @Override
public void repairBlocks() public void repairBlocks()
{ {
@@ -1118,9 +1118,9 @@ public class ArenaImpl implements Arena
{ {
repairQueue.add(r); repairQueue.add(r);
} }
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Items & Cleanup // Items & Cleanup
@@ -1131,11 +1131,11 @@ public class ArenaImpl implements Arena
public void assignClass(Player p, String className) { public void assignClass(Player p, String className) {
ArenaPlayer arenaPlayer = arenaPlayerMap.get(p); ArenaPlayer arenaPlayer = arenaPlayerMap.get(p);
ArenaClass arenaClass = classes.get(className); ArenaClass arenaClass = classes.get(className);
if (arenaPlayer == null || arenaClass == null) { if (arenaPlayer == null || arenaClass == null) {
return; return;
} }
InventoryManager.clearInventory(p); InventoryManager.clearInventory(p);
removePotionEffects(p); removePotionEffects(p);
arenaPlayer.setArenaClass(arenaClass); arenaPlayer.setArenaClass(arenaClass);
@@ -1158,21 +1158,21 @@ public class ArenaImpl implements Arena
autoReady(p); autoReady(p);
} }
@Override @Override
public void assignClassGiveInv(Player p, String className, ItemStack[] source) { public void assignClassGiveInv(Player p, String className, ItemStack[] source) {
ArenaPlayer arenaPlayer = arenaPlayerMap.get(p); ArenaPlayer arenaPlayer = arenaPlayerMap.get(p);
ArenaClass arenaClass = classes.get(className); ArenaClass arenaClass = classes.get(className);
if (arenaPlayer == null || arenaClass == null) { if (arenaPlayer == null || arenaClass == null) {
return; return;
} }
InventoryManager.clearInventory(p); InventoryManager.clearInventory(p);
removePermissionAttachments(p); removePermissionAttachments(p);
removePotionEffects(p); removePotionEffects(p);
arenaPlayer.setArenaClass(arenaClass); arenaPlayer.setArenaClass(arenaClass);
PlayerInventory inv = p.getInventory(); PlayerInventory inv = p.getInventory();
// Clone the source array to make sure we don't modify its contents // Clone the source array to make sure we don't modify its contents
@@ -1189,7 +1189,7 @@ public class ArenaImpl implements Arena
ItemStack leggings = null; ItemStack leggings = null;
ItemStack boots = null; ItemStack boots = null;
ItemStack offhand = null; ItemStack offhand = null;
// Check the very last slot to see if it'll work as a helmet // Check the very last slot to see if it'll work as a helmet
int last = contents.length-1; int last = contents.length-1;
if (contents[last] != null) { if (contents[last] != null) {
@@ -1221,7 +1221,7 @@ public class ArenaImpl implements Arena
} }
contents[i] = null; contents[i] = null;
} }
// Equip the fifth last slot as the off-hand // Equip the fifth last slot as the off-hand
offhand = contents[contents.length - 5]; offhand = contents[contents.length - 5];
if (offhand != null) { if (offhand != null) {
@@ -1276,7 +1276,7 @@ public class ArenaImpl implements Arena
} }
} }
} }
@Override @Override
public void addRandomPlayer(Player p) { public void addRandomPlayer(Player p) {
randoms.add(p); randoms.add(p);
@@ -1294,7 +1294,7 @@ public class ArenaImpl implements Arena
playerLeave(p); playerLeave(p);
return; return;
} }
int index = MobArena.random.nextInt(classes.size()); int index = MobArena.random.nextInt(classes.size());
String className = classes.get(index).getConfigName(); String className = classes.get(index).getConfigName();
@@ -1322,7 +1322,7 @@ public class ArenaImpl implements Arena
.map(PermissionAttachmentInfo::getAttachment) .map(PermissionAttachmentInfo::getAttachment)
.forEach(PermissionAttachment::remove); .forEach(PermissionAttachment::remove);
} }
private void removePotionEffects(Player p) { private void removePotionEffects(Player p) {
p.getActivePotionEffects().stream() p.getActivePotionEffects().stream()
.map(PotionEffect::getType) .map(PotionEffect::getType)
@@ -1335,21 +1335,21 @@ public class ArenaImpl implements Arena
removeEntities(); removeEntities();
clearPlayers(); clearPlayers();
} }
private void removeMonsters() { private void removeMonsters() {
monsterManager.clear(); monsterManager.clear();
} }
private void removeBlocks() { private void removeBlocks() {
for (Block b : blocks) { for (Block b : blocks) {
b.setType(Material.AIR); b.setType(Material.AIR);
} }
blocks.clear(); blocks.clear();
} }
private void removeEntities() { private void removeEntities() {
List<Chunk> chunks = region.getChunks(); List<Chunk> chunks = region.getChunks();
for (Chunk c : chunks) { for (Chunk c : chunks) {
for (Entity e : c.getEntities()) { for (Entity e : c.getEntities()) {
if (e == null) { if (e == null) {
@@ -1368,16 +1368,16 @@ public class ArenaImpl implements Arena
} }
} }
} }
private void clearPlayers() { private void clearPlayers() {
arenaPlayers.clear(); arenaPlayers.clear();
arenaPlayerMap.clear(); arenaPlayerMap.clear();
lobbyPlayers.clear(); lobbyPlayers.clear();
readyPlayers.clear(); readyPlayers.clear();
} }
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Initialization & Checks // Initialization & Checks
@@ -1388,13 +1388,13 @@ public class ArenaImpl implements Arena
public void restoreRegion() public void restoreRegion()
{ {
Collections.sort(repairables, new RepairableComparator()); Collections.sort(repairables, new RepairableComparator());
for (Repairable r : repairables) for (Repairable r : repairables)
r.repair(); r.repair();
} }
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Getters & Misc // Getters & Misc
@@ -1458,7 +1458,7 @@ public class ArenaImpl implements Arena
result.addAll(arenaPlayers); result.addAll(arenaPlayers);
result.addAll(lobbyPlayers); result.addAll(lobbyPlayers);
result.addAll(specPlayers); result.addAll(specPlayers);
return result; return result;
} }
@@ -1477,10 +1477,10 @@ public class ArenaImpl implements Arena
public List<ArenaPlayerStatistics> getArenaPlayerStatistics(Comparator<ArenaPlayerStatistics> comparator) public List<ArenaPlayerStatistics> getArenaPlayerStatistics(Comparator<ArenaPlayerStatistics> comparator)
{ {
List<ArenaPlayerStatistics> list = new ArrayList<ArenaPlayerStatistics>(); List<ArenaPlayerStatistics> list = new ArrayList<ArenaPlayerStatistics>();
for (ArenaPlayer ap : arenaPlayerMap.values()) for (ArenaPlayer ap : arenaPlayerMap.values())
list.add(ap.getStats()); list.add(ap.getStats());
Collections.sort(list, comparator); Collections.sort(list, comparator);
return list; return list;
}*/ }*/
@@ -1519,7 +1519,7 @@ public class ArenaImpl implements Arena
} }
return true; return true;
} }
@Override @Override
public boolean refund(Player p) { public boolean refund(Player p) {
entryFee.forEach(fee -> fee.giveTo(p)); entryFee.forEach(fee -> fee.giveTo(p));
@@ -1549,7 +1549,7 @@ public class ArenaImpl implements Arena
else if (!canAfford(p)) else if (!canAfford(p))
messenger.tell(p, Msg.JOIN_FEE_REQUIRED, MAUtils.listToString(entryFee, plugin)); messenger.tell(p, Msg.JOIN_FEE_REQUIRED, MAUtils.listToString(entryFee, plugin));
else return true; else return true;
return false; return false;
} }
@@ -1568,7 +1568,7 @@ public class ArenaImpl implements Arena
else if (getJoinDistance() > 0 && !region.contains(p.getLocation(), getJoinDistance())) else if (getJoinDistance() > 0 && !region.contains(p.getLocation(), getJoinDistance()))
messenger.tell(p, Msg.JOIN_TOO_FAR); messenger.tell(p, Msg.JOIN_TOO_FAR);
else return true; else return true;
return false; return false;
} }
@@ -1581,7 +1581,7 @@ public class ArenaImpl implements Arena
public Player getLastPlayerStanding() { public Player getLastPlayerStanding() {
return lastStanding; return lastStanding;
} }
/** /**
* The "perfect equals method" cf. "Object-Oriented Design and Patterns" * The "perfect equals method" cf. "Object-Oriented Design and Patterns"
* by Cay S. Horstmann. * by Cay S. Horstmann.
@@ -1591,11 +1591,11 @@ public class ArenaImpl implements Arena
if (this == other) return true; if (this == other) return true;
if (other == null) return false; if (other == null) return false;
if (getClass() != other.getClass()) return false; if (getClass() != other.getClass()) return false;
// Arenas must have different names. // Arenas must have different names.
if (other instanceof ArenaImpl && ((ArenaImpl)other).name.equals(name)) if (other instanceof ArenaImpl && ((ArenaImpl)other).name.equals(name))
return true; return true;
return false; return false;
} }
@@ -147,7 +147,7 @@ public class ArenaListener
this.canShare = s.getBoolean("share-items-in-arena", true); this.canShare = s.getBoolean("share-items-in-arena", true);
this.autoIgniteTNT = s.getBoolean("auto-ignite-tnt", false); this.autoIgniteTNT = s.getBoolean("auto-ignite-tnt", false);
this.useClassChests = s.getBoolean("use-class-chests", false); this.useClassChests = s.getBoolean("use-class-chests", false);
this.classLimits = arena.getClassLimitManager(); this.classLimits = arena.getClassLimitManager();
this.banned = new HashSet<>(); this.banned = new HashSet<>();
@@ -157,13 +157,13 @@ public class ArenaListener
EntityType.GUARDIAN EntityType.GUARDIAN
); );
} }
void pvpActivate() { void pvpActivate() {
if (arena.isRunning() && !arena.getPlayersInArena().isEmpty()) { if (arena.isRunning() && !arena.getPlayersInArena().isEmpty()) {
pvpEnabled = pvpOn; pvpEnabled = pvpOn;
} }
} }
void pvpDeactivate() { void pvpDeactivate() {
if (pvpOn) pvpEnabled = false; if (pvpOn) pvpEnabled = false;
} }
@@ -179,17 +179,17 @@ public class ArenaListener
// If the arena isn't protected, care // If the arena isn't protected, care
if (!protect) return; if (!protect) return;
if (!arena.getRegion().contains(event.getBlock().getLocation())) if (!arena.getRegion().contains(event.getBlock().getLocation()))
return; return;
if (!arena.inArena(event.getPlayer())) { if (!arena.inArena(event.getPlayer())) {
if (arena.inEditMode()) if (arena.inEditMode())
return; return;
else else
event.setCancelled(true); event.setCancelled(true);
} }
if (onBlockDestroy(event)) if (onBlockDestroy(event))
return; return;
@@ -223,18 +223,18 @@ public class ArenaListener
private boolean onBlockDestroy(BlockEvent event) { private boolean onBlockDestroy(BlockEvent event) {
if (arena.inEditMode()) if (arena.inEditMode())
return true; return true;
if (!arena.isRunning()) if (!arena.isRunning())
return false; return false;
Block b = event.getBlock(); Block b = event.getBlock();
if (arena.removeBlock(b) || b.getType() == Material.TNT) if (arena.removeBlock(b) || b.getType() == Material.TNT)
return true; return true;
if (softRestore) { if (softRestore) {
BlockState state = b.getState(); BlockState state = b.getState();
Repairable r = null; Repairable r = null;
if (state instanceof InventoryHolder) if (state instanceof InventoryHolder)
r = new RepairableContainer(state); r = new RepairableContainer(state);
else if (state instanceof Sign) else if (state instanceof Sign)
@@ -245,7 +245,7 @@ public class ArenaListener
r = new RepairableBlock(state); r = new RepairableBlock(state);
arena.addRepairable(r); arena.addRepairable(r);
if (!softRestoreDrops) if (!softRestoreDrops)
b.setType(Material.AIR); b.setType(Material.AIR);
return true; return true;
@@ -302,11 +302,11 @@ public class ArenaListener
arena.addBlock(b.getRelative(0, 1, 0)); arena.addBlock(b.getRelative(0, 1, 0));
} }
} }
private void setPlanter(Metadatable tnt, Player planter) { private void setPlanter(Metadatable tnt, Player planter) {
tnt.setMetadata("mobarena-planter", new FixedMetadataValue(plugin, planter)); tnt.setMetadata("mobarena-planter", new FixedMetadataValue(plugin, planter));
} }
private Player getPlanter(Metadatable tnt) { private Player getPlanter(Metadatable tnt) {
List<MetadataValue> values = tnt.getMetadata("mobarena-planter"); List<MetadataValue> values = tnt.getMetadata("mobarena-planter");
for (MetadataValue value : values) { for (MetadataValue value : values) {
@@ -511,9 +511,9 @@ public class ArenaListener
} }
/****************************************************** /******************************************************
* *
* DEATH LISTENERS * DEATH LISTENERS
* *
******************************************************/ ******************************************************/
public void onEntityDeath(EntityDeathEvent event) { public void onEntityDeath(EntityDeathEvent event) {
@@ -571,11 +571,11 @@ public class ArenaListener
arena.playerRespawn(p); arena.playerRespawn(p);
return true; return true;
} }
private void onMountDeath(EntityDeathEvent event) { private void onMountDeath(EntityDeathEvent event) {
// Shouldn't ever happen // Shouldn't ever happen
} }
private void onMonsterDeath(EntityDeathEvent event) { private void onMonsterDeath(EntityDeathEvent event) {
EntityDamageEvent e1 = event.getEntity().getLastDamageCause(); EntityDamageEvent e1 = event.getEntity().getLastDamageCause();
EntityDamageByEntityEvent e2 = (e1 instanceof EntityDamageByEntityEvent) ? (EntityDamageByEntityEvent) e1 : null; EntityDamageByEntityEvent e2 = (e1 instanceof EntityDamageByEntityEvent) ? (EntityDamageByEntityEvent) e1 : null;
@@ -652,9 +652,9 @@ public class ArenaListener
} }
/****************************************************** /******************************************************
* *
* DAMAGE LISTENERS * DAMAGE LISTENERS
* *
******************************************************/ ******************************************************/
public void onEntityDamage(EntityDamageEvent event) { public void onEntityDamage(EntityDamageEvent event) {
@@ -771,7 +771,7 @@ public class ArenaListener
double progress = boss.getHealth() / boss.getMaxHealth(); double progress = boss.getHealth() / boss.getMaxHealth();
boss.getHealthBar().setProgress(progress); boss.getHealthBar().setProgress(progress);
} }
private void onMonsterDamage(EntityDamageEvent event, Entity monster, Entity damager) { private void onMonsterDamage(EntityDamageEvent event, Entity monster, Entity damager) {
if (damager instanceof Player) { if (damager instanceof Player) {
Player p = (Player) damager; Player p = (Player) damager;
@@ -796,7 +796,7 @@ public class ArenaListener
event.setCancelled(true); event.setCancelled(true);
} }
} }
private void onGolemDamage(EntityDamageEvent event, Entity golem, Entity damager) { private void onGolemDamage(EntityDamageEvent event, Entity golem, Entity damager) {
if (damager instanceof Player) { if (damager instanceof Player) {
Player p = (Player) damager; Player p = (Player) damager;
@@ -804,7 +804,7 @@ public class ArenaListener
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (!pvpEnabled) { if (!pvpEnabled) {
event.setCancelled(true); event.setCancelled(true);
} }
@@ -898,7 +898,7 @@ public class ArenaListener
private boolean isArenaPet(Entity entity) { private boolean isArenaPet(Entity entity) {
return arena.hasPet(entity); return arena.hasPet(entity);
} }
public void onEntityTeleport(EntityTeleportEvent event) { public void onEntityTeleport(EntityTeleportEvent event) {
if (monsters.hasPet(event.getEntity()) && region.contains(event.getTo())) { if (monsters.hasPet(event.getEntity()) && region.contains(event.getTo())) {
return; return;
@@ -907,7 +907,7 @@ public class ArenaListener
event.setCancelled(true); event.setCancelled(true);
} }
} }
public void onPotionSplash(PotionSplashEvent event) { public void onPotionSplash(PotionSplashEvent event) {
ThrownPotion potion = event.getPotion(); ThrownPotion potion = event.getPotion();
if (!region.contains(potion.getLocation())) { if (!region.contains(potion.getLocation())) {
@@ -1014,18 +1014,18 @@ public class ArenaListener
event.setCancelled(true); event.setCancelled(true);
} }
} }
// If the player is in the lobby, just cancel // If the player is in the lobby, just cancel
else if (arena.inLobby(p)) { else if (arena.inLobby(p)) {
arena.getMessenger().tell(p, Msg.LOBBY_DROP_ITEM); arena.getMessenger().tell(p, Msg.LOBBY_DROP_ITEM);
event.setCancelled(true); event.setCancelled(true);
} }
// Same if it's a spectator, but... // Same if it's a spectator, but...
else if (arena.inSpec(p)) { else if (arena.inSpec(p)) {
arena.getMessenger().tell(p, Msg.LOBBY_DROP_ITEM); arena.getMessenger().tell(p, Msg.LOBBY_DROP_ITEM);
event.setCancelled(true); event.setCancelled(true);
// If the spectator isn't in the region, force them to leave // If the spectator isn't in the region, force them to leave
if (!region.contains(p.getLocation())) { if (!region.contains(p.getLocation())) {
arena.getMessenger().tell(p, Msg.MISC_MA_LEAVE_REMINDER); arena.getMessenger().tell(p, Msg.MISC_MA_LEAVE_REMINDER);
@@ -1122,14 +1122,14 @@ public class ArenaListener
arena.getMessenger().tell(p, Msg.LOBBY_CLASS_PERMISSION); arena.getMessenger().tell(p, Msg.LOBBY_CLASS_PERMISSION);
return; return;
} }
ArenaClass oldAC = arena.getArenaPlayer(p).getArenaClass(); ArenaClass oldAC = arena.getArenaPlayer(p).getArenaClass();
// Same class, do nothing. // Same class, do nothing.
if (newAC.equals(oldAC)) { if (newAC.equals(oldAC)) {
return; return;
} }
// If the new class is full, inform the player. // If the new class is full, inform the player.
if (!classLimits.canPlayerJoinClass(newAC)) { if (!classLimits.canPlayerJoinClass(newAC)) {
arena.getMessenger().tell(p, Msg.LOBBY_CLASS_FULL); arena.getMessenger().tell(p, Msg.LOBBY_CLASS_FULL);
@@ -1144,7 +1144,7 @@ public class ArenaListener
return; return;
} }
} }
// Otherwise, leave the old class, and pick the new! // Otherwise, leave the old class, and pick the new!
classLimits.playerLeftClass(oldAC, p); classLimits.playerLeftClass(oldAC, p);
classLimits.playerPickedClass(newAC, p); classLimits.playerPickedClass(newAC, p);
@@ -1152,14 +1152,14 @@ public class ArenaListener
// Delay the inventory stuff to ensure that right-clicking works. // Delay the inventory stuff to ensure that right-clicking works.
delayAssignClass(p, className, price, sign); delayAssignClass(p, className, price, sign);
} }
/*private boolean cansPlayerJoinClass(ArenaClass ac, Player p) { /*private boolean cansPlayerJoinClass(ArenaClass ac, Player p) {
// If they can not join the class, deny them // If they can not join the class, deny them
if (!classLimits.canPlayerJoinClass(ac)) { if (!classLimits.canPlayerJoinClass(ac)) {
Messenger.tell(p, Msg.LOBBY_CLASS_FULL); Messenger.tell(p, Msg.LOBBY_CLASS_FULL);
return false; return false;
} }
// Increment the "in use" in the Class Limit Manager // Increment the "in use" in the Class Limit Manager
classLimits.playerPickedClass(ac); classLimits.playerPickedClass(ac);
return true; return true;
@@ -1222,7 +1222,7 @@ public class ArenaListener
} }
}, ticks); }, ticks);
} }
public TeleportResponse onPlayerTeleport(PlayerTeleportEvent event) { public TeleportResponse onPlayerTeleport(PlayerTeleportEvent event) {
if (!arena.isEnabled() || !region.isSetup() || arena.inEditMode() || allowTeleport) { if (!arena.isEnabled() || !region.isSetup() || arena.inEditMode() || allowTeleport) {
return TeleportResponse.IDGAF; return TeleportResponse.IDGAF;
@@ -1310,10 +1310,10 @@ public class ArenaListener
public void onPlayerPreLogin(PlayerLoginEvent event) { public void onPlayerPreLogin(PlayerLoginEvent event) {
Player p = event.getPlayer(); Player p = event.getPlayer();
if (p == null || !p.isOnline()) return; if (p == null || !p.isOnline()) return;
Arena arena = plugin.getArenaMaster().getArenaWithPlayer(p); Arena arena = plugin.getArenaMaster().getArenaWithPlayer(p);
if (arena == null) return; if (arena == null) return;
arena.playerLeave(p); arena.playerLeave(p);
} }
@@ -137,7 +137,7 @@ public class ArenaMasterImpl implements ArenaMaster
public List<Arena> getEnabledArenas(List<Arena> arenas) { public List<Arena> getEnabledArenas(List<Arena> arenas) {
List<Arena> result = new ArrayList<>(arenas.size()); List<Arena> result = new ArrayList<>(arenas.size());
for (Arena arena : arenas) for (Arena arena : arenas)
if (arena.isEnabled()) if (arena.isEnabled())
result.add(arena); result.add(arena);
return result; return result;
} }
@@ -16,7 +16,7 @@ public class ClassLimitManager
private HashMap<ArenaClass, HashSet<String>> classesInUse; private HashMap<ArenaClass, HashSet<String>> classesInUse;
private ConfigurationSection limits; private ConfigurationSection limits;
private Map<String,ArenaClass> classes; private Map<String,ArenaClass> classes;
public ClassLimitManager(Arena arena, Map<String,ArenaClass> classes, ConfigurationSection limits) { public ClassLimitManager(Arena arena, Map<String,ArenaClass> classes, ConfigurationSection limits) {
this.limits = limits; this.limits = limits;
this.classes = classes; this.classes = classes;
@@ -26,7 +26,7 @@ public class ClassLimitManager
loadLimitMap(arena.getPlugin()); loadLimitMap(arena.getPlugin());
initInUseMap(); initInUseMap();
} }
private void loadLimitMap(Plugin plugin) { private void loadLimitMap(Plugin plugin) {
// If the config-section is empty, create and populate it. // If the config-section is empty, create and populate it.
if (limits.getKeys(false).isEmpty()) { if (limits.getKeys(false).isEmpty()) {
@@ -35,20 +35,20 @@ public class ClassLimitManager
} }
plugin.saveConfig(); plugin.saveConfig();
} }
// Populate the limits map using the values in the config-file. // Populate the limits map using the values in the config-file.
for (ArenaClass ac : classes.values()) { for (ArenaClass ac : classes.values()) {
classLimits.put(ac, new MutableInt(limits.getInt(ac.getConfigName(), -1))); classLimits.put(ac, new MutableInt(limits.getInt(ac.getConfigName(), -1)));
} }
} }
private void initInUseMap() { private void initInUseMap() {
// Initialize the in-use map with zeros. // Initialize the in-use map with zeros.
for (ArenaClass ac : classes.values()) { for (ArenaClass ac : classes.values()) {
classesInUse.put(ac, new HashSet<>()); classesInUse.put(ac, new HashSet<>());
} }
} }
/** /**
* This is the class a player is changing to * This is the class a player is changing to
* @param ac the new ArenaClass * @param ac the new ArenaClass
@@ -56,7 +56,7 @@ public class ClassLimitManager
public void playerPickedClass(ArenaClass ac, Player p) { public void playerPickedClass(ArenaClass ac, Player p) {
classesInUse.get(ac).add(p.getName()); classesInUse.get(ac).add(p.getName());
} }
/** /**
* This is the class a player left * This is the class a player left
* @param ac the current/old ArenaClass * @param ac the current/old ArenaClass
@@ -66,7 +66,7 @@ public class ClassLimitManager
classesInUse.get(ac).remove(p.getName()); classesInUse.get(ac).remove(p.getName());
} }
} }
/** /**
* Checks to see if a player can pick a specific class * Checks to see if a player can pick a specific class
* @param ac the ArenaClass to check * @param ac the ArenaClass to check
@@ -78,13 +78,13 @@ public class ClassLimitManager
classLimits.put(ac, new MutableInt(-1)); classLimits.put(ac, new MutableInt(-1));
classesInUse.put(ac, new HashSet<>()); classesInUse.put(ac, new HashSet<>());
} }
if (classLimits.get(ac).value() <= -1) if (classLimits.get(ac).value() <= -1)
return true; return true;
return classesInUse.get(ac).size() < classLimits.get(ac).value(); return classesInUse.get(ac).size() < classLimits.get(ac).value();
} }
/** /**
* returns a set of Player Names who have picked an ArenaClass * returns a set of Player Names who have picked an ArenaClass
* @param ac the ArenaClass in question * @param ac the ArenaClass in question
@@ -93,7 +93,7 @@ public class ClassLimitManager
public HashSet<String> getPlayersWithClass(ArenaClass ac) { public HashSet<String> getPlayersWithClass(ArenaClass ac) {
return classesInUse.get(ac); return classesInUse.get(ac);
} }
/** /**
* Clear the classes in use map and reinitialize it for the next match * Clear the classes in use map and reinitialize it for the next match
*/ */
@@ -101,4 +101,4 @@ public class ClassLimitManager
classesInUse.clear(); classesInUse.clear();
initInUseMap(); initInUseMap();
} }
} }
@@ -184,9 +184,9 @@ public class MASpawnThread implements Runnable
Wave w = waveManager.next(); Wave w = waveManager.next();
w.announce(arena, wave); w.announce(arena, wave);
arena.getScoreboard().updateWave(wave); arena.getScoreboard().updateWave(wave);
// Set the players' level to the wave number // Set the players' level to the wave number
if (wavesAsLevel) { if (wavesAsLevel) {
for (Player p : arena.getPlayersInArena()) { for (Player p : arena.getPlayersInArena()) {
@@ -311,7 +311,7 @@ public class MASpawnThread implements Runnable
if (waveClear && !monsterManager.getMonsters().isEmpty()) { if (waveClear && !monsterManager.getMonsters().isEmpty()) {
return false; return false;
} }
// Check for pre boss clear // Check for pre boss clear
if (preBossClear && waveManager.getNext().getType() == WaveType.BOSS && !monsterManager.getMonsters().isEmpty()) { if (preBossClear && waveManager.getNext().getType() == WaveType.BOSS && !monsterManager.getMonsters().isEmpty()) {
return false; return false;
@@ -345,7 +345,7 @@ public class MASpawnThread implements Runnable
if (region.contains(p.getLocation())) { if (region.contains(p.getLocation())) {
continue; continue;
} }
arena.getMessenger().tell(p, "Leaving so soon?"); arena.getMessenger().tell(p, "Leaving so soon?");
p.getInventory().clear(); p.getInventory().clear();
arena.playerLeave(p); arena.playerLeave(p);
@@ -402,4 +402,4 @@ public class MASpawnThread implements Runnable
} }
} }
} }
} }
@@ -28,18 +28,18 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
public class MAUtils public class MAUtils
{ {
/* ///////////////////////////////////////////////////////////////////// // /* ///////////////////////////////////////////////////////////////////// //
INITIALIZATION METHODS INITIALIZATION METHODS
// ///////////////////////////////////////////////////////////////////// */ // ///////////////////////////////////////////////////////////////////// */
/** /**
* Generates a map of wave numbers and rewards based on the * Generates a map of wave numbers and rewards based on the
* type of wave ("after" or "every") and the config-file. If * type of wave ("after" or "every") and the config-file. If
* no keys exist in the config-file, an empty map is returned. * no keys exist in the config-file, an empty map is returned.
*/ */
public static Map<Integer,List<Thing>> getArenaRewardMap(MobArena plugin, ConfigurationSection config, String arena, String type) public static Map<Integer,List<Thing>> getArenaRewardMap(MobArena plugin, ConfigurationSection config, String arena, String type)
{ {
//String arenaPath = "arenas." + arena + ".rewards.waves."; //String arenaPath = "arenas." + arena + ".rewards.waves.";
@@ -47,16 +47,16 @@ public class MAUtils
String typePath = "rewards.waves." + type; String typePath = "rewards.waves." + type;
if (!config.contains(typePath)) return result; if (!config.contains(typePath)) return result;
//Set<String> waves = config.getKeys(arenaPath + type); //Set<String> waves = config.getKeys(arenaPath + type);
Set<String> waves = config.getConfigurationSection(typePath).getKeys(false); Set<String> waves = config.getConfigurationSection(typePath).getKeys(false);
if (waves == null) return result; if (waves == null) return result;
for (String n : waves) for (String n : waves)
{ {
if (!n.matches("[0-9]+")) if (!n.matches("[0-9]+"))
continue; continue;
int wave = Integer.parseInt(n); int wave = Integer.parseInt(n);
String path = typePath + "." + wave; String path = typePath + "." + wave;
String rewards = config.getString(path); String rewards = config.getString(path);
@@ -75,20 +75,20 @@ public class MAUtils
return result; return result;
} }
/* ///////////////////////////////////////////////////////////////////// // /* ///////////////////////////////////////////////////////////////////// //
MISC METHODS MISC METHODS
// ///////////////////////////////////////////////////////////////////// */ // ///////////////////////////////////////////////////////////////////// */
public static Player getClosestPlayer(MobArena plugin, Entity e, Arena arena) { public static Player getClosestPlayer(MobArena plugin, Entity e, Arena arena) {
// Set up the comparison variable and the result. // Set up the comparison variable and the result.
double current = Double.POSITIVE_INFINITY; double current = Double.POSITIVE_INFINITY;
Player result = null; Player result = null;
/* Iterate through the ArrayList, and update current and result every /* Iterate through the ArrayList, and update current and result every
* time a squared distance smaller than current is found. */ * time a squared distance smaller than current is found. */
List<Player> players = new ArrayList<>(arena.getPlayersInArena()); List<Player> players = new ArrayList<>(arena.getPlayersInArena());
@@ -99,7 +99,7 @@ public class MAUtils
arena.getMessenger().tell(p, "You warped out of the arena world."); arena.getMessenger().tell(p, "You warped out of the arena world.");
continue; continue;
} }
double dist = distanceSquared(plugin, p, e.getLocation()); double dist = distanceSquared(plugin, p, e.getLocation());
if (dist < current && dist < 256D) { if (dist < current && dist < 256D) {
current = dist; current = dist;
@@ -108,7 +108,7 @@ public class MAUtils
} }
return result; return result;
} }
public static double distanceSquared(MobArena plugin, Player p, Location l) { public static double distanceSquared(MobArena plugin, Player p, Location l) {
try { try {
return p.getLocation().distanceSquared(l); return p.getLocation().distanceSquared(l);
@@ -121,7 +121,7 @@ public class MAUtils
return Double.MAX_VALUE; return Double.MAX_VALUE;
} }
} }
/** /**
* Convert a config-name to a proper spaced and capsed arena name. * Convert a config-name to a proper spaced and capsed arena name.
* The input String is split around all underscores, and every part * The input String is split around all underscores, and every part
@@ -133,7 +133,7 @@ public class MAUtils
if (parts.length == 1) { if (parts.length == 1) {
return toCamelCase(parts[0]); return toCamelCase(parts[0]);
} }
String separator = " "; String separator = " ";
StringBuffer buffy = new StringBuffer(name.length()); StringBuffer buffy = new StringBuffer(name.length());
for (String part : parts) { for (String part : parts) {
@@ -141,30 +141,30 @@ public class MAUtils
buffy.append(separator); buffy.append(separator);
} }
buffy.replace(buffy.length()-1, buffy.length(), ""); buffy.replace(buffy.length()-1, buffy.length(), "");
return buffy.toString(); return buffy.toString();
} }
/** /**
* Returns the input String with a capital first letter, and all the * Returns the input String with a capital first letter, and all the
* other letters become lower case. * other letters become lower case.
*/ */
public static String toCamelCase(String name) { public static String toCamelCase(String name) {
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
} }
/** /**
* Turn a list into a space-separated string-representation of the list. * Turn a list into a space-separated string-representation of the list.
*/ */
public static <E> String listToString(Collection<E> list, boolean none, MobArena plugin) public static <E> String listToString(Collection<E> list, boolean none, MobArena plugin)
{ {
if (list == null || list.isEmpty()) { if (list == null || list.isEmpty()) {
return (none ? Msg.MISC_NONE.toString() : ""); return (none ? Msg.MISC_NONE.toString() : "");
} }
StringBuffer buffy = new StringBuffer(); StringBuffer buffy = new StringBuffer();
int trimLength = 0; int trimLength = 0;
E type = list.iterator().next(); E type = list.iterator().next();
if (type instanceof Player) { if (type instanceof Player) {
for (E e : list) { for (E e : list) {
@@ -192,7 +192,7 @@ public class MAUtils
return buffy.toString().substring(0, buffy.length() - trimLength); return buffy.toString().substring(0, buffy.length() - trimLength);
} }
public static <E> String listToString(Collection<E> list, JavaPlugin plugin) { return listToString(list, true, (MobArena) plugin); } public static <E> String listToString(Collection<E> list, JavaPlugin plugin) { return listToString(list, true, (MobArena) plugin); }
/** /**
* Returns a String-list version of a comma-separated list. * Returns a String-list version of a comma-separated list.
*/ */
@@ -200,15 +200,15 @@ public class MAUtils
{ {
List<String> result = new LinkedList<>(); List<String> result = new LinkedList<>();
if (list == null) return result; if (list == null) return result;
String[] parts = list.trim().split(","); String[] parts = list.trim().split(",");
for (String part : parts) for (String part : parts)
result.add(part.trim()); result.add(part.trim());
return result; return result;
} }
/** /**
* Stand back, I'm going to try science! * Stand back, I'm going to try science!
*/ */
@@ -216,11 +216,11 @@ public class MAUtils
{ {
// Grab the Configuration and ArenaMaster // Grab the Configuration and ArenaMaster
ArenaMaster am = plugin.getArenaMaster(); ArenaMaster am = plugin.getArenaMaster();
// Create the arena node in the config-file. // Create the arena node in the config-file.
World world = loc.getWorld(); World world = loc.getWorld();
Arena arena = am.createArenaNode(name, world); Arena arena = am.createArenaNode(name, world);
// Get the hippie bounds. // Get the hippie bounds.
int x1 = (int)loc.getX() - radius; int x1 = (int)loc.getX() - radius;
int x2 = (int)loc.getX() + radius; int x2 = (int)loc.getX() + radius;
@@ -228,14 +228,14 @@ public class MAUtils
int y2 = (int)loc.getY() - 1; int y2 = (int)loc.getY() - 1;
int z1 = (int)loc.getZ() - radius; int z1 = (int)loc.getZ() - radius;
int z2 = (int)loc.getZ() + radius; int z2 = (int)loc.getZ() + radius;
int lx1 = x1; int lx1 = x1;
int lx2 = x1 + am.getClasses().size() + 3; int lx2 = x1 + am.getClasses().size() + 3;
int ly1 = y1-6; int ly1 = y1-6;
int ly2 = y1-2; int ly2 = y1-2;
int lz1 = z1; int lz1 = z1;
int lz2 = z1 + 6; int lz2 = z1 + 6;
// Build some monster walls. // Build some monster walls.
for (int i = x1; i <= x2; i++) for (int i = x1; i <= x2; i++)
{ {
@@ -253,7 +253,7 @@ public class MAUtils
world.getBlockAt(x2,j,k).setType(Material.SANDSTONE); world.getBlockAt(x2,j,k).setType(Material.SANDSTONE);
} }
} }
// Add some hippie light. // Add some hippie light.
for (int i = x1; i <= x2; i++) for (int i = x1; i <= x2; i++)
{ {
@@ -265,7 +265,7 @@ public class MAUtils
world.getBlockAt(x1,y1+2,k).setType(Material.GLOWSTONE); world.getBlockAt(x1,y1+2,k).setType(Material.GLOWSTONE);
world.getBlockAt(x2,y1+2,k).setType(Material.GLOWSTONE); world.getBlockAt(x2,y1+2,k).setType(Material.GLOWSTONE);
} }
// Build a monster floor, and some Obsidian foundation. // Build a monster floor, and some Obsidian foundation.
for (int i = x1; i <= x2; i++) for (int i = x1; i <= x2; i++)
{ {
@@ -275,20 +275,20 @@ public class MAUtils
world.getBlockAt(i,y1-1,k).setType(Material.OBSIDIAN); world.getBlockAt(i,y1-1,k).setType(Material.OBSIDIAN);
} }
} }
// Make a hippie roof. // Make a hippie roof.
for (int i = x1; i <= x2; i++) for (int i = x1; i <= x2; i++)
{ {
for (int k = z1; k <= z2; k++) for (int k = z1; k <= z2; k++)
world.getBlockAt(i,y2,k).setType(Material.GLASS); world.getBlockAt(i,y2,k).setType(Material.GLASS);
} }
// Monster bulldoze // Monster bulldoze
for (int i = x1+1; i < x2; i++) for (int i = x1+1; i < x2; i++)
for (int j = y1+1; j < y2; j++) for (int j = y1+1; j < y2; j++)
for (int k = z1+1; k < z2; k++) for (int k = z1+1; k < z2; k++)
world.getBlockAt(i,j,k).setType(Material.AIR); world.getBlockAt(i,j,k).setType(Material.AIR);
// Build a hippie lobby // Build a hippie lobby
for (int i = lx1; i <= lx2; i++) // Walls for (int i = lx1; i <= lx2; i++) // Walls
{ {
@@ -322,7 +322,7 @@ public class MAUtils
for (int j = ly1+1; j <= ly2; j++) for (int j = ly1+1; j <= ly2; j++)
for (int k = lz1+1; k < lz2; k++) for (int k = lz1+1; k < lz2; k++)
world.getBlockAt(i,j,k).setType(Material.AIR); world.getBlockAt(i,j,k).setType(Material.AIR);
// Place the hippie signs // Place the hippie signs
//Iterator<String> iterator = am.getClasses().iterator(); //Iterator<String> iterator = am.getClasses().iterator();
Iterator<String> iterator = am.getClasses().keySet().iterator(); Iterator<String> iterator = am.getClasses().keySet().iterator();
@@ -336,23 +336,23 @@ public class MAUtils
sign.update(); sign.update();
} }
world.getBlockAt(lx2-2,ly1+1,lz1+2).setType(Material.IRON_BLOCK); world.getBlockAt(lx2-2,ly1+1,lz1+2).setType(Material.IRON_BLOCK);
// Set up the monster points. // Set up the monster points.
ArenaRegion region = arena.getRegion(); ArenaRegion region = arena.getRegion();
region.set("p1", new Location(world, x1, ly1, z1)); region.set("p1", new Location(world, x1, ly1, z1));
region.set("p2", new Location(world, x2, y2+1, z2)); region.set("p2", new Location(world, x2, y2+1, z2));
region.set("arena", new Location(world, loc.getX(), y1+1, loc.getZ())); region.set("arena", new Location(world, loc.getX(), y1+1, loc.getZ()));
region.set("lobby", new Location(world, x1+2, ly1+1, z1+2)); region.set("lobby", new Location(world, x1+2, ly1+1, z1+2));
region.set("spectator", new Location(world, loc.getX(), y2+1, loc.getZ())); region.set("spectator", new Location(world, loc.getX(), y2+1, loc.getZ()));
region.addSpawn("s1", new Location(world, x1+3, y1+2, z1+3)); region.addSpawn("s1", new Location(world, x1+3, y1+2, z1+3));
region.addSpawn("s2", new Location(world, x1+3, y1+2, z2-3)); region.addSpawn("s2", new Location(world, x1+3, y1+2, z2-3));
region.addSpawn("s3", new Location(world, x2-3, y1+2, z1+3)); region.addSpawn("s3", new Location(world, x2-3, y1+2, z1+3));
region.addSpawn("s4", new Location(world, x2-3, y1+2, z2-3)); region.addSpawn("s4", new Location(world, x2-3, y1+2, z2-3));
region.save(); region.save();
am.reloadConfig(); am.reloadConfig();
return true; return true;
} }
} }
@@ -114,7 +114,7 @@ public class MobArena extends JavaPlugin
} }
} }
} }
private void setupArenaMaster() { private void setupArenaMaster() {
arenaMaster = new ArenaMasterImpl(this); arenaMaster = new ArenaMasterImpl(this);
} }
@@ -10,7 +10,7 @@ import org.bukkit.entity.Player;
public class MobArenaHandler public class MobArenaHandler
{ {
private MobArena plugin; private MobArena plugin;
/** /**
* Primary constructor. * Primary constructor.
* The field 'plugin' is initalized, if the server is running MobArena. * The field 'plugin' is initalized, if the server is running MobArena.
@@ -18,15 +18,15 @@ public class MobArenaHandler
public MobArenaHandler() { public MobArenaHandler() {
plugin = (MobArena) Bukkit.getServer().getPluginManager().getPlugin("MobArena"); plugin = (MobArena) Bukkit.getServer().getPluginManager().getPlugin("MobArena");
} }
/*////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////
REGION/LOCATION METHODS REGION/LOCATION METHODS
//////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////*/
/** /**
* Check if a Location is inside of any arena region. * Check if a Location is inside of any arena region.
* @param loc A location. * @param loc A location.
@@ -41,7 +41,7 @@ public class MobArenaHandler
return false; return false;
} }
/** /**
* Check if a Location is inside of a specific arena region (by arena object). * Check if a Location is inside of a specific arena region (by arena object).
* @param arena An Arena object * @param arena An Arena object
@@ -51,7 +51,7 @@ public class MobArenaHandler
public boolean inRegion(Arena arena, Location loc) { public boolean inRegion(Arena arena, Location loc) {
return (arena != null && arena.getRegion().contains(loc)); return (arena != null && arena.getRegion().contains(loc));
} }
/** /**
* Check if a Location is inside of a specific arena region (by arena name). * Check if a Location is inside of a specific arena region (by arena name).
* @param arenaName The name of an arena * @param arenaName The name of an arena
@@ -65,7 +65,7 @@ public class MobArenaHandler
return arena.getRegion().contains(loc); return arena.getRegion().contains(loc);
} }
/** /**
* Check if a Location is inside of the region of an arena that is currently running. * Check if a Location is inside of the region of an arena that is currently running.
* @param loc A location. * @param loc A location.
@@ -74,7 +74,7 @@ public class MobArenaHandler
public boolean inRunningRegion(Location loc) { public boolean inRunningRegion(Location loc) {
return inRegion(loc, false, true); return inRegion(loc, false, true);
} }
/** /**
* Check if a Location is inside of the region of an arena that is currently enabled. * Check if a Location is inside of the region of an arena that is currently enabled.
* @param loc A location. * @param loc A location.
@@ -83,7 +83,7 @@ public class MobArenaHandler
public boolean inEnabledRegion(Location loc) { public boolean inEnabledRegion(Location loc) {
return inRegion(loc, true, false); return inRegion(loc, true, false);
} }
/** /**
* Private helper method for inRunningRegion and inEnabledRegion * Private helper method for inRunningRegion and inEnabledRegion
* @param loc A location * @param loc A location
@@ -106,15 +106,15 @@ public class MobArenaHandler
return false; return false;
} }
/*////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////
PLAYER/MONSTER/PET METHODS PLAYER/MONSTER/PET METHODS
//////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////*/
/** /**
* Check if a player is in a MobArena arena (by Player). * Check if a player is in a MobArena arena (by Player).
* @param player The player * @param player The player
@@ -123,7 +123,7 @@ public class MobArenaHandler
public boolean isPlayerInArena(Player player) { public boolean isPlayerInArena(Player player) {
return (plugin.getArenaMaster().getArenaWithPlayer(player) != null); return (plugin.getArenaMaster().getArenaWithPlayer(player) != null);
} }
/** /**
* Check if a player is in a MobArena arena (by name). * Check if a player is in a MobArena arena (by name).
* @param playerName The name of the player * @param playerName The name of the player
@@ -132,7 +132,7 @@ public class MobArenaHandler
public boolean isPlayerInArena(String playerName) { public boolean isPlayerInArena(String playerName) {
return (plugin.getArenaMaster().getArenaWithPlayer(playerName) != null); return (plugin.getArenaMaster().getArenaWithPlayer(playerName) != null);
} }
/** /**
* Get the MobArena class of a given player. * Get the MobArena class of a given player.
* @param player The player * @param player The player
@@ -144,7 +144,7 @@ public class MobArenaHandler
return getPlayerClass(arena, player); return getPlayerClass(arena, player);
} }
/** /**
* Get the MobArena class of a given player in a given arena. * Get the MobArena class of a given player in a given arena.
* This method is faster than the above method, granted the Arena object is known. * This method is faster than the above method, granted the Arena object is known.
@@ -155,13 +155,13 @@ public class MobArenaHandler
public String getPlayerClass(Arena arena, Player player) { public String getPlayerClass(Arena arena, Player player) {
ArenaPlayer ap = arena.getArenaPlayer(player); ArenaPlayer ap = arena.getArenaPlayer(player);
if (ap == null) return null; if (ap == null) return null;
ArenaClass ac = ap.getArenaClass(); ArenaClass ac = ap.getArenaClass();
if (ac == null) return null; if (ac == null) return null;
return ac.getLowercaseName(); return ac.getLowercaseName();
} }
/** /**
* Check if a monster is in a MobArena arena. * Check if a monster is in a MobArena arena.
* @param entity The monster entity * @param entity The monster entity
@@ -170,7 +170,7 @@ public class MobArenaHandler
public boolean isMonsterInArena(LivingEntity entity) { public boolean isMonsterInArena(LivingEntity entity) {
return plugin.getArenaMaster().getArenaWithMonster(entity) != null; return plugin.getArenaMaster().getArenaWithMonster(entity) != null;
} }
/** /**
* Check if a pet is in a MobArena arena. * Check if a pet is in a MobArena arena.
* @param wolf The pet wolf * @param wolf The pet wolf
@@ -179,15 +179,15 @@ public class MobArenaHandler
public boolean isPetInArena(LivingEntity wolf) { public boolean isPetInArena(LivingEntity wolf) {
return plugin.getArenaMaster().getArenaWithPet(wolf) != null; return plugin.getArenaMaster().getArenaWithPet(wolf) != null;
} }
/*////////////////////////////////////////////////////////////////// /*//////////////////////////////////////////////////////////////////
ARENA GETTERS ARENA GETTERS
//////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////*/
/** /**
* Get an Arena object at the given location. * Get an Arena object at the given location.
* @param loc A location * @param loc A location
@@ -196,7 +196,7 @@ public class MobArenaHandler
public Arena getArenaAtLocation(Location loc) { public Arena getArenaAtLocation(Location loc) {
return plugin.getArenaMaster().getArenaAtLocation(loc); return plugin.getArenaMaster().getArenaAtLocation(loc);
} }
/** /**
* Get the Arena object that the given player is currently in. * Get the Arena object that the given player is currently in.
* @param p A player * @param p A player
@@ -205,7 +205,7 @@ public class MobArenaHandler
public Arena getArenaWithPlayer(Player p) { public Arena getArenaWithPlayer(Player p) {
return plugin.getArenaMaster().getArenaWithPlayer(p); return plugin.getArenaMaster().getArenaWithPlayer(p);
} }
/** /**
* Get the Arena object that the given pet is currently in. * Get the Arena object that the given pet is currently in.
* @param wolf A pet wolf * @param wolf A pet wolf
@@ -214,7 +214,7 @@ public class MobArenaHandler
public Arena getArenaWithPet(Entity wolf) { public Arena getArenaWithPet(Entity wolf) {
return plugin.getArenaMaster().getArenaWithPet(wolf); return plugin.getArenaMaster().getArenaWithPet(wolf);
} }
/** /**
* Get the Arena object that the given monster is currently in. * Get the Arena object that the given monster is currently in.
* @param monster A monster * @param monster A monster
@@ -24,7 +24,7 @@ public class MonsterManager
private Set<LivingEntity> mounts; private Set<LivingEntity> mounts;
private Map<Entity, Player> petToPlayer; private Map<Entity, Player> petToPlayer;
private Map<Player, Set<Entity>> playerToPets; private Map<Player, Set<Entity>> playerToPets;
public MonsterManager() { public MonsterManager() {
this.monsters = new HashSet<>(); this.monsters = new HashSet<>();
this.sheep = new HashSet<>(); this.sheep = new HashSet<>();
@@ -35,7 +35,7 @@ public class MonsterManager
this.petToPlayer = new HashMap<>(); this.petToPlayer = new HashMap<>();
this.playerToPets = new HashMap<>(); this.playerToPets = new HashMap<>();
} }
public void reset() { public void reset() {
monsters.clear(); monsters.clear();
sheep.clear(); sheep.clear();
@@ -46,7 +46,7 @@ public class MonsterManager
petToPlayer.clear(); petToPlayer.clear();
playerToPets.clear(); playerToPets.clear();
} }
public void clear() { public void clear() {
bosses.values().stream() bosses.values().stream()
.map(MABoss::getHealthBar) .map(MABoss::getHealthBar)
@@ -60,10 +60,10 @@ public class MonsterManager
removeAll(suppliers.keySet()); removeAll(suppliers.keySet());
removeAll(mounts); removeAll(mounts);
removeAll(petToPlayer.keySet()); removeAll(petToPlayer.keySet());
reset(); reset();
} }
private void removeAll(Collection<? extends Entity> collection) { private void removeAll(Collection<? extends Entity> collection) {
for (Entity e : collection) { for (Entity e : collection) {
if (e != null) { if (e != null) {
@@ -71,7 +71,7 @@ public class MonsterManager
} }
} }
} }
public void remove(Entity e) { public void remove(Entity e) {
if (monsters.remove(e)) { if (monsters.remove(e)) {
sheep.remove(e); sheep.remove(e);
@@ -83,50 +83,50 @@ public class MonsterManager
} }
} }
} }
public Set<LivingEntity> getMonsters() { public Set<LivingEntity> getMonsters() {
return monsters; return monsters;
} }
public void addMonster(LivingEntity e) { public void addMonster(LivingEntity e) {
monsters.add(e); monsters.add(e);
} }
public boolean removeMonster(Entity e) { public boolean removeMonster(Entity e) {
return monsters.remove(e); return monsters.remove(e);
} }
public Set<LivingEntity> getExplodingSheep() { public Set<LivingEntity> getExplodingSheep() {
return sheep; return sheep;
} }
public void addExplodingSheep(LivingEntity e) { public void addExplodingSheep(LivingEntity e) {
sheep.add(e); sheep.add(e);
} }
public boolean removeExplodingSheep(LivingEntity e) { public boolean removeExplodingSheep(LivingEntity e) {
return sheep.remove(e); return sheep.remove(e);
} }
public Set<LivingEntity> getGolems() { public Set<LivingEntity> getGolems() {
return golems; return golems;
} }
public void addGolem(LivingEntity e) { public void addGolem(LivingEntity e) {
golems.add(e); golems.add(e);
} }
public boolean removeGolem(LivingEntity e) { public boolean removeGolem(LivingEntity e) {
return golems.remove(e); return golems.remove(e);
} }
public void addPet(Player player, Entity pet) { public void addPet(Player player, Entity pet) {
petToPlayer.put(pet, player); petToPlayer.put(pet, player);
playerToPets playerToPets
.computeIfAbsent(player, (key) -> new HashSet<>()) .computeIfAbsent(player, (key) -> new HashSet<>())
.add(pet); .add(pet);
} }
public boolean hasPet(Entity e) { public boolean hasPet(Entity e) {
return petToPlayer.containsKey(e); return petToPlayer.containsKey(e);
} }
@@ -154,7 +154,7 @@ public class MonsterManager
} }
return Collections.emptySet(); return Collections.emptySet();
} }
public void removePets(Player p) { public void removePets(Player p) {
Set<Entity> pets = playerToPets.remove(p); Set<Entity> pets = playerToPets.remove(p);
if (pets != null) { if (pets != null) {
@@ -162,7 +162,7 @@ public class MonsterManager
pets.clear(); pets.clear();
} }
} }
public void addMount(LivingEntity e) { public void addMount(LivingEntity e) {
mounts.add(e); mounts.add(e);
} }
@@ -180,29 +180,29 @@ public class MonsterManager
e.remove(); e.remove();
} }
} }
public void addSupplier(LivingEntity e, List<ItemStack> drops) { public void addSupplier(LivingEntity e, List<ItemStack> drops) {
suppliers.put(e, drops); suppliers.put(e, drops);
} }
public List<ItemStack> getLoot(Entity e) { public List<ItemStack> getLoot(Entity e) {
return suppliers.get(e); return suppliers.get(e);
} }
public MABoss addBoss(LivingEntity e, double maxHealth) { public MABoss addBoss(LivingEntity e, double maxHealth) {
MABoss b = new MABoss(e, maxHealth); MABoss b = new MABoss(e, maxHealth);
bosses.put(e, b); bosses.put(e, b);
return b; return b;
} }
public MABoss removeBoss(LivingEntity e) { public MABoss removeBoss(LivingEntity e) {
return bosses.remove(e); return bosses.remove(e);
} }
public MABoss getBoss(LivingEntity e) { public MABoss getBoss(LivingEntity e) {
return bosses.get(e); return bosses.get(e);
} }
public Set<LivingEntity> getBossMonsters() { public Set<LivingEntity> getBossMonsters() {
return bosses.keySet(); return bosses.keySet();
} }
@@ -124,4 +124,4 @@ public enum Msg {
} }
return yaml; return yaml;
} }
} }
@@ -15,17 +15,17 @@ public class RewardManager
{ {
private Map<Player,List<Thing>> players; private Map<Player,List<Thing>> players;
private Set<Player> rewarded; private Set<Player> rewarded;
public RewardManager(Arena arena) { public RewardManager(Arena arena) {
this.players = new HashMap<>(); this.players = new HashMap<>();
this.rewarded = new HashSet<>(); this.rewarded = new HashSet<>();
} }
public void reset() { public void reset() {
players.clear(); players.clear();
rewarded.clear(); rewarded.clear();
} }
public void addReward(Player p, Thing thing) { public void addReward(Player p, Thing thing) {
if (!players.containsKey(p)) { if (!players.containsKey(p)) {
players.put(p, new ArrayList<>()); players.put(p, new ArrayList<>());
@@ -35,10 +35,10 @@ public class RewardManager
public void grantRewards(Player p) { public void grantRewards(Player p) {
if (rewarded.contains(p)) return; if (rewarded.contains(p)) return;
List<Thing> rewards = players.get(p); List<Thing> rewards = players.get(p);
if (rewards == null) return; if (rewards == null) return;
for (Thing reward : rewards) { for (Thing reward : rewards) {
if (reward == null) { if (reward == null) {
continue; continue;
@@ -47,4 +47,4 @@ public class RewardManager
} }
rewarded.add(p); rewarded.add(p);
} }
} }
@@ -20,7 +20,7 @@ public class ScoreboardManager {
private Objective kills; private Objective kills;
private Map<Player, Scoreboard> scoreboards; private Map<Player, Scoreboard> scoreboards;
/** /**
* Create a new scoreboard for the given arena. * Create a new scoreboard for the given arena.
* @param arena an arena * @param arena an arena
@@ -30,7 +30,7 @@ public class ScoreboardManager {
scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
scoreboards = new HashMap<>(); scoreboards = new HashMap<>();
} }
/** /**
* Add a player to the scoreboard by setting the player's scoreboard * Add a player to the scoreboard by setting the player's scoreboard
* and giving him an initial to-be-reset non-zero score. * and giving him an initial to-be-reset non-zero score.
@@ -44,7 +44,7 @@ public class ScoreboardManager {
player.setScoreboard(scoreboard); player.setScoreboard(scoreboard);
kills.getScore(player.getName()).setScore(8); kills.getScore(player.getName()).setScore(8);
} }
/** /**
* Remove a player from the scoreboard by setting the player's scoreboard * Remove a player from the scoreboard by setting the player's scoreboard
* to the main server scoreboard. * to the main server scoreboard.
@@ -108,7 +108,7 @@ public class ScoreboardManager {
fake.setScore(value); fake.setScore(value);
} }
} }
/** /**
* Update the scoreboard to display the given wave number. * Update the scoreboard to display the given wave number.
* @param wave a wave number * @param wave a wave number
@@ -116,7 +116,7 @@ public class ScoreboardManager {
void updateWave(int wave) { void updateWave(int wave) {
kills.setDisplayName(DISPLAY_NAME + wave); kills.setDisplayName(DISPLAY_NAME + wave);
} }
/** /**
* Initialize the scoreboard by resetting the kills objective and * Initialize the scoreboard by resetting the kills objective and
* setting all player scores to 0. * setting all player scores to 0.
@@ -129,7 +129,7 @@ public class ScoreboardManager {
resetKills(); resetKills();
arena.scheduleTask(this::resetPlayerScores, 1); arena.scheduleTask(this::resetPlayerScores, 1);
} }
private void resetKills() { private void resetKills() {
if (kills != null) { if (kills != null) {
kills.unregister(); kills.unregister();
@@ -53,7 +53,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
private Messenger fallbackMessenger; private Messenger fallbackMessenger;
private Map<String,Command> commands; private Map<String,Command> commands;
public CommandHandler(MobArena plugin) { public CommandHandler(MobArena plugin) {
this.plugin = plugin; this.plugin = plugin;
this.fallbackMessenger = new Messenger("&a[MobArena] "); this.fallbackMessenger = new Messenger("&a[MobArena] ");
@@ -98,7 +98,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
// Get all commands that match the base. // Get all commands that match the base.
List<Command> matches = getMatchingCommands(base); List<Command> matches = getMatchingCommands(base);
// If there's more than one match, display them. // If there's more than one match, display them.
if (matches.size() > 1) { if (matches.size() > 1) {
am.getGlobalMessenger().tell(sender, Msg.MISC_MULTIPLE_MATCHES); am.getGlobalMessenger().tell(sender, Msg.MISC_MULTIPLE_MATCHES);
@@ -107,29 +107,29 @@ public class CommandHandler implements CommandExecutor, TabCompleter
} }
return true; return true;
} }
// If there are no matches at all, notify. // If there are no matches at all, notify.
if (matches.size() == 0) { if (matches.size() == 0) {
am.getGlobalMessenger().tell(sender, Msg.MISC_NO_MATCHES); am.getGlobalMessenger().tell(sender, Msg.MISC_NO_MATCHES);
return true; return true;
} }
// Grab the only match. // Grab the only match.
Command command = matches.get(0); Command command = matches.get(0);
CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); CommandInfo info = command.getClass().getAnnotation(CommandInfo.class);
// First check if the sender has permission. // First check if the sender has permission.
if (!sender.hasPermission(info.permission())) { if (!sender.hasPermission(info.permission())) {
am.getGlobalMessenger().tell(sender, Msg.MISC_NO_ACCESS); am.getGlobalMessenger().tell(sender, Msg.MISC_NO_ACCESS);
return true; return true;
} }
// Check if the last argument is a ?, in which case, display usage and description // Check if the last argument is a ?, in which case, display usage and description
if (last.equals("?") || last.equals("help")) { if (last.equals("?") || last.equals("help")) {
showUsage(command, sender, true); showUsage(command, sender, true);
return true; return true;
} }
// Otherwise, execute the command! // Otherwise, execute the command!
String[] params = trimFirstArg(args); String[] params = trimFirstArg(args);
if (!command.execute(am, sender, params)) { if (!command.execute(am, sender, params)) {
@@ -162,7 +162,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
} }
return true; return true;
} }
/** /**
* Get all commands that match a given string. * Get all commands that match a given string.
* @param arg the given string * @param arg the given string
@@ -170,17 +170,17 @@ public class CommandHandler implements CommandExecutor, TabCompleter
*/ */
private List<Command> getMatchingCommands(String arg) { private List<Command> getMatchingCommands(String arg) {
List<Command> result = new ArrayList<>(); List<Command> result = new ArrayList<>();
// Grab the commands that match the argument. // Grab the commands that match the argument.
for (Entry<String,Command> entry : commands.entrySet()) { for (Entry<String,Command> entry : commands.entrySet()) {
if (arg.matches(entry.getKey())) { if (arg.matches(entry.getKey())) {
result.add(entry.getValue()); result.add(entry.getValue());
} }
} }
return result; return result;
} }
/** /**
* Show the usage and description messages of a command to a player. * Show the usage and description messages of a command to a player.
* The usage will only be shown, if the player has permission for the command. * The usage will only be shown, if the player has permission for the command.
@@ -193,7 +193,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
sender.sendMessage((prefix ? "Usage: " : "") + info.usage() + " " + ChatColor.YELLOW + info.desc()); sender.sendMessage((prefix ? "Usage: " : "") + info.usage() + " " + ChatColor.YELLOW + info.desc());
} }
/** /**
* Remove the first argument of a string. This is because the very first * Remove the first argument of a string. This is because the very first
* element of the arguments array will be the command itself. * element of the arguments array will be the command itself.
@@ -203,7 +203,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
private String[] trimFirstArg(String[] args) { private String[] trimFirstArg(String[] args) {
return Arrays.copyOfRange(args, 1, args.length); return Arrays.copyOfRange(args, 1, args.length);
} }
/** /**
* List all the available MobArena commands for the CommandSender. * List all the available MobArena commands for the CommandSender.
* @param sender a player or the console * @param sender a player or the console
@@ -240,7 +240,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
if (setup.length() > 0) am.getGlobalMessenger().tell(sender, "Setup commands: " + setup.toString()); if (setup.length() > 0) am.getGlobalMessenger().tell(sender, "Setup commands: " + setup.toString());
} }
} }
@Override @Override
public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command bcmd, String alias, String[] args) { public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command bcmd, String alias, String[] args) {
// Only players can tab complete // Only players can tab complete
@@ -302,7 +302,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
*/ */
private void registerCommands() { private void registerCommands() {
commands = new LinkedHashMap<>(); commands = new LinkedHashMap<>();
// mobarena.use // mobarena.use
register(JoinCommand.class); register(JoinCommand.class);
register(LeaveCommand.class); register(LeaveCommand.class);
@@ -319,7 +319,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
register(ForceCommand.class); register(ForceCommand.class);
register(KickCommand.class); register(KickCommand.class);
register(RestoreCommand.class); register(RestoreCommand.class);
// mobarena.setup // mobarena.setup
register(SetupCommand.class); register(SetupCommand.class);
register(SettingCommand.class); register(SettingCommand.class);
@@ -339,7 +339,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
register(RemoveLeaderboardCommand.class); register(RemoveLeaderboardCommand.class);
register(AutoGenerateCommand.class); register(AutoGenerateCommand.class);
} }
/** /**
* Register a command. * Register a command.
* The Command's CommandInfo annotation is queried to find its pattern * The Command's CommandInfo annotation is queried to find its pattern
@@ -349,7 +349,7 @@ public class CommandHandler implements CommandExecutor, TabCompleter
public void register(Class<? extends Command> c) { public void register(Class<? extends Command> c) {
CommandInfo info = c.getAnnotation(CommandInfo.class); CommandInfo info = c.getAnnotation(CommandInfo.class);
if (info == null) return; if (info == null) return;
try { try {
commands.put(info.pattern(), c.newInstance()); commands.put(info.pattern(), c.newInstance());
} }
@@ -10,24 +10,24 @@ public @interface CommandInfo
* The actual name of the command. Not really used anywhere. * The actual name of the command. Not really used anywhere.
*/ */
String name(); String name();
/** /**
* A regex pattern that allows minor oddities and alternatives to the command name. * A regex pattern that allows minor oddities and alternatives to the command name.
*/ */
String pattern(); String pattern();
/** /**
* The usage message, i.e. how the command should be used. * The usage message, i.e. how the command should be used.
*/ */
String usage(); String usage();
/** /**
* A description of what the command does. * A description of what the command does.
*/ */
String desc(); String desc();
/** /**
* The permission required to execute this command. * The permission required to execute this command.
*/ */
String permission(); String permission();
} }
@@ -34,7 +34,7 @@ public class Commands
public static boolean isPlayer(CommandSender sender) { public static boolean isPlayer(CommandSender sender) {
return (sender instanceof Player); return (sender instanceof Player);
} }
public static Arena getArenaToJoinOrSpec(ArenaMaster am, Player p, String arg1) { public static Arena getArenaToJoinOrSpec(ArenaMaster am, Player p, String arg1) {
// Check if MobArena is enabled first. // Check if MobArena is enabled first.
if (!am.isEnabled()) { if (!am.isEnabled()) {
@@ -48,17 +48,17 @@ public class Commands
am.getGlobalMessenger().tell(p, Msg.JOIN_NO_PERMISSION); am.getGlobalMessenger().tell(p, Msg.JOIN_NO_PERMISSION);
return null; return null;
} }
// Then check if we have any enabled arenas. // Then check if we have any enabled arenas.
arenas = am.getEnabledArenas(arenas); arenas = am.getEnabledArenas(arenas);
if (arenas.isEmpty()) { if (arenas.isEmpty()) {
am.getGlobalMessenger().tell(p, Msg.JOIN_NOT_ENABLED); am.getGlobalMessenger().tell(p, Msg.JOIN_NOT_ENABLED);
return null; return null;
} }
// The arena to join. // The arena to join.
Arena arena = null; Arena arena = null;
// Branch on whether there's an argument or not. // Branch on whether there's an argument or not.
if (arg1 != null) { if (arg1 != null) {
arena = am.getArenaWithName(arg1); arena = am.getArenaWithName(arg1);
@@ -66,7 +66,7 @@ public class Commands
am.getGlobalMessenger().tell(p, Msg.ARENA_DOES_NOT_EXIST); am.getGlobalMessenger().tell(p, Msg.ARENA_DOES_NOT_EXIST);
return null; return null;
} }
if (!arenas.contains(arena)) { if (!arenas.contains(arena)) {
am.getGlobalMessenger().tell(p, Msg.JOIN_ARENA_NOT_ENABLED); am.getGlobalMessenger().tell(p, Msg.JOIN_ARENA_NOT_ENABLED);
return null; return null;
@@ -80,18 +80,18 @@ public class Commands
} }
arena = arenas.get(0); arena = arenas.get(0);
} }
// If player is in a boat/minecart, eject! // If player is in a boat/minecart, eject!
if (p.isInsideVehicle()) { if (p.isInsideVehicle()) {
p.leaveVehicle(); p.leaveVehicle();
} }
// If player is in a bed, unbed! // If player is in a bed, unbed!
if (p.isSleeping()) { if (p.isSleeping()) {
p.kickPlayer("Banned for life... Nah, just don't join from a bed ;)"); p.kickPlayer("Banned for life... Nah, just don't join from a bed ;)");
return null; return null;
} }
return arena; return arena;
} }
} }
@@ -26,14 +26,14 @@ public class DisableCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Grab the argument, if any. // Grab the argument, if any.
String arg1 = (args.length > 0 ? args[0] : ""); String arg1 = (args.length > 0 ? args[0] : "");
if (arg1.equals("all")) { if (arg1.equals("all")) {
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
disable(arena, sender); disable(arena, sender);
} }
return true; return true;
} }
if (!arg1.equals("")) { if (!arg1.equals("")) {
Arena arena = am.getArenaWithName(arg1); Arena arena = am.getArenaWithName(arg1);
if (arena == null) { if (arena == null) {
@@ -43,13 +43,13 @@ public class DisableCommand implements Command
disable(arena, sender); disable(arena, sender);
return true; return true;
} }
am.setEnabled(false); am.setEnabled(false);
am.saveConfig(); am.saveConfig();
am.getGlobalMessenger().tell(sender, "MobArena " + ChatColor.RED + "disabled"); am.getGlobalMessenger().tell(sender, "MobArena " + ChatColor.RED + "disabled");
return true; return true;
} }
private void disable(Arena arena, CommandSender sender) { private void disable(Arena arena, CommandSender sender) {
arena.setEnabled(false); arena.setEnabled(false);
arena.getPlugin().saveConfig(); arena.getPlugin().saveConfig();
@@ -26,14 +26,14 @@ public class EnableCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Grab the argument, if any. // Grab the argument, if any.
String arg1 = (args.length > 0 ? args[0] : ""); String arg1 = (args.length > 0 ? args[0] : "");
if (arg1.equals("all")) { if (arg1.equals("all")) {
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
enable(arena, sender); enable(arena, sender);
} }
return true; return true;
} }
if (!arg1.equals("")) { if (!arg1.equals("")) {
Arena arena = am.getArenaWithName(arg1); Arena arena = am.getArenaWithName(arg1);
if (arena == null) { if (arena == null) {
@@ -43,13 +43,13 @@ public class EnableCommand implements Command
enable(arena, sender); enable(arena, sender);
return true; return true;
} }
am.setEnabled(true); am.setEnabled(true);
am.saveConfig(); am.saveConfig();
am.getGlobalMessenger().tell(sender, "MobArena " + ChatColor.GREEN + "enabled"); am.getGlobalMessenger().tell(sender, "MobArena " + ChatColor.GREEN + "enabled");
return true; return true;
} }
private void enable(Arena arena, CommandSender sender) { private void enable(Arena arena, CommandSender sender) {
arena.setEnabled(true); arena.setEnabled(true);
arena.getPlugin().saveConfig(); arena.getPlugin().saveConfig();
@@ -30,7 +30,7 @@ public class ForceCommand implements Command
// Grab the argument, if any. // Grab the argument, if any.
String arg1 = (args.length > 0 ? args[0] : ""); String arg1 = (args.length > 0 ? args[0] : "");
String arg2 = (args.length > 1 ? args[1] : ""); String arg2 = (args.length > 1 ? args[1] : "");
if (arg1.equals("end")) { if (arg1.equals("end")) {
// With no arguments, end all. // With no arguments, end all.
if (arg2.equals("")) { if (arg2.equals("")) {
@@ -41,46 +41,46 @@ public class ForceCommand implements Command
am.resetArenaMap(); am.resetArenaMap();
return true; return true;
} }
// Otherwise, grab the arena in question. // Otherwise, grab the arena in question.
Arena arena = am.getArenaWithName(arg2); Arena arena = am.getArenaWithName(arg2);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST); am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST);
return true; return true;
} }
if (arena.getAllPlayers().isEmpty()) { if (arena.getAllPlayers().isEmpty()) {
am.getGlobalMessenger().tell(sender, Msg.FORCE_END_EMPTY); am.getGlobalMessenger().tell(sender, Msg.FORCE_END_EMPTY);
return true; return true;
} }
// And end it! // And end it!
arena.forceEnd(); arena.forceEnd();
am.getGlobalMessenger().tell(sender, Msg.FORCE_END_ENDED); am.getGlobalMessenger().tell(sender, Msg.FORCE_END_ENDED);
return true; return true;
} }
if (arg1.equals("start")) { if (arg1.equals("start")) {
// Require argument. // Require argument.
if (arg2.equals("")) return false; if (arg2.equals("")) return false;
// Grab the arena. // Grab the arena.
Arena arena = am.getArenaWithName(arg2); Arena arena = am.getArenaWithName(arg2);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST); am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST);
return true; return true;
} }
if (arena.isRunning()) { if (arena.isRunning()) {
am.getGlobalMessenger().tell(sender, Msg.FORCE_START_RUNNING); am.getGlobalMessenger().tell(sender, Msg.FORCE_START_RUNNING);
return true; return true;
} }
if (arena.getReadyPlayersInLobby().isEmpty()) { if (arena.getReadyPlayersInLobby().isEmpty()) {
am.getGlobalMessenger().tell(sender, Msg.FORCE_START_NOT_READY); am.getGlobalMessenger().tell(sender, Msg.FORCE_START_NOT_READY);
return true; return true;
} }
// And start it! // And start it!
arena.forceStart(); arena.forceStart();
am.getGlobalMessenger().tell(sender, Msg.FORCE_START_STARTED); am.getGlobalMessenger().tell(sender, Msg.FORCE_START_STARTED);
@@ -24,16 +24,16 @@ public class KickCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Require a player name // Require a player name
if (args.length != 1) return false; if (args.length != 1) return false;
Arena arena = am.getArenaWithPlayer(args[0]); Arena arena = am.getArenaWithPlayer(args[0]);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, "That player is not in an arena."); am.getGlobalMessenger().tell(sender, "That player is not in an arena.");
return true; return true;
} }
// Grab the Player object. // Grab the Player object.
Player bp = am.getPlugin().getServer().getPlayer(args[0]); Player bp = am.getPlugin().getServer().getPlayer(args[0]);
// Force leave. // Force leave.
arena.playerLeave(bp); arena.playerLeave(bp);
am.getGlobalMessenger().tell(sender, "Player '" + args[0] + "' was kicked from arena '" + arena.configName() + "'."); am.getGlobalMessenger().tell(sender, "Player '" + args[0] + "' was kicked from arena '" + arena.configName() + "'.");
@@ -25,7 +25,7 @@ public class RestoreCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Require a player name // Require a player name
if (args.length != 1) return false; if (args.length != 1) return false;
Player player = am.getPlugin().getServer().getPlayer(args[0]); Player player = am.getPlugin().getServer().getPlayer(args[0]);
if (player == null) { if (player == null) {
am.getGlobalMessenger().tell(sender, "Player not found."); am.getGlobalMessenger().tell(sender, "Player not found.");
@@ -35,7 +35,7 @@ public class RestoreCommand implements Command
am.getGlobalMessenger().tell(sender, "Player is currently in an arena."); am.getGlobalMessenger().tell(sender, "Player is currently in an arena.");
return true; return true;
} }
if (InventoryManager.restoreFromFile(am.getPlugin(), player)) { if (InventoryManager.restoreFromFile(am.getPlugin(), player)) {
am.getGlobalMessenger().tell(sender, "Restored " + args[0] + "'s inventory!"); am.getGlobalMessenger().tell(sender, "Restored " + args[0] + "'s inventory!");
} else { } else {
@@ -27,10 +27,10 @@ public class AddArenaCommand implements Command
// Require an arena name // Require an arena name
if (args.length != 1) return false; if (args.length != 1) return false;
// Unwrap the sender. // Unwrap the sender.
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
Arena arena = am.getArenaWithName(args[0]); Arena arena = am.getArenaWithName(args[0]);
if (arena != null) { if (arena != null) {
am.getGlobalMessenger().tell(sender, "An arena with that name already exists."); am.getGlobalMessenger().tell(sender, "An arena with that name already exists.");
@@ -28,22 +28,22 @@ public class AutoGenerateCommand implements Command
// Require an arena name // Require an arena name
if (args.length != 1) return false; if (args.length != 1) return false;
// Unwrap the sender. // Unwrap the sender.
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
// Check if arena already exists. // Check if arena already exists.
Arena arena = am.getArenaWithName(args[0]); Arena arena = am.getArenaWithName(args[0]);
if (arena != null) { if (arena != null) {
am.getGlobalMessenger().tell(sender, "An arena with that name already exists."); am.getGlobalMessenger().tell(sender, "An arena with that name already exists.");
return true; return true;
} }
if (!MAUtils.doooooItHippieMonster(p.getLocation(), 13, args[0], am.getPlugin())) { if (!MAUtils.doooooItHippieMonster(p.getLocation(), 13, args[0], am.getPlugin())) {
am.getGlobalMessenger().tell(sender, "Could not auto-generate arena."); am.getGlobalMessenger().tell(sender, "Could not auto-generate arena.");
return true; return true;
} }
am.getGlobalMessenger().tell(sender, "Arena with name '" + args[0] + "' generated."); am.getGlobalMessenger().tell(sender, "Arena with name '" + args[0] + "' generated.");
return true; return true;
} }
@@ -24,7 +24,7 @@ public class ListClassesCommand implements Command
am.getGlobalMessenger().tell(sender, "<none>"); am.getGlobalMessenger().tell(sender, "<none>");
return true; return true;
} }
for (String c : classes) { for (String c : classes) {
am.getGlobalMessenger().tell(sender, "- " + c); am.getGlobalMessenger().tell(sender, "- " + c);
} }
@@ -24,12 +24,12 @@ public class RemoveArenaCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Require an arena name // Require an arena name
if (args.length != 1) return false; if (args.length != 1) return false;
if (am.getArenas().size() == 1) { if (am.getArenas().size() == 1) {
am.getGlobalMessenger().tell(sender, "At least one arena must exist."); am.getGlobalMessenger().tell(sender, "At least one arena must exist.");
return true; return true;
} }
Arena arena = am.getArenaWithName(args[0]); Arena arena = am.getArenaWithName(args[0]);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, "There is no arena with that name."); am.getGlobalMessenger().tell(sender, "There is no arena with that name.");
@@ -41,4 +41,4 @@ public class RemoveLeaderboardCommand implements Command
} }
return true; return true;
} }
} }
@@ -24,14 +24,14 @@ public class ArenaListCommand implements Command
@Override @Override
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
List<Arena> arenas; List<Arena> arenas;
if (Commands.isPlayer(sender)) { if (Commands.isPlayer(sender)) {
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
arenas = am.getPermittedArenas(p); arenas = am.getPermittedArenas(p);
} else { } else {
arenas = am.getArenas(); arenas = am.getArenas();
} }
String list = MAUtils.listToString(arenas, am.getPlugin()); String list = MAUtils.listToString(arenas, am.getPlugin());
am.getGlobalMessenger().tell(sender, Msg.MISC_LIST_ARENAS.format(list)); am.getGlobalMessenger().tell(sender, Msg.MISC_LIST_ARENAS.format(list));
return true; return true;
@@ -29,7 +29,7 @@ public class JoinCommand implements Command
am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE); am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE);
return true; return true;
} }
// Unwrap the sender, grab the argument, if any. // Unwrap the sender, grab the argument, if any.
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
String arg1 = (args.length > 0 ? args[0] : null); String arg1 = (args.length > 0 ? args[0] : null);
@@ -39,7 +39,7 @@ public class JoinCommand implements Command
if (toArena == null || !canJoin(p, toArena)) { if (toArena == null || !canJoin(p, toArena)) {
return true; return true;
} }
// Join the arena! // Join the arena!
int seconds = toArena.getSettings().getInt("join-interrupt-timer", 0); int seconds = toArena.getSettings().getInt("join-interrupt-timer", 0);
if (seconds > 0) { if (seconds > 0) {
@@ -24,11 +24,11 @@ public class LeaveCommand implements Command
am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE); am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE);
return true; return true;
} }
// Unwrap the sender. // Unwrap the sender.
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
Arena arena = am.getArenaWithPlayer(p); Arena arena = am.getArenaWithPlayer(p);
if (arena == null) { if (arena == null) {
arena = am.getArenaWithSpectator(p); arena = am.getArenaWithSpectator(p);
if (arena == null) { if (arena == null) {
@@ -36,7 +36,7 @@ public class LeaveCommand implements Command
return true; return true;
} }
} }
if (arena.playerLeave(p)) { if (arena.playerLeave(p)) {
arena.getMessenger().tell(p, Msg.LEAVE_PLAYER_LEFT); arena.getMessenger().tell(p, Msg.LEAVE_PLAYER_LEFT);
} }
@@ -23,10 +23,10 @@ public class NotReadyCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Grab the argument, if any // Grab the argument, if any
String arg1 = (args.length > 0 ? args[0] : ""); String arg1 = (args.length > 0 ? args[0] : "");
// The arena to query. // The arena to query.
Arena arena = null; Arena arena = null;
if (!arg1.equals("")) { if (!arg1.equals("")) {
arena = am.getArenaWithName(arg1); arena = am.getArenaWithName(arg1);
if (arena == null) { if (arena == null) {
@@ -36,7 +36,7 @@ public class NotReadyCommand implements Command
} else if (Commands.isPlayer(sender)) { } else if (Commands.isPlayer(sender)) {
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
arena = am.getArenaWithPlayer(p); arena = am.getArenaWithPlayer(p);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, Msg.LEAVE_NOT_PLAYING); am.getGlobalMessenger().tell(sender, Msg.LEAVE_NOT_PLAYING);
return true; return true;
@@ -44,7 +44,7 @@ public class NotReadyCommand implements Command
} else { } else {
return false; return false;
} }
String list = MAUtils.listToString(arena.getNonreadyPlayers(), am.getPlugin()); String list = MAUtils.listToString(arena.getNonreadyPlayers(), am.getPlugin());
arena.getMessenger().tell(sender, Msg.MISC_LIST_PLAYERS.format(list)); arena.getMessenger().tell(sender, Msg.MISC_LIST_PLAYERS.format(list));
return true; return true;
@@ -36,7 +36,7 @@ public class PickClassCommand implements Command
// Require a class name // Require a class name
if (args.length != 1) return false; if (args.length != 1) return false;
// Unwrap the sender // Unwrap the sender
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
@@ -25,29 +25,29 @@ public class PlayerListCommand implements Command
public boolean execute(ArenaMaster am, CommandSender sender, String... args) { public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
// Grab the argument, if any. // Grab the argument, if any.
String arg1 = (args.length > 0 ? args[0] : ""); String arg1 = (args.length > 0 ? args[0] : "");
String list = null; String list = null;
if (!arg1.equals("")) { if (!arg1.equals("")) {
Arena arena = am.getArenaWithName(arg1); Arena arena = am.getArenaWithName(arg1);
if (arena == null) { if (arena == null) {
am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST); am.getGlobalMessenger().tell(sender, Msg.ARENA_DOES_NOT_EXIST);
return false; return false;
} }
list = MAUtils.listToString(arena.getPlayersInArena(), am.getPlugin()); list = MAUtils.listToString(arena.getPlayersInArena(), am.getPlugin());
} else { } else {
StringBuilder buffy = new StringBuilder(); StringBuilder buffy = new StringBuilder();
List<Player> players = new LinkedList<>(); List<Player> players = new LinkedList<>();
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
players.addAll(arena.getPlayersInArena()); players.addAll(arena.getPlayersInArena());
} }
buffy.append(MAUtils.listToString(players, am.getPlugin())); buffy.append(MAUtils.listToString(players, am.getPlugin()));
list = buffy.toString(); list = buffy.toString();
} }
am.getGlobalMessenger().tell(sender, Msg.MISC_LIST_PLAYERS.format(list)); am.getGlobalMessenger().tell(sender, Msg.MISC_LIST_PLAYERS.format(list));
return true; return true;
} }
@@ -29,11 +29,11 @@ public class SpecCommand implements Command
am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE); am.getGlobalMessenger().tell(sender, Msg.MISC_NOT_FROM_CONSOLE);
return false; return false;
} }
// Unwrap the sender, grab the argument, if any. // Unwrap the sender, grab the argument, if any.
Player p = Commands.unwrap(sender); Player p = Commands.unwrap(sender);
String arg1 = (args.length > 0 ? args[0] : null); String arg1 = (args.length > 0 ? args[0] : null);
// Run some rough sanity checks, and grab the arena to spec. // Run some rough sanity checks, and grab the arena to spec.
Arena toArena = Commands.getArenaToJoinOrSpec(am, p, arg1); Arena toArena = Commands.getArenaToJoinOrSpec(am, p, arg1);
if (toArena == null || !canSpec(p, toArena)) { if (toArena == null || !canSpec(p, toArena)) {
@@ -10,12 +10,12 @@ public class ArenaEndEvent extends Event implements Cancellable
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;
public ArenaEndEvent(Arena arena) { public ArenaEndEvent(Arena arena) {
this.arena = arena; this.arena = arena;
this.cancelled = false; this.cancelled = false;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -29,12 +29,12 @@ public class ArenaEndEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -11,17 +11,17 @@ public class ArenaPlayerDeathEvent extends Event
private Player player; private Player player;
private Arena arena; private Arena arena;
private boolean last; private boolean last;
public ArenaPlayerDeathEvent(Player player, Arena arena, boolean last) { public ArenaPlayerDeathEvent(Player player, Arena arena, boolean last) {
this.player = player; this.player = player;
this.arena = arena; this.arena = arena;
this.last = last; this.last = last;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -29,12 +29,12 @@ public class ArenaPlayerDeathEvent extends Event
public boolean wasLastPlayerStanding() { public boolean wasLastPlayerStanding() {
return last; return last;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -12,17 +12,17 @@ public class ArenaPlayerJoinEvent extends Event implements Cancellable
private Player player; private Player player;
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;
public ArenaPlayerJoinEvent(Player player, Arena arena) { public ArenaPlayerJoinEvent(Player player, Arena arena) {
this.player = player; this.player = player;
this.arena = arena; this.arena = arena;
this.cancelled = false; this.cancelled = false;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -36,12 +36,12 @@ public class ArenaPlayerJoinEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -12,17 +12,17 @@ public class ArenaPlayerLeaveEvent extends Event implements Cancellable
private Player player; private Player player;
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;
public ArenaPlayerLeaveEvent(Player player, Arena arena) { public ArenaPlayerLeaveEvent(Player player, Arena arena) {
this.player = player; this.player = player;
this.arena = arena; this.arena = arena;
this.cancelled = false; this.cancelled = false;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -36,12 +36,12 @@ public class ArenaPlayerLeaveEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -18,11 +18,11 @@ public class ArenaPlayerReadyEvent extends Event implements Cancellable
this.arena = arena; this.arena = arena;
this.cancelled = false; this.cancelled = false;
} }
public Player getPlayer() { public Player getPlayer() {
return player; return player;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -36,12 +36,12 @@ public class ArenaPlayerReadyEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -10,12 +10,12 @@ public class ArenaStartEvent extends Event implements Cancellable
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;
public ArenaStartEvent(Arena arena) { public ArenaStartEvent(Arena arena) {
this.arena = arena; this.arena = arena;
this.cancelled = false; this.cancelled = false;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -29,12 +29,12 @@ public class ArenaStartEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }
@@ -11,10 +11,10 @@ public class NewWaveEvent extends Event implements Cancellable
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;
private Wave wave; private Wave wave;
private int waveNo; private int waveNo;
public NewWaveEvent(Arena arena, Wave wave, int waveNo) { public NewWaveEvent(Arena arena, Wave wave, int waveNo) {
this.arena = arena; this.arena = arena;
this.wave = wave; this.wave = wave;
@@ -24,11 +24,11 @@ public class NewWaveEvent extends Event implements Cancellable
public Wave getWave() { public Wave getWave() {
return wave; return wave;
} }
public int getWaveNumber() { public int getWaveNumber() {
return waveNo; return waveNo;
} }
public Arena getArena() { public Arena getArena() {
return arena; return arena;
} }
@@ -42,11 +42,11 @@ public class NewWaveEvent extends Event implements Cancellable
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@@ -40,78 +40,78 @@ public interface Arena
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
ConfigurationSection getSettings(); ConfigurationSection getSettings();
World getWorld(); World getWorld();
void setWorld(World world); void setWorld(World world);
boolean isEnabled(); boolean isEnabled();
void setEnabled(boolean value); void setEnabled(boolean value);
boolean isProtected(); boolean isProtected();
void setProtected(boolean value); void setProtected(boolean value);
boolean isRunning(); boolean isRunning();
boolean inEditMode(); boolean inEditMode();
void setEditMode(boolean value); void setEditMode(boolean value);
int getMinPlayers(); int getMinPlayers();
int getMaxPlayers(); int getMaxPlayers();
List<Thing> getEntryFee(); List<Thing> getEntryFee();
Set<Map.Entry<Integer,List<Thing>>> getEveryWaveEntrySet(); Set<Map.Entry<Integer,List<Thing>>> getEveryWaveEntrySet();
List<Thing> getAfterWaveReward(int wave); List<Thing> getAfterWaveReward(int wave);
Set<Player> getPlayersInArena(); Set<Player> getPlayersInArena();
Set<Player> getPlayersInLobby(); Set<Player> getPlayersInLobby();
Set<Player> getReadyPlayersInLobby(); Set<Player> getReadyPlayersInLobby();
Set<Player> getSpectators(); Set<Player> getSpectators();
MASpawnThread getSpawnThread(); MASpawnThread getSpawnThread();
WaveManager getWaveManager(); WaveManager getWaveManager();
ArenaListener getEventListener(); ArenaListener getEventListener();
void setLeaderboard(Leaderboard leaderboard); void setLeaderboard(Leaderboard leaderboard);
ArenaPlayer getArenaPlayer(Player p); ArenaPlayer getArenaPlayer(Player p);
Set<Block> getBlocks(); Set<Block> getBlocks();
void addBlock(Block b); void addBlock(Block b);
boolean removeBlock(Block b); boolean removeBlock(Block b);
boolean hasPet(Entity e); boolean hasPet(Entity e);
void addRepairable(Repairable r); void addRepairable(Repairable r);
ArenaRegion getRegion(); ArenaRegion getRegion();
InventoryManager getInventoryManager(); InventoryManager getInventoryManager();
RewardManager getRewardManager(); RewardManager getRewardManager();
MonsterManager getMonsterManager(); MonsterManager getMonsterManager();
ClassLimitManager getClassLimitManager(); ClassLimitManager getClassLimitManager();
void revivePlayer(Player p); void revivePlayer(Player p);
ScoreboardManager getScoreboard(); ScoreboardManager getScoreboard();
Messenger getMessenger(); Messenger getMessenger();
Messenger getGlobalMessenger(); Messenger getGlobalMessenger();
@@ -121,127 +121,127 @@ public interface Arena
void announce(Msg msg, String s); void announce(Msg msg, String s);
void announce(Msg msg); void announce(Msg msg);
void scheduleTask(Runnable r, int delay); void scheduleTask(Runnable r, int delay);
boolean startArena(); boolean startArena();
boolean endArena(); boolean endArena();
void forceStart(); void forceStart();
void forceEnd(); void forceEnd();
boolean hasPermission(Player p); boolean hasPermission(Player p);
boolean playerJoin(Player p, Location loc); boolean playerJoin(Player p, Location loc);
void playerReady(Player p); void playerReady(Player p);
boolean playerLeave(Player p); boolean playerLeave(Player p);
boolean isMoving(Player p); boolean isMoving(Player p);
boolean isLeaving(Player p); boolean isLeaving(Player p);
void playerDeath(Player p); void playerDeath(Player p);
void playerRespawn(Player p); void playerRespawn(Player p);
Location getRespawnLocation(Player p); Location getRespawnLocation(Player p);
void playerSpec(Player p, Location loc); void playerSpec(Player p, Location loc);
void storeContainerContents(); void storeContainerContents();
void restoreContainerContents(); void restoreContainerContents();
void discardPlayer(Player p); void discardPlayer(Player p);
void repairBlocks(); void repairBlocks();
void queueRepairable(Repairable r); void queueRepairable(Repairable r);
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Items & Cleanup // Items & Cleanup
// //
////////////////////////////////////////////////////////////////////*/ ////////////////////////////////////////////////////////////////////*/
void assignClass(Player p, String className); void assignClass(Player p, String className);
void assignClassGiveInv(Player p, String className, ItemStack[] contents); void assignClassGiveInv(Player p, String className, ItemStack[] contents);
void addRandomPlayer(Player p); void addRandomPlayer(Player p);
void assignRandomClass(Player p); void assignRandomClass(Player p);
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Initialization & Checks // Initialization & Checks
// //
////////////////////////////////////////////////////////////////////*/ ////////////////////////////////////////////////////////////////////*/
void restoreRegion(); void restoreRegion();
/*//////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////
// //
// Getters & Misc // Getters & Misc
// //
////////////////////////////////////////////////////////////////////*/ ////////////////////////////////////////////////////////////////////*/
boolean inArena(Player p); boolean inArena(Player p);
boolean inLobby(Player p); boolean inLobby(Player p);
boolean inSpec(Player p); boolean inSpec(Player p);
boolean isDead(Player p); boolean isDead(Player p);
String configName(); String configName();
String arenaName(); String arenaName();
MobArena getPlugin(); MobArena getPlugin();
Map<String,ArenaClass> getClasses(); Map<String,ArenaClass> getClasses();
int getPlayerCount(); int getPlayerCount();
List<Player> getAllPlayers(); List<Player> getAllPlayers();
Collection<ArenaPlayer> getArenaPlayerSet(); Collection<ArenaPlayer> getArenaPlayerSet();
List<Player> getNonreadyPlayers(); List<Player> getNonreadyPlayers();
boolean canAfford(Player p); boolean canAfford(Player p);
boolean takeFee(Player p); boolean takeFee(Player p);
boolean refund(Player p); boolean refund(Player p);
boolean canJoin(Player p); boolean canJoin(Player p);
boolean canSpec(Player p); boolean canSpec(Player p);
boolean hasIsolatedChat(); boolean hasIsolatedChat();
@@ -21,121 +21,121 @@ public interface ArenaMaster
// NEW METHODS IN REFACTORING // NEW METHODS IN REFACTORING
// //
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
MobArena getPlugin(); MobArena getPlugin();
Messenger getGlobalMessenger(); Messenger getGlobalMessenger();
boolean isEnabled(); boolean isEnabled();
void setEnabled(boolean value); void setEnabled(boolean value);
boolean notifyOnUpdates(); boolean notifyOnUpdates();
List<Arena> getArenas(); List<Arena> getArenas();
Map<String,ArenaClass> getClasses(); Map<String,ArenaClass> getClasses();
void addPlayer(Player p, Arena arena); void addPlayer(Player p, Arena arena);
Arena removePlayer(Player p); Arena removePlayer(Player p);
void resetArenaMap(); void resetArenaMap();
/*///////////////////////////////////////////////////////////////////////// /*/////////////////////////////////////////////////////////////////////////
// //
// Getters // Getters
// //
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
List<Arena> getEnabledArenas(); List<Arena> getEnabledArenas();
List<Arena> getEnabledArenas(List<Arena> arenas); List<Arena> getEnabledArenas(List<Arena> arenas);
List<Arena> getPermittedArenas(Player p); List<Arena> getPermittedArenas(Player p);
List<Arena> getEnabledAndPermittedArenas(Player p); List<Arena> getEnabledAndPermittedArenas(Player p);
Arena getArenaAtLocation(Location loc); Arena getArenaAtLocation(Location loc);
List<Arena> getArenasInWorld(World world); List<Arena> getArenasInWorld(World world);
List<Player> getAllPlayers(); List<Player> getAllPlayers();
List<Player> getAllPlayersInArena(String arenaName); List<Player> getAllPlayersInArena(String arenaName);
List<Player> getAllLivingPlayers(); List<Player> getAllLivingPlayers();
List<Player> getLivingPlayersInArena(String arenaName); List<Player> getLivingPlayersInArena(String arenaName);
Arena getArenaWithPlayer(Player p); Arena getArenaWithPlayer(Player p);
Arena getArenaWithPlayer(String playerName); Arena getArenaWithPlayer(String playerName);
Arena getArenaWithSpectator(Player p); Arena getArenaWithSpectator(Player p);
Arena getArenaWithMonster(Entity e); Arena getArenaWithMonster(Entity e);
Arena getArenaWithPet(Entity e); Arena getArenaWithPet(Entity e);
Arena getArenaWithName(String configName); Arena getArenaWithName(String configName);
Arena getArenaWithName(Collection<Arena> arenas, String configName); Arena getArenaWithName(Collection<Arena> arenas, String configName);
boolean isAllowed(String command); boolean isAllowed(String command);
JoinInterruptTimer getJoinInterruptTimer(); JoinInterruptTimer getJoinInterruptTimer();
/*///////////////////////////////////////////////////////////////////////// /*/////////////////////////////////////////////////////////////////////////
// //
// Initialization // Initialization
// //
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
void initialize(); void initialize();
/** /**
* Load the global settings. * Load the global settings.
*/ */
void loadSettings(); void loadSettings();
/** /**
* Load all class-related stuff. * Load all class-related stuff.
*/ */
void loadClasses(); void loadClasses();
/** /**
* Load all arena-related stuff. * Load all arena-related stuff.
*/ */
void loadArenas(); void loadArenas();
void loadArenasInWorld(String worldName); void loadArenasInWorld(String worldName);
void unloadArenasInWorld(String worldName); void unloadArenasInWorld(String worldName);
boolean reloadArena(String name); boolean reloadArena(String name);
Arena createArenaNode(String configName, World world); Arena createArenaNode(String configName, World world);
void removeArenaNode(Arena arena); void removeArenaNode(Arena arena);
SpawnsPets getSpawnsPets(); SpawnsPets getSpawnsPets();
/*///////////////////////////////////////////////////////////////////////// /*/////////////////////////////////////////////////////////////////////////
// //
// Update and serialization methods // Update and serialization methods
// //
/////////////////////////////////////////////////////////////////////////*/ /////////////////////////////////////////////////////////////////////////*/
void reloadConfig(); void reloadConfig();
void saveConfig(); void saveConfig();
} }
@@ -10,32 +10,32 @@ public abstract class AbstractLeaderboardColumn implements LeaderboardColumn
protected String statname; protected String statname;
private Sign header; private Sign header;
private List<Sign> signs; private List<Sign> signs;
public AbstractLeaderboardColumn(String statname, Sign header, List<Sign> signs) { public AbstractLeaderboardColumn(String statname, Sign header, List<Sign> signs) {
this.statname = statname; this.statname = statname;
this.header = header; this.header = header;
this.signs = signs; this.signs = signs;
} }
public void update(List<ArenaPlayerStatistics> stats) { public void update(List<ArenaPlayerStatistics> stats) {
// Make sure the stats will fit on the signs. // Make sure the stats will fit on the signs.
int range = Math.min(stats.size(), signs.size()*4); int range = Math.min(stats.size(), signs.size()*4);
for (int i = 0; i < range; i++) { for (int i = 0; i < range; i++) {
// Grab the right sign. // Grab the right sign.
Sign s = signs.get(i/4); Sign s = signs.get(i/4);
// Call the template method. // Call the template method.
String value = getLine(stats.get(i)); String value = getLine(stats.get(i));
// And set the line // And set the line
s.setLine(i % 4, value); s.setLine(i % 4, value);
s.update(); s.update();
} }
} }
public abstract String getLine(ArenaPlayerStatistics stats); public abstract String getLine(ArenaPlayerStatistics stats);
public void clear() { public void clear() {
for (Sign s : signs) { for (Sign s : signs) {
s.setLine(0, ""); s.setLine(0, "");
@@ -45,11 +45,11 @@ public abstract class AbstractLeaderboardColumn implements LeaderboardColumn
s.update(); s.update();
} }
} }
public Sign getHeader() { public Sign getHeader() {
return header; return header;
} }
public List<Sign> getSigns() { public List<Sign> getSigns() {
return signs; return signs;
} }
@@ -21,17 +21,17 @@ public class Leaderboard
{ {
private MobArena plugin; private MobArena plugin;
private Arena arena; private Arena arena;
private Location topLeft; private Location topLeft;
private Sign topLeftSign; private Sign topLeftSign;
private BlockFace direction; private BlockFace direction;
private int rows, cols, trackingId; private int rows, cols, trackingId;
private List<LeaderboardColumn> boards; private List<LeaderboardColumn> boards;
private List<ArenaPlayerStatistics> stats; private List<ArenaPlayerStatistics> stats;
private boolean isValid; private boolean isValid;
/** /**
* Private constructor. * Private constructor.
* Creates a new leaderboard with no signs or locations or anything. * Creates a new leaderboard with no signs or locations or anything.
@@ -45,7 +45,7 @@ public class Leaderboard
this.boards = new ArrayList<>(); this.boards = new ArrayList<>();
this.stats = new ArrayList<>(); this.stats = new ArrayList<>();
} }
/** /**
* Location constructor. * Location constructor.
* Used to create a leaderboard on-the-fly from the location from the SignChangeEvent. * Used to create a leaderboard on-the-fly from the location from the SignChangeEvent.
@@ -56,19 +56,19 @@ public class Leaderboard
public Leaderboard(MobArena plugin, Arena arena, Location topLeft) public Leaderboard(MobArena plugin, Arena arena, Location topLeft)
{ {
this(plugin, arena); this(plugin, arena);
if (topLeft == null) { if (topLeft == null) {
return; return;
} }
if (!(topLeft.getBlock().getState() instanceof Sign)) { if (!(topLeft.getBlock().getState() instanceof Sign)) {
plugin.getLogger().warning("The leaderboard-node for arena '" + arena.configName() + "' does not point to a sign!"); plugin.getLogger().warning("The leaderboard-node for arena '" + arena.configName() + "' does not point to a sign!");
return; return;
} }
this.topLeft = topLeft; this.topLeft = topLeft;
} }
/** /**
* Grab all adjacent signs and register the individual columns. * Grab all adjacent signs and register the individual columns.
*/ */
@@ -77,26 +77,26 @@ public class Leaderboard
if (!isGridWellFormed()) { if (!isGridWellFormed()) {
return; return;
} }
initializeBoards(); initializeBoards();
initializeStats(); initializeStats();
clear(); clear();
} }
public void clear() public void clear()
{ {
for (LeaderboardColumn column : boards) for (LeaderboardColumn column : boards)
column.clear(); column.clear();
} }
public void update() public void update()
{ {
Collections.sort(stats, ArenaPlayerStatistics.waveComparator()); Collections.sort(stats, ArenaPlayerStatistics.waveComparator());
for (LeaderboardColumn column : boards) for (LeaderboardColumn column : boards)
column.update(stats); column.update(stats);
} }
public void startTracking() public void startTracking()
{ {
trackingId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, trackingId = plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin,
@@ -108,12 +108,12 @@ public class Leaderboard
} }
}, 100, 100); }, 100, 100);
} }
public void stopTracking() public void stopTracking()
{ {
plugin.getServer().getScheduler().cancelTask(trackingId); plugin.getServer().getScheduler().cancelTask(trackingId);
} }
/** /**
* Check if the leaderboards grid is well-formed. * Check if the leaderboards grid is well-formed.
* @return true, if the grid is well-formed, false otherwise. * @return true, if the grid is well-formed, false otherwise.
@@ -123,19 +123,19 @@ public class Leaderboard
if (topLeft == null) { if (topLeft == null) {
return false; return false;
} }
BlockState state = topLeft.getBlock().getState(); BlockState state = topLeft.getBlock().getState();
if (!(state instanceof Sign)) if (!(state instanceof Sign))
{ {
plugin.getLogger().severe("Leaderboards for '" + arena.configName() + "' could not be established!"); plugin.getLogger().severe("Leaderboards for '" + arena.configName() + "' could not be established!");
return false; return false;
} }
// Grab the top left sign and set up a copy for parsing. // Grab the top left sign and set up a copy for parsing.
this.topLeftSign = (Sign) state; this.topLeftSign = (Sign) state;
Sign current = this.topLeftSign; Sign current = this.topLeftSign;
// Calculate matrix dimensions. // Calculate matrix dimensions.
BlockFace direction = getRightDirection(current); BlockFace direction = getRightDirection(current);
if (direction == null) { if (direction == null) {
@@ -144,12 +144,12 @@ public class Leaderboard
this.direction = direction; this.direction = direction;
this.rows = getSignCount(current, BlockFace.DOWN); this.rows = getSignCount(current, BlockFace.DOWN);
this.cols = getSignCount(current, direction); this.cols = getSignCount(current, direction);
// Require at least 2x2 to be valid // Require at least 2x2 to be valid
if (rows <= 1 || cols <= 1) { if (rows <= 1 || cols <= 1) {
return false; return false;
} }
// Get the left-most sign in the current row. // Get the left-most sign in the current row.
Sign first = getAdjacentSign(current, BlockFace.DOWN); Sign first = getAdjacentSign(current, BlockFace.DOWN);
@@ -163,13 +163,13 @@ public class Leaderboard
current = getAdjacentSign(current, direction); current = getAdjacentSign(current, direction);
if (current == null) return false; if (current == null) return false;
} }
// Hop down to the next row. // Hop down to the next row.
first = getAdjacentSign(first, BlockFace.DOWN); first = getAdjacentSign(first, BlockFace.DOWN);
} }
return true; return true;
} }
/** /**
* Build the leaderboards. * Build the leaderboards.
* Requires: The grid MUST be valid! * Requires: The grid MUST be valid!
@@ -179,16 +179,16 @@ public class Leaderboard
boards.clear(); boards.clear();
Sign header = this.topLeftSign; Sign header = this.topLeftSign;
Sign current; Sign current;
do do
{ {
// Strip the sign of any colors. // Strip the sign of any colors.
String name = ChatColor.stripColor(header.getLine(2)); String name = ChatColor.stripColor(header.getLine(2));
// Grab the stat to track. // Grab the stat to track.
Stats stat = Stats.getByFullName(name); Stats stat = Stats.getByFullName(name);
if (stat == null) continue; if (stat == null) continue;
// Create the list of signs // Create the list of signs
List<Sign> signs = new ArrayList<>(); List<Sign> signs = new ArrayList<>();
current = header; current = header;
@@ -197,10 +197,10 @@ public class Leaderboard
current = getAdjacentSign(current, BlockFace.DOWN); current = getAdjacentSign(current, BlockFace.DOWN);
signs.add(current); signs.add(current);
} }
// Create the column. // Create the column.
LeaderboardColumn column = null; LeaderboardColumn column = null;
// Switch on the type of stat // Switch on the type of stat
switch (stat) { switch (stat) {
case PLAYER_NAME: case PLAYER_NAME:
@@ -213,19 +213,19 @@ public class Leaderboard
column = new IntLeaderboardColumn(stat.getShortName(), header, signs); column = new IntLeaderboardColumn(stat.getShortName(), header, signs);
break; break;
} }
this.boards.add(column); this.boards.add(column);
} }
while ((header = getAdjacentSign(header, direction)) != null); while ((header = getAdjacentSign(header, direction)) != null);
} }
private void initializeStats() private void initializeStats()
{ {
stats.clear(); stats.clear();
for (ArenaPlayer ap : arena.getArenaPlayerSet()) for (ArenaPlayer ap : arena.getArenaPlayerSet())
stats.add(ap.getStats()); stats.add(ap.getStats());
} }
private int getSignCount(Sign s, BlockFace direction) private int getSignCount(Sign s, BlockFace direction)
{ {
int i = 1; int i = 1;
@@ -247,7 +247,7 @@ public class Leaderboard
return i; return i;
} }
private Sign getAdjacentSign(Sign s, BlockFace direction) private Sign getAdjacentSign(Sign s, BlockFace direction)
{ {
BlockState state = s.getBlock().getRelative(direction).getState(); BlockState state = s.getBlock().getRelative(direction).getState();
@@ -255,7 +255,7 @@ public class Leaderboard
return (Sign) state; return (Sign) state;
return null; return null;
} }
private BlockFace getRightDirection(Sign s) private BlockFace getRightDirection(Sign s)
{ {
BlockData data = s.getBlockData(); BlockData data = s.getBlockData();
@@ -270,7 +270,7 @@ public class Leaderboard
} }
return null; return null;
} }
public boolean isValid() public boolean isValid()
{ {
return isValid; return isValid;
@@ -12,7 +12,7 @@ public interface LeaderboardColumn
* of the player stat associated with this column. * of the player stat associated with this column.
*/ */
void update(List<ArenaPlayerStatistics> stats); void update(List<ArenaPlayerStatistics> stats);
/** /**
* Get the String representation of the stat in question. * Get the String representation of the stat in question.
* The line is calculated by simply calling the appropriate * The line is calculated by simply calling the appropriate
@@ -21,19 +21,19 @@ public interface LeaderboardColumn
* @return the String representation of the stat in question * @return the String representation of the stat in question
*/ */
String getLine(ArenaPlayerStatistics stats); String getLine(ArenaPlayerStatistics stats);
/** /**
* Clear the text on all the signs in the column. * Clear the text on all the signs in the column.
*/ */
void clear(); void clear();
/** /**
* Get the top sign of the column. * Get the top sign of the column.
* The top sign displays the stat name. * The top sign displays the stat name.
* @return the top sign of the column * @return the top sign of the column
*/ */
Sign getHeader(); Sign getHeader();
/** /**
* Get all signs in the column (minus the header). * Get all signs in the column (minus the header).
* @return all signs in the column (minus the header) * @return all signs in the column (minus the header)
@@ -10,29 +10,29 @@ public enum Stats
SWINGS("Swings", "swings"), SWINGS("Swings", "swings"),
HITS("Hits", "hits"), HITS("Hits", "hits"),
LAST_WAVE("Last Wave", "lastWave"); LAST_WAVE("Last Wave", "lastWave");
private String name, shortName; private String name, shortName;
Stats(String name, String shortName) { Stats(String name, String shortName) {
this.name = name; this.name = name;
this.shortName = shortName; this.shortName = shortName;
} }
public String getShortName() { public String getShortName() {
return shortName; return shortName;
} }
public String getFullName() { public String getFullName() {
return name; return name;
} }
public static Stats getByFullName(String name) { public static Stats getByFullName(String name) {
for (Stats s : Stats.values()) for (Stats s : Stats.values())
if (s.name.equals(name)) if (s.name.equals(name))
return s; return s;
return null; return null;
} }
public static Stats getByShortName(String name) { public static Stats getByShortName(String name) {
for (Stats s : Stats.values()) { for (Stats s : Stats.values()) {
if (s.shortName.equalsIgnoreCase(name)) { if (s.shortName.equalsIgnoreCase(name)) {
@@ -65,18 +65,18 @@ public class MAGlobalListener implements Listener
{ {
private MobArena plugin; private MobArena plugin;
private ArenaMaster am; private ArenaMaster am;
public MAGlobalListener(MobArena plugin, ArenaMaster am) { public MAGlobalListener(MobArena plugin, ArenaMaster am) {
this.plugin = plugin; this.plugin = plugin;
this.am = am; this.am = am;
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// // // //
// BLOCK EVENTS // // BLOCK EVENTS //
// // // //
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void blockBreak(BlockBreakEvent event) { public void blockBreak(BlockBreakEvent event) {
for (Arena arena : am.getArenas()) for (Arena arena : am.getArenas())
@@ -125,15 +125,15 @@ public class MAGlobalListener implements Listener
if (!event.getPlayer().hasPermission("mobarena.setup.leaderboards")) { if (!event.getPlayer().hasPermission("mobarena.setup.leaderboards")) {
return; return;
} }
if (!event.getLine(0).startsWith("[MA]")) { if (!event.getLine(0).startsWith("[MA]")) {
return; return;
} }
String text = event.getLine(0).substring((4)); String text = event.getLine(0).substring((4));
Arena arena; Arena arena;
Stats stat; Stats stat;
if ((arena = am.getArenaWithName(text)) != null) { if ((arena = am.getArenaWithName(text)) != null) {
arena.getEventListener().onSignChange(event); arena.getEventListener().onSignChange(event);
setSignLines(event, ChatColor.GREEN + "MobArena", ChatColor.YELLOW + arena.arenaName(), ChatColor.AQUA + "Players", "---------------"); setSignLines(event, ChatColor.GREEN + "MobArena", ChatColor.YELLOW + arena.arenaName(), ChatColor.AQUA + "Players", "---------------");
@@ -143,23 +143,23 @@ public class MAGlobalListener implements Listener
am.getGlobalMessenger().tell(event.getPlayer(), "Stat sign created."); am.getGlobalMessenger().tell(event.getPlayer(), "Stat sign created.");
} }
} }
private void setSignLines(SignChangeEvent event, String s1, String s2, String s3, String s4) { private void setSignLines(SignChangeEvent event, String s1, String s2, String s3, String s4) {
event.setLine(0, s1); event.setLine(0, s1);
event.setLine(1, s2); event.setLine(1, s2);
event.setLine(2, s3); event.setLine(2, s3);
event.setLine(3, s4); event.setLine(3, s4);
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// // // //
// ENTITY EVENTS // // ENTITY EVENTS //
// // // //
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void creatureSpawn(CreatureSpawnEvent event) { public void creatureSpawn(CreatureSpawnEvent event) {
for (Arena arena : am.getArenas()) for (Arena arena : am.getArenas())
@@ -217,7 +217,7 @@ public class MAGlobalListener implements Listener
for (Arena arena : am.getArenas()) for (Arena arena : am.getArenas())
arena.getEventListener().onEntityRegainHealth(event); arena.getEventListener().onEntityRegainHealth(event);
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void entityFoodLevelChange(FoodLevelChangeEvent event) { public void entityFoodLevelChange(FoodLevelChangeEvent event) {
for (Arena arena : am.getArenas()) for (Arena arena : am.getArenas())
@@ -229,30 +229,30 @@ public class MAGlobalListener implements Listener
for (Arena arena : am.getArenas()) for (Arena arena : am.getArenas())
arena.getEventListener().onEntityTarget(event); arena.getEventListener().onEntityTarget(event);
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void entityTeleport(EntityTeleportEvent event) { public void entityTeleport(EntityTeleportEvent event) {
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
arena.getEventListener().onEntityTeleport(event); arena.getEventListener().onEntityTeleport(event);
} }
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void potionSplash(PotionSplashEvent event) { public void potionSplash(PotionSplashEvent event) {
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
arena.getEventListener().onPotionSplash(event); arena.getEventListener().onPotionSplash(event);
} }
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// // // //
// PLAYER EVENTS // // PLAYER EVENTS //
// // // //
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void playerAnimation(PlayerAnimationEvent event) { public void playerAnimation(PlayerAnimationEvent event) {
if (!am.isEnabled()) return; if (!am.isEnabled()) return;
@@ -340,7 +340,7 @@ public class MAGlobalListener implements Listener
} }
} }
} }
public enum TeleportResponse { public enum TeleportResponse {
ALLOW, REJECT, IDGAF ALLOW, REJECT, IDGAF
} }
@@ -352,7 +352,7 @@ public class MAGlobalListener implements Listener
boolean allow = true; boolean allow = true;
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
TeleportResponse r = arena.getEventListener().onPlayerTeleport(event); TeleportResponse r = arena.getEventListener().onPlayerTeleport(event);
// If just one arena allows, uncancel and stop. // If just one arena allows, uncancel and stop.
switch (r) { switch (r) {
case ALLOW: case ALLOW:
@@ -375,7 +375,7 @@ public class MAGlobalListener implements Listener
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void playerPreLogin(PlayerLoginEvent event) { public void playerPreLogin(PlayerLoginEvent event) {
for (Arena arena : am.getArenas()) { for (Arena arena : am.getArenas()) {
@@ -396,21 +396,21 @@ public class MAGlobalListener implements Listener
arena.getEventListener().onVehicleExit(event); arena.getEventListener().onVehicleExit(event);
} }
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// // // //
// WORLD EVENTS // // WORLD EVENTS //
// // // //
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void worldLoadEvent(WorldLoadEvent event) { public void worldLoadEvent(WorldLoadEvent event) {
am.loadArenasInWorld(event.getWorld().getName()); am.loadArenasInWorld(event.getWorld().getName());
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void worldUnloadEvent(WorldUnloadEvent event) { public void worldUnloadEvent(WorldUnloadEvent event) {
am.unloadArenasInWorld(event.getWorld().getName()); am.unloadArenasInWorld(event.getWorld().getName());
@@ -32,17 +32,17 @@ public class ArenaRegion
{ {
private Arena arena; private Arena arena;
private World world; private World world;
private Location lastP1, lastP2, lastL1, lastL2; private Location lastP1, lastP2, lastL1, lastL2;
private Location p1, p2, l1, l2, arenaWarp, lobbyWarp, specWarp, exitWarp, leaderboard; private Location p1, p2, l1, l2, arenaWarp, lobbyWarp, specWarp, exitWarp, leaderboard;
private Map<String,Location> spawnpoints, containers; private Map<String,Location> spawnpoints, containers;
private boolean setup, lobbySetup; private boolean setup, lobbySetup;
private ConfigurationSection coords; private ConfigurationSection coords;
private ConfigurationSection spawns; private ConfigurationSection spawns;
private ConfigurationSection chests; private ConfigurationSection chests;
public ArenaRegion(ConfigurationSection section, Arena arena) { public ArenaRegion(ConfigurationSection section, Arena arena) {
this.arena = arena; this.arena = arena;
refreshWorld(); refreshWorld();
@@ -50,34 +50,34 @@ public class ArenaRegion
this.coords = makeSection(section, "coords"); this.coords = makeSection(section, "coords");
this.spawns = makeSection(coords, "spawnpoints"); this.spawns = makeSection(coords, "spawnpoints");
this.chests = makeSection(coords, "containers"); this.chests = makeSection(coords, "containers");
reloadAll(); reloadAll();
} }
public void refreshWorld() { public void refreshWorld() {
this.world = arena.getWorld(); this.world = arena.getWorld();
} }
public void reloadAll() { public void reloadAll() {
reloadRegion(); reloadRegion();
reloadWarps(); reloadWarps();
reloadLeaderboards(); reloadLeaderboards();
reloadSpawnpoints(); reloadSpawnpoints();
reloadChests(); reloadChests();
verifyData(); verifyData();
} }
public void reloadRegion() { public void reloadRegion() {
p1 = parseLocation(coords, "p1", world); p1 = parseLocation(coords, "p1", world);
p2 = parseLocation(coords, "p2", world); p2 = parseLocation(coords, "p2", world);
//fixRegion(); //fixRegion();
l1 = parseLocation(coords, "l1", world); l1 = parseLocation(coords, "l1", world);
l2 = parseLocation(coords, "l2", world); l2 = parseLocation(coords, "l2", world);
//fixLobbyRegion(); //fixLobbyRegion();
} }
public void reloadWarps() { public void reloadWarps() {
arenaWarp = parseLocation(coords, "arena", world); arenaWarp = parseLocation(coords, "arena", world);
lobbyWarp = parseLocation(coords, "lobby", world); lobbyWarp = parseLocation(coords, "lobby", world);
@@ -89,7 +89,7 @@ public class ArenaRegion
throw new ConfigError("Failed to parse exit warp for arena " + arena.configName() + " because: " + e.getMessage()); throw new ConfigError("Failed to parse exit warp for arena " + arena.configName() + " because: " + e.getMessage());
} }
} }
public void reloadLeaderboards() { public void reloadLeaderboards() {
// try-catch for backwards compatibility // try-catch for backwards compatibility
try { try {
@@ -101,7 +101,7 @@ public class ArenaRegion
leaderboard.setWorld(world); leaderboard.setWorld(world);
} }
} }
public void reloadSpawnpoints() { public void reloadSpawnpoints() {
spawnpoints = new HashMap<>(); spawnpoints = new HashMap<>();
Set<String> keys = spawns.getKeys(false); Set<String> keys = spawns.getKeys(false);
@@ -111,7 +111,7 @@ public class ArenaRegion
} }
} }
} }
public void reloadChests() { public void reloadChests() {
containers = new HashMap<>(); containers = new HashMap<>();
Set<String> keys = chests.getKeys(false); Set<String> keys = chests.getKeys(false);
@@ -121,7 +121,7 @@ public class ArenaRegion
} }
} }
} }
public void verifyData() { public void verifyData() {
setup = (p1 != null && setup = (p1 != null &&
p2 != null && p2 != null &&
@@ -129,15 +129,15 @@ public class ArenaRegion
lobbyWarp != null && lobbyWarp != null &&
specWarp != null && specWarp != null &&
!spawnpoints.isEmpty()); !spawnpoints.isEmpty());
lobbySetup = (l1 != null && lobbySetup = (l1 != null &&
l2 != null); l2 != null);
} }
public void checkData(MobArena plugin, CommandSender s, boolean ready, boolean region, boolean warps, boolean spawns) { public void checkData(MobArena plugin, CommandSender s, boolean ready, boolean region, boolean warps, boolean spawns) {
// Verify data first // Verify data first
verifyData(); verifyData();
// Prepare the list // Prepare the list
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
@@ -150,7 +150,7 @@ public class ArenaRegion
list.clear(); list.clear();
} }
} }
// Warps // Warps
if (warps) { if (warps) {
if (arenaWarp == null) list.add("arena"); if (arenaWarp == null) list.add("arena");
@@ -161,82 +161,82 @@ public class ArenaRegion
list.clear(); list.clear();
} }
} }
// Spawnpoints // Spawnpoints
if (spawns) { if (spawns) {
if (spawnpoints.isEmpty()) { if (spawnpoints.isEmpty()) {
arena.getGlobalMessenger().tell(s, "Missing spawnpoints"); arena.getGlobalMessenger().tell(s, "Missing spawnpoints");
} }
} }
// Ready? // Ready?
if (ready && setup) { if (ready && setup) {
arena.getGlobalMessenger().tell(s, "Arena is ready to be used!"); arena.getGlobalMessenger().tell(s, "Arena is ready to be used!");
} }
} }
public boolean isDefined() { public boolean isDefined() {
return (p1 != null && p2 != null); return (p1 != null && p2 != null);
} }
public boolean isLobbyDefined() { public boolean isLobbyDefined() {
return (l1 != null && l2 != null); return (l1 != null && l2 != null);
} }
public boolean isSetup() { public boolean isSetup() {
return setup; return setup;
} }
public boolean isLobbySetup() { public boolean isLobbySetup() {
return lobbySetup; return lobbySetup;
} }
public boolean isWarp(Location l) { public boolean isWarp(Location l) {
return (l.equals(arenaWarp) || return (l.equals(arenaWarp) ||
l.equals(lobbyWarp) || l.equals(lobbyWarp) ||
l.equals(specWarp) || l.equals(specWarp) ||
l.equals(exitWarp)); l.equals(exitWarp));
} }
public boolean contains(Location l) { public boolean contains(Location l) {
if (!l.getWorld().getName().equals(world.getName()) || !isDefined()) { if (!l.getWorld().getName().equals(world.getName()) || !isDefined()) {
return false; return false;
} }
int x = l.getBlockX(); int x = l.getBlockX();
int y = l.getBlockY(); int y = l.getBlockY();
int z = l.getBlockZ(); int z = l.getBlockZ();
// Check the lobby first. // Check the lobby first.
if (lobbySetup) { if (lobbySetup) {
if ((x >= l1.getBlockX() && x <= l2.getBlockX()) && if ((x >= l1.getBlockX() && x <= l2.getBlockX()) &&
(z >= l1.getBlockZ() && z <= l2.getBlockZ()) && (z >= l1.getBlockZ() && z <= l2.getBlockZ()) &&
(y >= l1.getBlockY() && y <= l2.getBlockY())) (y >= l1.getBlockY() && y <= l2.getBlockY()))
return true; return true;
} }
// Returns false if the location is outside of the region. // Returns false if the location is outside of the region.
return ((x >= p1.getBlockX() && x <= p2.getBlockX()) && return ((x >= p1.getBlockX() && x <= p2.getBlockX()) &&
(z >= p1.getBlockZ() && z <= p2.getBlockZ()) && (z >= p1.getBlockZ() && z <= p2.getBlockZ()) &&
(y >= p1.getBlockY() && y <= p2.getBlockY())); (y >= p1.getBlockY() && y <= p2.getBlockY()));
} }
public boolean contains(Location l, int radius) { public boolean contains(Location l, int radius) {
if (!l.getWorld().getName().equals(world.getName()) || !isDefined()) { if (!l.getWorld().getName().equals(world.getName()) || !isDefined()) {
return false; return false;
} }
int x = l.getBlockX(); int x = l.getBlockX();
int y = l.getBlockY(); int y = l.getBlockY();
int z = l.getBlockZ(); int z = l.getBlockZ();
if (lobbySetup) { if (lobbySetup) {
if ((x + radius >= l1.getBlockX() && x - radius <= l2.getBlockX()) && if ((x + radius >= l1.getBlockX() && x - radius <= l2.getBlockX()) &&
(z + radius >= l1.getBlockZ() && z - radius <= l2.getBlockZ()) && (z + radius >= l1.getBlockZ() && z - radius <= l2.getBlockZ()) &&
(y + radius >= l1.getBlockY() && y - radius <= l2.getBlockY())) (y + radius >= l1.getBlockY() && y - radius <= l2.getBlockY()))
return true; return true;
} }
return ((x + radius >= p1.getBlockX() && x - radius <= p2.getBlockX()) && return ((x + radius >= p1.getBlockX() && x - radius <= p2.getBlockX()) &&
(z + radius >= p1.getBlockZ() && z - radius <= p2.getBlockZ()) && (z + radius >= p1.getBlockZ() && z - radius <= p2.getBlockZ()) &&
(y + radius >= p1.getBlockY() && y - radius <= p2.getBlockY())); (y + radius >= p1.getBlockY() && y - radius <= p2.getBlockY()));
@@ -263,33 +263,33 @@ public class ArenaRegion
int z = p2.getBlockZ(); int z = p2.getBlockZ();
setSaveReload(coords, "p2", p2.getWorld(), x ,y ,z); setSaveReload(coords, "p2", p2.getWorld(), x ,y ,z);
} }
public void expandDown(int amount) { public void expandDown(int amount) {
int x = p1.getBlockX(); int x = p1.getBlockX();
int y = Math.max(0, p1.getBlockY() - amount); int y = Math.max(0, p1.getBlockY() - amount);
int z = p1.getBlockZ(); int z = p1.getBlockZ();
setSaveReload(coords, "p1", p1.getWorld(), x ,y ,z); setSaveReload(coords, "p1", p1.getWorld(), x ,y ,z);
} }
public void expandP1(int dx, int dz) { public void expandP1(int dx, int dz) {
int x = p1.getBlockX() - dx; int x = p1.getBlockX() - dx;
int y = p1.getBlockY(); int y = p1.getBlockY();
int z = p1.getBlockZ() - dz; int z = p1.getBlockZ() - dz;
setSaveReload(coords, "p1", p1.getWorld(), x ,y ,z); setSaveReload(coords, "p1", p1.getWorld(), x ,y ,z);
} }
public void expandP2(int dx, int dz) { public void expandP2(int dx, int dz) {
int x = p2.getBlockX() + dx; int x = p2.getBlockX() + dx;
int y = p2.getBlockY(); int y = p2.getBlockY();
int z = p2.getBlockZ() + dz; int z = p2.getBlockZ() + dz;
setSaveReload(coords, "p2", p2.getWorld(), x ,y ,z); setSaveReload(coords, "p2", p2.getWorld(), x ,y ,z);
} }
public void expandOut(int amount) { public void expandOut(int amount) {
expandP1(amount, amount); expandP1(amount, amount);
expandP2(amount, amount); expandP2(amount, amount);
} }
// Lobby expand // Lobby expand
public void expandLobbyUp(int amount) { public void expandLobbyUp(int amount) {
int x = l2.getBlockX(); int x = l2.getBlockX();
@@ -297,28 +297,28 @@ public class ArenaRegion
int z = l2.getBlockZ(); int z = l2.getBlockZ();
setSaveReload(coords, "l2", l2.getWorld(), x ,y ,z); setSaveReload(coords, "l2", l2.getWorld(), x ,y ,z);
} }
public void expandLobbyDown(int amount) { public void expandLobbyDown(int amount) {
int x = l1.getBlockX(); int x = l1.getBlockX();
int y = Math.max(0, l1.getBlockY() - amount); int y = Math.max(0, l1.getBlockY() - amount);
int z = l1.getBlockZ(); int z = l1.getBlockZ();
setSaveReload(coords, "l1", l1.getWorld(), x ,y ,z); setSaveReload(coords, "l1", l1.getWorld(), x ,y ,z);
} }
public void expandL1(int dx, int dz) { public void expandL1(int dx, int dz) {
int x = l1.getBlockX() - dx; int x = l1.getBlockX() - dx;
int y = l1.getBlockY(); int y = l1.getBlockY();
int z = l1.getBlockZ() - dz; int z = l1.getBlockZ() - dz;
setSaveReload(coords, "l1", l1.getWorld(), x ,y ,z); setSaveReload(coords, "l1", l1.getWorld(), x ,y ,z);
} }
public void expandL2(int dx, int dz) { public void expandL2(int dx, int dz) {
int x = l2.getBlockX() + dx; int x = l2.getBlockX() + dx;
int y = l2.getBlockY(); int y = l2.getBlockY();
int z = l2.getBlockZ() + dz; int z = l2.getBlockZ() + dz;
setSaveReload(coords, "l2", l2.getWorld(), x ,y ,z); setSaveReload(coords, "l2", l2.getWorld(), x ,y ,z);
} }
public void expandLobbyOut(int amount) { public void expandLobbyOut(int amount) {
expandL1(amount, amount); expandL1(amount, amount);
expandL2(amount, amount); expandL2(amount, amount);
@@ -330,19 +330,19 @@ public class ArenaRegion
save(); save();
reloadRegion(); reloadRegion();
} }
public void fixRegion() { public void fixRegion() {
fix("p1", "p2"); fix("p1", "p2");
} }
public void fixLobbyRegion() { public void fixLobbyRegion() {
fix("l1", "l2"); fix("l1", "l2");
} }
private void fix(String location1, String location2) { private void fix(String location1, String location2) {
Location loc1 = parseLocation(coords, location1, world); Location loc1 = parseLocation(coords, location1, world);
Location loc2 = parseLocation(coords, location2, world); Location loc2 = parseLocation(coords, location2, world);
if (loc1 == null || loc2 == null) { if (loc1 == null || loc2 == null) {
return; return;
} }
@@ -355,21 +355,21 @@ public class ArenaRegion
loc2.setX(tmp); loc2.setX(tmp);
modified = true; modified = true;
} }
if (loc1.getZ() > loc2.getZ()) { if (loc1.getZ() > loc2.getZ()) {
double tmp = loc1.getZ(); double tmp = loc1.getZ();
loc1.setZ(loc2.getZ()); loc1.setZ(loc2.getZ());
loc2.setZ(tmp); loc2.setZ(tmp);
modified = true; modified = true;
} }
if (loc1.getY() > loc2.getY()) { if (loc1.getY() > loc2.getY()) {
double tmp = loc1.getY(); double tmp = loc1.getY();
loc1.setY(loc2.getY()); loc1.setY(loc2.getY());
loc2.setY(tmp); loc2.setY(tmp);
modified = true; modified = true;
} }
if (!arena.getWorld().getName().equals(world.getName())) { if (!arena.getWorld().getName().equals(world.getName())) {
arena.setWorld(world); arena.setWorld(world);
modified = true; modified = true;
@@ -378,39 +378,39 @@ public class ArenaRegion
if (!modified) { if (!modified) {
return; return;
} }
setLocation(coords, location1, loc1); setLocation(coords, location1, loc1);
setLocation(coords, location2, loc2); setLocation(coords, location2, loc2);
save(); save();
} }
public List<Chunk> getChunks() { public List<Chunk> getChunks() {
List<Chunk> result = new ArrayList<>(); List<Chunk> result = new ArrayList<>();
if (p1 == null || p2 == null) { if (p1 == null || p2 == null) {
return result; return result;
} }
Chunk c1 = world.getChunkAt(p1); Chunk c1 = world.getChunkAt(p1);
Chunk c2 = world.getChunkAt(p2); Chunk c2 = world.getChunkAt(p2);
for (int i = c1.getX(); i <= c2.getX(); i++) { for (int i = c1.getX(); i <= c2.getX(); i++) {
for (int j = c1.getZ(); j <= c2.getZ(); j++) { for (int j = c1.getZ(); j <= c2.getZ(); j++) {
result.add(world.getChunkAt(i,j)); result.add(world.getChunkAt(i,j));
} }
} }
return result; return result;
} }
public Location getArenaWarp() { public Location getArenaWarp() {
return arenaWarp; return arenaWarp;
} }
public Location getLobbyWarp() { public Location getLobbyWarp() {
return lobbyWarp; return lobbyWarp;
} }
public Location getSpecWarp() { public Location getSpecWarp() {
return specWarp; return specWarp;
} }
@@ -418,27 +418,27 @@ public class ArenaRegion
public Location getExitWarp() { public Location getExitWarp() {
return exitWarp; return exitWarp;
} }
public Location getSpawnpoint(String name) { public Location getSpawnpoint(String name) {
return spawnpoints.get(name); return spawnpoints.get(name);
} }
public Collection<Location> getSpawnpoints() { public Collection<Location> getSpawnpoints() {
return spawnpoints.values(); return spawnpoints.values();
} }
public List<Location> getSpawnpointList() { public List<Location> getSpawnpointList() {
return new ArrayList<>(spawnpoints.values()); return new ArrayList<>(spawnpoints.values());
} }
public Collection<Location> getContainers() { public Collection<Location> getContainers() {
return containers.values(); return containers.values();
} }
public Location getLeaderboard() { public Location getLeaderboard() {
return leaderboard; return leaderboard;
} }
public void set(RegionPoint point, Location loc) { public void set(RegionPoint point, Location loc) {
// Act based on the point // Act based on the point
switch (point) { switch (point) {
@@ -452,10 +452,10 @@ public class ArenaRegion
case SPECTATOR: setWarp(point, loc); return; case SPECTATOR: setWarp(point, loc); return;
case LEADERBOARD: setLeaderboard(loc); return; case LEADERBOARD: setLeaderboard(loc); return;
} }
throw new IllegalArgumentException("Invalid region point!"); throw new IllegalArgumentException("Invalid region point!");
} }
private void setPoint(RegionPoint point, Location l) { private void setPoint(RegionPoint point, Location l) {
// Lower and upper locations // Lower and upper locations
RegionPoint r1, r2; RegionPoint r1, r2;
@@ -468,7 +468,7 @@ public class ArenaRegion
* location for the given point. These location references are only * location for the given point. These location references are only
* ever overwritten when using the set commands, and remain fully * ever overwritten when using the set commands, and remain fully
* decoupled from the 'fixed' points. * decoupled from the 'fixed' points.
* *
* Effectively, the config-file and region store 'fixed' locations * Effectively, the config-file and region store 'fixed' locations
* that allow fast membership tests, but the region also stores the * that allow fast membership tests, but the region also stores the
* 'unfixed' locations for a more intuitive setup process. * 'unfixed' locations for a more intuitive setup process.
@@ -502,7 +502,7 @@ public class ArenaRegion
lower = upper = null; lower = upper = null;
r1 = r2 = null; r1 = r2 = null;
} }
// Min-max if both locations are non-null // Min-max if both locations are non-null
if (lower != null && upper != null) { if (lower != null && upper != null) {
double tmp; double tmp;
@@ -522,98 +522,98 @@ public class ArenaRegion
upper.setZ(tmp); upper.setZ(tmp);
} }
} }
// Set the coords and save // Set the coords and save
if (lower != null) setLocation(coords, r1.name().toLowerCase(), lower); if (lower != null) setLocation(coords, r1.name().toLowerCase(), lower);
if (upper != null) setLocation(coords, r2.name().toLowerCase(), upper); if (upper != null) setLocation(coords, r2.name().toLowerCase(), upper);
save(); save();
// Reload regions and verify data // Reload regions and verify data
reloadRegion(); reloadRegion();
verifyData(); verifyData();
} }
public void set(String point, Location loc) { public void set(String point, Location loc) {
// Get the region point enum // Get the region point enum
RegionPoint rp = Enums.getEnumFromString(RegionPoint.class, point); RegionPoint rp = Enums.getEnumFromString(RegionPoint.class, point);
if (rp == null) throw new IllegalArgumentException("Invalid region point '" + point + "'"); if (rp == null) throw new IllegalArgumentException("Invalid region point '" + point + "'");
// Then delegate // Then delegate
set(rp, loc); set(rp, loc);
} }
public void setWarp(RegionPoint point, Location l) { public void setWarp(RegionPoint point, Location l) {
// Set the point and save // Set the point and save
setLocation(coords, point.toString(), l); setLocation(coords, point.toString(), l);
save(); save();
// Then reload warps // Then reload warps
reloadWarps(); reloadWarps();
} }
public void setLeaderboard(Location l) { public void setLeaderboard(Location l) {
// Set the point and save // Set the point and save
setLocation(coords, "leaderboard", l); setLocation(coords, "leaderboard", l);
save(); save();
// Then reload the leaderboards // Then reload the leaderboards
reloadLeaderboards(); reloadLeaderboards();
} }
public void addSpawn(String name, Location loc) { public void addSpawn(String name, Location loc) {
// Add the spawn and save // Add the spawn and save
setLocation(spawns, name, loc); setLocation(spawns, name, loc);
save(); save();
// Reload spawnpoints and verify data // Reload spawnpoints and verify data
reloadSpawnpoints(); reloadSpawnpoints();
verifyData(); verifyData();
} }
public boolean removeSpawn(String name) { public boolean removeSpawn(String name) {
// Check if the spawnpoint exists // Check if the spawnpoint exists
if (spawns.getString(name) == null) { if (spawns.getString(name) == null) {
return false; return false;
} }
// Null the spawnpoint and save // Null the spawnpoint and save
setLocation(spawns, name, null); setLocation(spawns, name, null);
save(); save();
// Reload spawnpoints and verify data // Reload spawnpoints and verify data
reloadSpawnpoints(); reloadSpawnpoints();
verifyData(); verifyData();
return true; return true;
} }
public void addChest(String name, Location loc) { public void addChest(String name, Location loc) {
// Add the chest location and save // Add the chest location and save
setLocation(chests, name, loc); setLocation(chests, name, loc);
save(); save();
// Reload the chests // Reload the chests
reloadChests(); reloadChests();
} }
public boolean removeChest(String name) { public boolean removeChest(String name) {
// Check if the chest exists // Check if the chest exists
if (chests.getString(name) == null) { if (chests.getString(name) == null) {
return false; return false;
} }
// Null the chest and save // Null the chest and save
setLocation(chests, name, null); setLocation(chests, name, null);
save(); save();
// Reload the chests // Reload the chests
reloadChests(); reloadChests();
return true; return true;
} }
public void save() { public void save() {
arena.getPlugin().saveConfig(); arena.getPlugin().saveConfig();
} }
public void showRegion(Player p) { public void showRegion(Player p) {
if (!isDefined()) { if (!isDefined()) {
return; return;
@@ -10,10 +10,10 @@ public interface Repairable
void repair(); void repair();
BlockState getState(); BlockState getState();
Material getType(); Material getType();
BlockData getData(); BlockData getData();
World getWorld(); World getWorld();
int getX(); int getX();
int getY(); int getY();
@@ -9,21 +9,21 @@ import org.bukkit.material.Attachable;
public class RepairableAttachable extends RepairableBlock public class RepairableAttachable extends RepairableBlock
{ {
private int x, y, z; private int x, y, z;
public RepairableAttachable(BlockState state) public RepairableAttachable(BlockState state)
{ {
super(state); super(state);
BlockState attached; BlockState attached;
if (state.getData() instanceof Attachable) if (state.getData() instanceof Attachable)
attached = state.getBlock().getRelative(((Attachable) state.getData()).getAttachedFace()).getState(); attached = state.getBlock().getRelative(((Attachable) state.getData()).getAttachedFace()).getState();
else else
attached = state.getBlock().getRelative(BlockFace.DOWN).getState(); attached = state.getBlock().getRelative(BlockFace.DOWN).getState();
x = attached.getX(); x = attached.getX();
y = attached.getY(); y = attached.getY();
z = attached.getZ(); z = attached.getZ();
state.getBlock().setType(Material.STONE); state.getBlock().setType(Material.STONE);
} }
@@ -32,7 +32,7 @@ public class RepairableAttachable extends RepairableBlock
Block b = getWorld().getBlockAt(x,y,z); Block b = getWorld().getBlockAt(x,y,z);
if (b.getType() == Material.AIR) if (b.getType() == Material.AIR)
b.setType(Material.STONE); b.setType(Material.STONE);
super.repair(); super.repair();
} }
} }
@@ -6,18 +6,18 @@ import org.bukkit.material.Bed;
public class RepairableBed extends RepairableBlock public class RepairableBed extends RepairableBlock
{ {
private BlockState other; private BlockState other;
public RepairableBed(BlockState state) public RepairableBed(BlockState state)
{ {
super(state); super(state);
other = state.getBlock().getRelative(((Bed) state.getData()).getFacing()).getState(); other = state.getBlock().getRelative(((Bed) state.getData()).getFacing()).getState();
} }
public void repair() public void repair()
{ {
if (getWorld().getBlockAt(getX(), getY(), getZ()).getState().getData() instanceof Bed) if (getWorld().getBlockAt(getX(), getY(), getZ()).getState().getData() instanceof Bed)
return; return;
super.repair(); super.repair();
other.getBlock().setBlockData(other.getBlockData()); other.getBlock().setBlockData(other.getBlockData());
} }
@@ -12,21 +12,21 @@ public class RepairableBlock implements Repairable
private BlockData data; private BlockData data;
private int x, y, z; private int x, y, z;
private Material type; private Material type;
public RepairableBlock(BlockState state) public RepairableBlock(BlockState state)
{ {
this.state = state; this.state = state;
world = state.getWorld(); world = state.getWorld();
x = state.getX(); x = state.getX();
y = state.getY(); y = state.getY();
z = state.getZ(); z = state.getZ();
data = state.getBlockData(); data = state.getBlockData();
type = state.getType(); type = state.getType();
} }
/** /**
* Repairs the block by setting the type and data * Repairs the block by setting the type and data
*/ */
@@ -39,32 +39,32 @@ public class RepairableBlock implements Repairable
{ {
return state; return state;
} }
public World getWorld() public World getWorld()
{ {
return world; return world;
} }
public Material getType() public Material getType()
{ {
return type; return type;
} }
public BlockData getData() public BlockData getData()
{ {
return data; return data;
} }
public int getX() public int getX()
{ {
return x; return x;
} }
public int getY() public int getY()
{ {
return y; return y;
} }
public int getZ() public int getZ()
{ {
return z; return z;
@@ -10,7 +10,7 @@ import org.bukkit.block.data.type.RedstoneWire;
import java.util.Comparator; import java.util.Comparator;
public class RepairableComparator implements Comparator<Repairable> public class RepairableComparator implements Comparator<Repairable>
{ {
public int compare(Repairable r1, Repairable r2) public int compare(Repairable r1, Repairable r2)
{ {
if (restoreLast(r1)) if (restoreLast(r1))
@@ -21,15 +21,15 @@ public class RepairableComparator implements Comparator<Repairable>
} }
else if (restoreLast(r2)) else if (restoreLast(r2))
return -1; return -1;
return 0; return 0;
} }
private boolean restoreLast(Repairable r) private boolean restoreLast(Repairable r)
{ {
Material t = r.getType(); Material t = r.getType();
BlockData data = r.getData(); BlockData data = r.getData();
return (data instanceof Attachable || data instanceof RedstoneWire || data instanceof Door || data instanceof Bed || t == Material.LAVA || t == Material.WATER || t == Material.FIRE); return (data instanceof Attachable || data instanceof RedstoneWire || data instanceof Door || data instanceof Bed || t == Material.LAVA || t == Material.WATER || t == Material.FIRE);
} }
} }
@@ -8,7 +8,7 @@ import org.bukkit.inventory.ItemStack;
public class RepairableContainer extends RepairableBlock public class RepairableContainer extends RepairableBlock
{ {
private ItemStack[] contents; private ItemStack[] contents;
public RepairableContainer(BlockState state, boolean clear) { public RepairableContainer(BlockState state, boolean clear) {
super(state); super(state);
@@ -21,21 +21,21 @@ public class RepairableContainer extends RepairableBlock
for (int i = 0; i < contents.length; i++) { for (int i = 0; i < contents.length; i++) {
contents[i] = (stacks[i] != null) ? stacks[i].clone() : null; contents[i] = (stacks[i] != null) ? stacks[i].clone() : null;
} }
// Clear the inventory if prompted // Clear the inventory if prompted
if (clear) inv.clear(); if (clear) inv.clear();
} }
public RepairableContainer(BlockState state) { public RepairableContainer(BlockState state) {
this(state, true); this(state, true);
} }
/** /**
* Repairs the container block by adding all the contents back in. * Repairs the container block by adding all the contents back in.
*/ */
public void repair() { public void repair() {
super.repair(); super.repair();
// Grab the inventory // Grab the inventory
InventoryHolder cb = (InventoryHolder) getWorld().getBlockAt(getX(),getY(),getZ()).getState(); InventoryHolder cb = (InventoryHolder) getWorld().getBlockAt(getX(),getY(),getZ()).getState();
Inventory chestInv = cb.getInventory(); Inventory chestInv = cb.getInventory();
@@ -10,18 +10,18 @@ public class RepairableDoor extends RepairableAttachable//RepairableBlock
{ {
private BlockState other; private BlockState other;
private int x, y, z; private int x, y, z;
public RepairableDoor(BlockState state) public RepairableDoor(BlockState state)
{ {
super(state); super(state);
other = state.getBlock().getRelative(BlockFace.UP).getState(); other = state.getBlock().getRelative(BlockFace.UP).getState();
BlockState attached = state.getBlock().getRelative(BlockFace.DOWN).getState(); BlockState attached = state.getBlock().getRelative(BlockFace.DOWN).getState();
x = attached.getX(); x = attached.getX();
y = attached.getY(); y = attached.getY();
z = attached.getZ(); z = attached.getZ();
} }
public void repair() public void repair()
{ {
if (getWorld().getBlockAt(getX(), getY(), getZ()).getState().getData() instanceof Door) if (getWorld().getBlockAt(getX(), getY(), getZ()).getState().getData() instanceof Door)
@@ -30,7 +30,7 @@ public class RepairableDoor extends RepairableAttachable//RepairableBlock
Block b = getWorld().getBlockAt(x,y,z); Block b = getWorld().getBlockAt(x,y,z);
if (b.getType() == Material.AIR) if (b.getType() == Material.AIR)
b.setType(Material.STONE); b.setType(Material.STONE);
super.repair(); super.repair();
other.getBlock().setBlockData(other.getBlockData()); other.getBlock().setBlockData(other.getBlockData());
} }
@@ -6,11 +6,11 @@ import org.bukkit.block.Sign;
public class RepairableSign extends RepairableAttachable public class RepairableSign extends RepairableAttachable
{ {
private String[] lines = new String[4]; private String[] lines = new String[4];
public RepairableSign(BlockState state) public RepairableSign(BlockState state)
{ {
super(state); super(state);
Sign s = (Sign) state; Sign s = (Sign) state;
lines = s.getLines(); lines = s.getLines();
} }
@@ -21,7 +21,7 @@ public class RepairableSign extends RepairableAttachable
public void repair() public void repair()
{ {
super.repair(); super.repair();
Sign s = (Sign) getWorld().getBlockAt(getX(),getY(),getZ()).getState(); Sign s = (Sign) getWorld().getBlockAt(getX(),getY(),getZ()).getState();
s.setLine(0, lines[0]); s.setLine(0, lines[0]);
s.setLine(1, lines[1]); s.setLine(1, lines[1]);
@@ -14,14 +14,14 @@ public enum Time
DUSK(13300), DUSK(13300),
NIGHT(14000), NIGHT(14000),
MIDNIGHT(18000); MIDNIGHT(18000);
private int time; private int time;
Time(int time) { Time(int time) {
this.time = time; this.time = time;
} }
public int getTime() { public int getTime() {
return time; return time;
} }
} }
@@ -26,7 +26,7 @@ public class EntityPosition implements Serializable{
this.yaw = yaw; this.yaw = yaw;
this.pitch = pitch; this.pitch = pitch;
} }
public EntityPosition(Location location) { public EntityPosition(Location location) {
this.x = location.getX(); this.x = location.getX();
this.y = location.getY(); this.y = location.getY();
@@ -35,7 +35,7 @@ public class EntityPosition implements Serializable{
this.yaw = location.getYaw(); this.yaw = location.getYaw();
this.pitch = location.getPitch(); this.pitch = location.getPitch();
} }
public Location getLocation(World world) { public Location getLocation(World world) {
return new Location(world, x, y, z, yaw, pitch); return new Location(world, x, y, z, yaw, pitch);
} }
@@ -87,4 +87,4 @@ public class EntityPosition implements Serializable{
public void setZ(double z) { public void setZ(double z) {
this.z = z; this.z = z;
} }
} }
@@ -14,7 +14,7 @@ public class Enums
} }
return null; return null;
} }
/** /**
* Get the enum value of a string, null if it doesn't exist. * Get the enum value of a string, null if it doesn't exist.
*/ */
@@ -20,20 +20,20 @@ public class ItemParser
if (s == null) { if (s == null) {
return new ArrayList<>(1); return new ArrayList<>(1);
} }
String[] items = s.split(","); String[] items = s.split(",");
List<ItemStack> result = new ArrayList<>(items.length); List<ItemStack> result = new ArrayList<>(items.length);
for (String item : items) { for (String item : items) {
ItemStack stack = parseItem(item.trim()); ItemStack stack = parseItem(item.trim());
if (stack != null) { if (stack != null) {
result.add(stack); result.add(stack);
} }
} }
return result; return result;
} }
public static ItemStack parseItem(String item) { public static ItemStack parseItem(String item) {
return parseItem(item, true); return parseItem(item, true);
} }
@@ -41,13 +41,13 @@ public class ItemParser
public static ItemStack parseItem(String item, boolean logFailure) { public static ItemStack parseItem(String item, boolean logFailure) {
if (item == null || item.equals("")) if (item == null || item.equals(""))
return null; return null;
// Check if the item has enchantments. // Check if the item has enchantments.
String[] space = item.split(" "); String[] space = item.split(" ");
String[] parts = (space.length == 2 ? space[0].split(":") : item.split(":")); String[] parts = (space.length == 2 ? space[0].split(":") : item.split(":"));
ItemStack result = null; ItemStack result = null;
switch (parts.length) { switch (parts.length) {
case 1: case 1:
result = singleItem(parts[0]); result = singleItem(parts[0]);
@@ -72,19 +72,19 @@ public class ItemParser
return result; return result;
} }
private static ItemStack singleItem(String item) { private static ItemStack singleItem(String item) {
return getType(item) return getType(item)
.map(ItemStack::new) .map(ItemStack::new)
.orElse(null); .orElse(null);
} }
private static ItemStack withAmount(String item, String amount) { private static ItemStack withAmount(String item, String amount) {
return getType(item) return getType(item)
.map(type -> new ItemStack(type, getAmount(amount))) .map(type -> new ItemStack(type, getAmount(amount)))
.orElse(null); .orElse(null);
} }
private static ItemStack withDataAndAmount(String item, String data, String amount) { private static ItemStack withDataAndAmount(String item, String data, String amount) {
ItemStack stack = withAmount(item, amount); ItemStack stack = withAmount(item, amount);
if (stack == null) { if (stack == null) {
@@ -98,7 +98,7 @@ public class ItemParser
return stack; return stack;
} }
private static ItemStack withPotionMeta(ItemStack stack, String data) { private static ItemStack withPotionMeta(ItemStack stack, String data) {
PotionType type; PotionType type;
boolean extended = false; boolean extended = false;
@@ -127,23 +127,23 @@ public class ItemParser
private static Optional<Material> getType(String item) { private static Optional<Material> getType(String item) {
return Optional.ofNullable(Material.getMaterial(item.toUpperCase())); return Optional.ofNullable(Material.getMaterial(item.toUpperCase()));
} }
private static int getAmount(String amount) { private static int getAmount(String amount) {
if (amount.matches("(-)?[1-9][0-9]*")) { if (amount.matches("(-)?[1-9][0-9]*")) {
return Integer.parseInt(amount); return Integer.parseInt(amount);
} }
return 1; return 1;
} }
private static void addEnchantments(ItemStack stack, String list) { private static void addEnchantments(ItemStack stack, String list) {
String[] parts = list.split(";"); String[] parts = list.split(";");
for (String ench : parts) { for (String ench : parts) {
addEnchantment(stack, ench.trim()); addEnchantment(stack, ench.trim());
} }
} }
private static void addEnchantment(ItemStack stack, String ench) { private static void addEnchantment(ItemStack stack, String ench) {
String[] parts = ench.split(":"); String[] parts = ench.split(":");
if (parts.length != 2) { if (parts.length != 2) {
@@ -3,7 +3,7 @@ package com.garbagemule.MobArena.util;
public class MutableInt public class MutableInt
{ {
private int value; private int value;
/** /**
* Create a new MutableInt with the given value. * Create a new MutableInt with the given value.
* @param value the initial value of the MutableInt * @param value the initial value of the MutableInt
@@ -11,14 +11,14 @@ public class MutableInt
public MutableInt(int value) { public MutableInt(int value) {
this.value = value; this.value = value;
} }
/** /**
* Create a new MutableInt with value 0. * Create a new MutableInt with value 0.
*/ */
public MutableInt() { public MutableInt() {
this(0); this(0);
} }
/** /**
* Add the given amount to the internal int value. * Add the given amount to the internal int value.
* @param amount the amount to add * @param amount the amount to add
@@ -26,7 +26,7 @@ public class MutableInt
public void add(double amount) { public void add(double amount) {
this.value += amount; this.value += amount;
} }
/** /**
* Subtract the given amount from the internal int value. * Subtract the given amount from the internal int value.
* @param amount the amount to subtract * @param amount the amount to subtract
@@ -34,7 +34,7 @@ public class MutableInt
public void sub(int amount) { public void sub(int amount) {
this.value -= amount; this.value -= amount;
} }
/** /**
* Increment the value and return it. * Increment the value and return it.
* This is essentially the same as calling add(1), followed by value(). * This is essentially the same as calling add(1), followed by value().
@@ -43,7 +43,7 @@ public class MutableInt
public int inc() { public int inc() {
return ++this.value; return ++this.value;
} }
/** /**
* Decrement the value and return it. * Decrement the value and return it.
* This is essentially the same as calling sub(1), followed by value(). * This is essentially the same as calling sub(1), followed by value().
@@ -52,7 +52,7 @@ public class MutableInt
public int dec() { public int dec() {
return --this.value; return --this.value;
} }
/** /**
* The value of the MutableInt. * The value of the MutableInt.
* @return the current value * @return the current value
@@ -60,7 +60,7 @@ public class MutableInt
public int value() { public int value() {
return value; return value;
} }
@Override @Override
public String toString() { public String toString() {
return "" + value; return "" + value;
@@ -12,11 +12,11 @@ public class PotionEffectParser
private static final int TICKS_PER_SECOND = 20; private static final int TICKS_PER_SECOND = 20;
private static final int DEFAULT_POTION_AMPLIFIER = 0; private static final int DEFAULT_POTION_AMPLIFIER = 0;
private static final int DEFAULT_POTION_DURATION = Integer.MAX_VALUE; private static final int DEFAULT_POTION_DURATION = Integer.MAX_VALUE;
public static List<PotionEffect> parsePotionEffects(String s) { public static List<PotionEffect> parsePotionEffects(String s) {
if (s == null || s.isEmpty()) if (s == null || s.isEmpty())
return null; return null;
List<PotionEffect> potions = new ArrayList<>(); List<PotionEffect> potions = new ArrayList<>();
for (String potion : s.split(",")) { for (String potion : s.split(",")) {
PotionEffect eff = parsePotionEffect(potion.trim()); PotionEffect eff = parsePotionEffect(potion.trim());
@@ -24,21 +24,21 @@ public class PotionEffectParser
potions.add(eff); potions.add(eff);
} }
} }
return potions; return potions;
} }
public static PotionEffect parsePotionEffect(String p) { public static PotionEffect parsePotionEffect(String p) {
return parsePotionEffect(p, true); return parsePotionEffect(p, true);
} }
public static PotionEffect parsePotionEffect(String p, boolean logFailure) { public static PotionEffect parsePotionEffect(String p, boolean logFailure) {
if (p == null || p.isEmpty()) if (p == null || p.isEmpty())
return null; return null;
String[] parts = p.split(":"); String[] parts = p.split(":");
PotionEffect result = null; PotionEffect result = null;
switch (parts.length) { switch (parts.length) {
case 1: case 1:
result = parseSingle(parts[0]); result = parseSingle(parts[0]);
@@ -50,67 +50,67 @@ public class PotionEffectParser
result = withAmplifierAndDuration(parts[0], parts[1], parts[2]); result = withAmplifierAndDuration(parts[0], parts[1], parts[2]);
break; break;
} }
if (result == null) { if (result == null) {
if (logFailure) { if (logFailure) {
Bukkit.getLogger().warning("[MobArena] Failed to parse potion effect: " + p); Bukkit.getLogger().warning("[MobArena] Failed to parse potion effect: " + p);
} }
return null; return null;
} }
return result; return result;
} }
private static PotionEffect parseSingle(String type) { private static PotionEffect parseSingle(String type) {
PotionEffectType effect = PotionEffectType.getByName(type); PotionEffectType effect = PotionEffectType.getByName(type);
if (effect == null) { if (effect == null) {
return null; return null;
} else { } else {
return new PotionEffect(effect, DEFAULT_POTION_DURATION, DEFAULT_POTION_AMPLIFIER); return new PotionEffect(effect, DEFAULT_POTION_DURATION, DEFAULT_POTION_AMPLIFIER);
} }
} }
private static PotionEffect withAmplifier(String type, String amplifier) { private static PotionEffect withAmplifier(String type, String amplifier) {
PotionEffectType effect = PotionEffectType.getByName(type); PotionEffectType effect = PotionEffectType.getByName(type);
int amp = getAmplification(amplifier); int amp = getAmplification(amplifier);
if (effect == null || amp == -1) { if (effect == null || amp == -1) {
return null; return null;
} else { } else {
return new PotionEffect(effect, DEFAULT_POTION_DURATION, amp); return new PotionEffect(effect, DEFAULT_POTION_DURATION, amp);
} }
} }
private static PotionEffect withAmplifierAndDuration(String type, String amplifier, String duration) { private static PotionEffect withAmplifierAndDuration(String type, String amplifier, String duration) {
PotionEffectType effect = PotionEffectType.getByName(type); PotionEffectType effect = PotionEffectType.getByName(type);
int amp = getAmplification(amplifier); int amp = getAmplification(amplifier);
int dur = getDuration(duration); int dur = getDuration(duration);
if (effect == null || dur == -1 || amp == -1) { if (effect == null || dur == -1 || amp == -1) {
return null; return null;
} else { } else {
return new PotionEffect(effect, dur * TICKS_PER_SECOND, amp); return new PotionEffect(effect, dur * TICKS_PER_SECOND, amp);
} }
} }
private static int getDuration(String duration) { private static int getDuration(String duration) {
int dur = -1; int dur = -1;
if (duration.matches("[0-9]+")) { if (duration.matches("[0-9]+")) {
dur = Integer.parseInt(duration); dur = Integer.parseInt(duration);
} }
return dur; return dur;
} }
private static int getAmplification(String amplifier) { private static int getAmplification(String amplifier) {
int amp = -1; int amp = -1;
if (amplifier.matches("[0-9]+")) { if (amplifier.matches("[0-9]+")) {
amp = Integer.parseInt(amplifier); amp = Integer.parseInt(amplifier);
} }
return amp; return amp;
} }
} }
@@ -44,7 +44,7 @@ public class TextUtils
public static String padLeft(String s, int length) { return padLeft(s, length, ' '); } public static String padLeft(String s, int length) { return padLeft(s, length, ' '); }
public static String padLeft(int s, int length) { return padLeft(Integer.toString(s), length, ' '); } public static String padLeft(int s, int length) { return padLeft(Integer.toString(s), length, ' '); }
public static String padLeft(double s, int length) { return padLeft(Double.toString(s), length, ' '); } public static String padLeft(double s, int length) { return padLeft(Double.toString(s), length, ' '); }
/** /**
* Truncate the input string to be at most the input length * Truncate the input string to be at most the input length
* @param s The string to truncate * @param s The string to truncate
@@ -58,32 +58,32 @@ public class TextUtils
return s.substring(0, length); return s.substring(0, length);
} }
public static String truncate(String s) { return truncate(s, 15); } public static String truncate(String s) { return truncate(s, 15); }
public static String camelCase(String s) { public static String camelCase(String s) {
if (s == null || s.length() < 2) if (s == null || s.length() < 2)
return null; return null;
String firstLetter = s.substring(0,1).toUpperCase(); String firstLetter = s.substring(0,1).toUpperCase();
return firstLetter + s.substring(1).toLowerCase(); return firstLetter + s.substring(1).toLowerCase();
} }
public static String playerListToString(Collection<? extends Player> list) { public static String playerListToString(Collection<? extends Player> list) {
if (list.isEmpty()) { if (list.isEmpty()) {
return Msg.MISC_NONE.toString(); return Msg.MISC_NONE.toString();
} }
StringBuffer buffy = new StringBuffer(); StringBuffer buffy = new StringBuffer();
for (Player p : list) { for (Player p : list) {
buffy.append(", " + p.getName()); buffy.append(", " + p.getName());
} }
return buffy.substring(2); return buffy.substring(2);
} }
public static String listToString(Collection<? extends Object> list) { public static String listToString(Collection<? extends Object> list) {
if (list.isEmpty()) { if (list.isEmpty()) {
return Msg.MISC_NONE.toString(); return Msg.MISC_NONE.toString();
} }
StringBuffer buffy = new StringBuffer(); StringBuffer buffy = new StringBuffer();
for (Object o : list) { for (Object o : list) {
buffy.append(", " + o.toString()); buffy.append(", " + o.toString());
@@ -17,22 +17,22 @@ public class TimeUtils
long mins = total % 3600 / 60; long mins = total % 3600 / 60;
long hours = total / 3600 % 24; long hours = total / 3600 % 24;
long days = total / 3600 / 24; long days = total / 3600 / 24;
String time = (days > 0 ? days + ":" : "") + String time = (days > 0 ? days + ":" : "") +
(hours < 10 ? "0" + hours : hours) + ":" + (hours < 10 ? "0" + hours : hours) + ":" +
(mins < 10 ? "0" + mins : mins) + ":" + (mins < 10 ? "0" + mins : mins) + ":" +
(secs < 10 ? "0" + secs : secs); (secs < 10 ? "0" + secs : secs);
return time; return time;
} }
/** /**
* Makes a new java.util.Date with the input long and toString()s it. * Makes a new java.util.Date with the input long and toString()s it.
* @param ms time in milliseconds * @param ms time in milliseconds
* @return java.util.Date toString() of the input long * @return java.util.Date toString() of the input long
*/ */
public static String toDateTime(long ms) { public static String toDateTime(long ms) {
return new Date(ms).toString(); return new Date(ms).toString();
} }
/** /**
* Adds two string-representations of time and returns the resulting time. * Adds two string-representations of time and returns the resulting time.
* @param t1 a time-string * @param t1 a time-string
@@ -42,7 +42,7 @@ public class TimeUtils
public static String addTimes(String t1, String t2) { public static String addTimes(String t1, String t2) {
String[] parts1 = t1.split(":"); String[] parts1 = t1.split(":");
String[] parts2 = t2.split(":"); String[] parts2 = t2.split(":");
long secs1 = extractSeconds(parts1); long secs1 = extractSeconds(parts1);
long secs2 = extractSeconds(parts2); long secs2 = extractSeconds(parts2);
@@ -54,12 +54,12 @@ public class TimeUtils
long days1 = extractDays(parts1); long days1 = extractDays(parts1);
long days2 = extractDays(parts2); long days2 = extractDays(parts2);
long time = (secs1 + secs2 + mins1 + mins2 + hours1 + hours2 + days1 + days2) * 1000; long time = (secs1 + secs2 + mins1 + mins2 + hours1 + hours2 + days1 + days2) * 1000;
return toTime(time); return toTime(time);
} }
private static long extractSeconds(String[] parts) { private static long extractSeconds(String[] parts) {
int length = parts.length; int length = parts.length;
if (length < 1) { if (length < 1) {
@@ -67,7 +67,7 @@ public class TimeUtils
} }
return Long.parseLong(parts[length - 1]); return Long.parseLong(parts[length - 1]);
} }
private static long extractMinutes(String[] parts) { private static long extractMinutes(String[] parts) {
int length = parts.length; int length = parts.length;
if (length < 2) { if (length < 2) {
@@ -75,7 +75,7 @@ public class TimeUtils
} }
return Long.parseLong(parts[length - 2]) * 60; return Long.parseLong(parts[length - 2]) * 60;
} }
private static long extractHours(String[] parts) { private static long extractHours(String[] parts) {
int length = parts.length; int length = parts.length;
if (length < 3) { if (length < 3) {
@@ -83,7 +83,7 @@ public class TimeUtils
} }
return Long.parseLong(parts[length - 3]) * 3600; return Long.parseLong(parts[length - 3]) * 3600;
} }
private static long extractDays(String[] parts) { private static long extractDays(String[] parts) {
int length = parts.length; int length = parts.length;
if (length < 4) { if (length < 4) {
@@ -17,15 +17,15 @@ import java.util.logging.Level;
public class InventoryManager public class InventoryManager
{ {
private Map<Player, ItemStack[]> inventories; private Map<Player, ItemStack[]> inventories;
public InventoryManager() { public InventoryManager() {
this.inventories = new HashMap<>(); this.inventories = new HashMap<>();
} }
public void put(Player p, ItemStack[] contents) { public void put(Player p, ItemStack[] contents) {
inventories.put(p, contents); inventories.put(p, contents);
} }
public void equip(Player p) { public void equip(Player p) {
ItemStack[] contents = inventories.get(p); ItemStack[] contents = inventories.get(p);
if (contents == null) { if (contents == null) {
@@ -37,7 +37,7 @@ public class InventoryManager
public void remove(Player p) { public void remove(Player p) {
inventories.remove(p); inventories.remove(p);
} }
/** /**
* Clear a player's inventory completely. * Clear a player's inventory completely.
* @param p a player * @param p a player
@@ -59,11 +59,11 @@ public class InventoryManager
} }
} }
} }
public static boolean hasEmptyInventory(Player p) { public static boolean hasEmptyInventory(Player p) {
ItemStack[] inventory = p.getInventory().getContents(); ItemStack[] inventory = p.getInventory().getContents();
ItemStack[] armor = p.getInventory().getArmorContents(); ItemStack[] armor = p.getInventory().getArmorContents();
// Check for null or id 0, or AIR // Check for null or id 0, or AIR
for (ItemStack stack : inventory) { for (ItemStack stack : inventory) {
if (stack != null && stack.getType() != Material.AIR) if (stack != null && stack.getType() != Material.AIR)
@@ -74,10 +74,10 @@ public class InventoryManager
if (stack != null && stack.getType() != Material.AIR) if (stack != null && stack.getType() != Material.AIR)
return false; return false;
} }
return true; return true;
} }
public static boolean restoreFromFile(MobArena plugin, Player p) { public static boolean restoreFromFile(MobArena plugin, Player p) {
try { try {
File inventories = new File(plugin.getDataFolder(), "inventories"); File inventories = new File(plugin.getDataFolder(), "inventories");
@@ -89,10 +89,10 @@ public class InventoryManager
YamlConfiguration config = new YamlConfiguration(); YamlConfiguration config = new YamlConfiguration();
config.load(file); config.load(file);
ItemStack[] contents = config.getList("contents").toArray(new ItemStack[0]); ItemStack[] contents = config.getList("contents").toArray(new ItemStack[0]);
p.getInventory().setContents(contents); p.getInventory().setContents(contents);
file.delete(); file.delete();
return true; return true;
} catch (Exception e) { } catch (Exception e) {
@@ -13,17 +13,17 @@ import java.util.Map;
public abstract class AbstractWave implements Wave public abstract class AbstractWave implements Wave
{ {
private String name; private String name;
private WaveBranch branch; // recurrent, single private WaveBranch branch; // recurrent, single
private WaveType type; // default, special, swarm, boss private WaveType type; // default, special, swarm, boss
private double healthMultiplier, amountMultiplier; private double healthMultiplier, amountMultiplier;
private int firstWave, frequency, priority; private int firstWave, frequency, priority;
private List<Location> spawnpoints; private List<Location> spawnpoints;
private List<PotionEffect> effects; private List<PotionEffect> effects;
public AbstractWave() { public AbstractWave() {
this.effects = new ArrayList<>(); this.effects = new ArrayList<>();
} }
@@ -39,12 +39,12 @@ public abstract class AbstractWave implements Wave
protected List<Location> getSpawnpoints() { protected List<Location> getSpawnpoints() {
return spawnpoints; return spawnpoints;
} }
@Override @Override
public void setSpawnpoints(List<Location> spawnpoints) { public void setSpawnpoints(List<Location> spawnpoints) {
this.spawnpoints = spawnpoints; this.spawnpoints = spawnpoints;
} }
@Override @Override
public List<PotionEffect> getEffects() { public List<PotionEffect> getEffects() {
return effects; return effects;
@@ -64,7 +64,7 @@ public abstract class AbstractWave implements Wave
public String getName() { public String getName() {
return name; return name;
} }
@Override @Override
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
@@ -84,7 +84,7 @@ public abstract class AbstractWave implements Wave
public WaveType getType() { public WaveType getType() {
return type; return type;
} }
@Override @Override
public void setType(WaveType type) { public void setType(WaveType type) {
this.type = type; this.type = type;
@@ -124,7 +124,7 @@ public abstract class AbstractWave implements Wave
public double getHealthMultiplier() { public double getHealthMultiplier() {
return healthMultiplier; return healthMultiplier;
} }
@Override @Override
public void setHealthMultiplier(double healthMultiplier) { public void setHealthMultiplier(double healthMultiplier) {
this.healthMultiplier = healthMultiplier; this.healthMultiplier = healthMultiplier;
@@ -134,7 +134,7 @@ public abstract class AbstractWave implements Wave
public double getAmountMultiplier() { public double getAmountMultiplier() {
return amountMultiplier; return amountMultiplier;
} }
@Override @Override
public void setAmountMultiplier(double amountMultiplier) { public void setAmountMultiplier(double amountMultiplier) {
this.amountMultiplier = amountMultiplier; this.amountMultiplier = amountMultiplier;
@@ -13,26 +13,26 @@ public class BossAbilityThread implements Runnable
private List<Ability> abilities; private List<Ability> abilities;
private Arena arena; private Arena arena;
private int counter; private int counter;
public BossAbilityThread(BossWave wave, List<Ability> abilities, Arena arena) { public BossAbilityThread(BossWave wave, List<Ability> abilities, Arena arena) {
this.wave = wave; this.wave = wave;
this.abilities = abilities; this.abilities = abilities;
this.arena = arena; this.arena = arena;
this.counter = 0; this.counter = 0;
} }
@Override @Override
public void run() { public void run() {
// If we have no abilities, we can't execute any, so just quit. // If we have no abilities, we can't execute any, so just quit.
if (abilities.isEmpty()) { if (abilities.isEmpty()) {
return; return;
} }
// If the arena isn't running or has no players, quit. // If the arena isn't running or has no players, quit.
if (!arena.isRunning() || arena.getPlayersInArena().isEmpty()) { if (!arena.isRunning() || arena.getPlayersInArena().isEmpty()) {
return; return;
} }
// If all bosses are dead, quit. // If all bosses are dead, quit.
Set<MABoss> bosses = wave.getMABosses(); Set<MABoss> bosses = wave.getMABosses();
if (bosses.isEmpty()) { if (bosses.isEmpty()) {
@@ -41,16 +41,16 @@ public class BossAbilityThread implements Runnable
for (MABoss boss : bosses) { for (MABoss boss : bosses) {
if (boss.isDead()) return; if (boss.isDead()) return;
} }
// Get the next ability in the list. // Get the next ability in the list.
Ability ability = abilities.get(counter++ % abilities.size()); Ability ability = abilities.get(counter++ % abilities.size());
// And make each boss in this boss wave use it! // And make each boss in this boss wave use it!
for (MABoss boss : bosses) { for (MABoss boss : bosses) {
wave.announceAbility(ability, boss, arena); wave.announceAbility(ability, boss, arena);
ability.execute(arena, boss); ability.execute(arena, boss);
} }
// Schedule for another run! // Schedule for another run!
arena.scheduleTask(this, wave.getAbilityInterval()); arena.scheduleTask(this, wave.getAbilityInterval());
} }
@@ -16,7 +16,7 @@ public class MABoss
private Thing reward; private Thing reward;
private List<ItemStack> drops; private List<ItemStack> drops;
private HealthBar healthbar; private HealthBar healthbar;
/** /**
* Create an MABoss from the given entity with the given max health. * Create an MABoss from the given entity with the given max health.
* @param entity an entity * @param entity an entity
@@ -34,7 +34,7 @@ public class MABoss
this.entity = entity; this.entity = entity;
this.dead = false; this.dead = false;
} }
/** /**
* Get the LivingEntity associated with this MABoss * Get the LivingEntity associated with this MABoss
* @return a LivingEntity * @return a LivingEntity
@@ -42,7 +42,7 @@ public class MABoss
public LivingEntity getEntity() { public LivingEntity getEntity() {
return entity; return entity;
} }
/** /**
* Get the current health of this MABoss * Get the current health of this MABoss
* @return the current health of the boss * @return the current health of the boss
@@ -50,7 +50,7 @@ public class MABoss
public double getHealth() { public double getHealth() {
return entity.getHealth(); return entity.getHealth();
} }
/** /**
* Get the maximum health of this MABoss * Get the maximum health of this MABoss
* @return the maximum health of the boss * @return the maximum health of the boss
@@ -58,7 +58,7 @@ public class MABoss
public double getMaxHealth() { public double getMaxHealth() {
return entity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); return entity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue();
} }
/** /**
* Check if the boss is dead. * Check if the boss is dead.
* A boss is dead if it has been damaged such that its health is below 0. * A boss is dead if it has been damaged such that its health is below 0.
@@ -67,7 +67,7 @@ public class MABoss
public boolean isDead() { public boolean isDead() {
return dead; return dead;
} }
/** /**
* Set the death status of a boss. * Set the death status of a boss.
* This is used by the ArenaListener to force kill bosses that die due to * This is used by the ArenaListener to force kill bosses that die due to
@@ -78,7 +78,7 @@ public class MABoss
this.dead = dead; this.dead = dead;
healthbar.removeAll(); healthbar.removeAll();
} }
public void setReward(Thing reward) { public void setReward(Thing reward) {
this.reward = reward; this.reward = reward;
} }
@@ -101,7 +101,7 @@ public class MACreature
public MACreature(String name, EntityType type) { public MACreature(String name, EntityType type) {
this(name, name + "s", type); this(name, name + "s", type);
} }
private MACreature(EntityType type) { private MACreature(EntityType type) {
this( this(
type.name().toLowerCase().replaceAll("[-_\\.]", ""), type.name().toLowerCase().replaceAll("[-_\\.]", ""),
@@ -122,11 +122,11 @@ public class MACreature
public EntityType getType() { public EntityType getType() {
return type; return type;
} }
public static MACreature fromString(String string) { public static MACreature fromString(String string) {
return map.get(string.toLowerCase().replaceAll("[-_\\.]", "")); return map.get(string.toLowerCase().replaceAll("[-_\\.]", ""));
} }
public LivingEntity spawn(Arena arena, World world, Location loc) { public LivingEntity spawn(Arena arena, World world, Location loc) {
LivingEntity e = (LivingEntity) world.spawnEntity(loc, type); LivingEntity e = (LivingEntity) world.spawnEntity(loc, type);
e.getEquipment().clear(); e.getEquipment().clear();
@@ -191,12 +191,12 @@ public class MACreature
default: default:
break; break;
} }
if (e instanceof Creature) { if (e instanceof Creature) {
Creature c = (Creature) e; Creature c = (Creature) e;
c.setTarget(WaveUtils.getClosestPlayer(arena, e)); c.setTarget(WaveUtils.getClosestPlayer(arena, e));
} }
return e; return e;
} }
} }
@@ -16,11 +16,11 @@ public class SheepBouncer implements Runnable
private Arena arena; private Arena arena;
private BukkitTask task; private BukkitTask task;
public SheepBouncer(Arena arena) { public SheepBouncer(Arena arena) {
this.arena = arena; this.arena = arena;
} }
public void start() { public void start() {
if (task != null) { if (task != null) {
arena.getPlugin().getLogger().warning("Starting sheep bouncer in arena " + arena.configName() + " with existing bouncer still running. This should never happen."); arena.getPlugin().getLogger().warning("Starting sheep bouncer in arena " + arena.configName() + " with existing bouncer still running. This should never happen.");
@@ -48,44 +48,44 @@ public class SheepBouncer implements Runnable
if (!arena.isRunning() || arena.getPlayersInArena().isEmpty()) { if (!arena.isRunning() || arena.getPlayersInArena().isEmpty()) {
return; return;
} }
// Put all the sheep in a new collection for iteration purposes. // Put all the sheep in a new collection for iteration purposes.
Set<LivingEntity> sheep = new HashSet<>(arena.getMonsterManager().getExplodingSheep()); Set<LivingEntity> sheep = new HashSet<>(arena.getMonsterManager().getExplodingSheep());
// If there are no sheep, reschedule and return. // If there are no sheep, reschedule and return.
if (sheep.isEmpty()) { if (sheep.isEmpty()) {
arena.scheduleTask(this, BOUNCE_INTERVAL); arena.scheduleTask(this, BOUNCE_INTERVAL);
return; return;
} }
for (LivingEntity e : sheep) { for (LivingEntity e : sheep) {
// If an entity is null just ignore it. // If an entity is null just ignore it.
if (e == null) { if (e == null) {
continue; continue;
} }
// If the sheep is dead, remove it. // If the sheep is dead, remove it.
if (e.isDead()) { if (e.isDead()) {
arena.getMonsterManager().removeMonster(e); arena.getMonsterManager().removeMonster(e);
arena.getMonsterManager().removeExplodingSheep(e); arena.getMonsterManager().removeExplodingSheep(e);
continue; continue;
} }
// Create an explosion if there's a player amongst the nearby entities. // Create an explosion if there's a player amongst the nearby entities.
for (Entity entity : e.getNearbyEntities(2D, 2D, 2D)) { for (Entity entity : e.getNearbyEntities(2D, 2D, 2D)) {
if (entity instanceof Player) { if (entity instanceof Player) {
e.getWorld().createExplosion(e.getLocation(), 2f); e.getWorld().createExplosion(e.getLocation(), 2f);
e.remove(); e.remove();
break; break;
} }
} }
// Otherwise, if it's not already bouncing, BOUNCE! // Otherwise, if it's not already bouncing, BOUNCE!
if (Math.abs(e.getVelocity().getY()) < 1) if (Math.abs(e.getVelocity().getY()) < 1)
e.setVelocity(e.getVelocity().setY(0.5)); e.setVelocity(e.getVelocity().setY(0.5));
} }
// Reschedule for more bouncy madness! // Reschedule for more bouncy madness!
task = Bukkit.getScheduler().runTaskLater(arena.getPlugin(), this, BOUNCE_INTERVAL); task = Bukkit.getScheduler().runTaskLater(arena.getPlugin(), this, BOUNCE_INTERVAL);
} }
@@ -21,7 +21,7 @@ public interface Wave
* @return a collection of MACreatures and how many of each to spawn * @return a collection of MACreatures and how many of each to spawn
*/ */
Map<MACreature,Integer> getMonstersToSpawn(int wave, int playerCount, Arena arena); Map<MACreature,Integer> getMonstersToSpawn(int wave, int playerCount, Arena arena);
/** /**
* Get a list of spawnpoints upon which the monsters of this * Get a list of spawnpoints upon which the monsters of this
* wave may be spawned. Note that it is expected that the * wave may be spawned. Note that it is expected that the
@@ -32,7 +32,7 @@ public interface Wave
* @return a list of valid spawnpoints * @return a list of valid spawnpoints
*/ */
List<Location> getSpawnpoints(Arena arena); List<Location> getSpawnpoints(Arena arena);
/** /**
* Set the list of spawnpoints on which the monsters of this * Set the list of spawnpoints on which the monsters of this
* wave may be spawned. If the value is null, all spawnpoints * wave may be spawned. If the value is null, all spawnpoints
@@ -40,7 +40,7 @@ public interface Wave
* @param spawnpoints a list of spawnpoints * @param spawnpoints a list of spawnpoints
*/ */
void setSpawnpoints(List<Location> spawnpoints); void setSpawnpoints(List<Location> spawnpoints);
/** /**
* Get a list of potion effects that the monsters of this wave * Get a list of potion effects that the monsters of this wave
* will be given when they spawn. * will be given when they spawn.
@@ -63,7 +63,7 @@ public interface Wave
* @param wave a wave number * @param wave a wave number
*/ */
void announce(Arena arena, int wave); void announce(Arena arena, int wave);
/** /**
* Get the wave's name. * Get the wave's name.
* @return The name * @return The name
@@ -87,7 +87,7 @@ public interface Wave
* @param branch recurrent or single * @param branch recurrent or single
*/ */
void setBranch(WaveBranch branch); void setBranch(WaveBranch branch);
/** /**
* Get the type of wave. * Get the type of wave.
* @return a WaveType * @return a WaveType
@@ -99,7 +99,7 @@ public interface Wave
* @param type a WaveType * @param type a WaveType
*/ */
void setType(WaveType type); void setType(WaveType type);
/** /**
* Get the first wave this Wave instance may spawn on. * Get the first wave this Wave instance may spawn on.
* @return a wave number * @return a wave number
@@ -111,55 +111,55 @@ public interface Wave
* @param firstWave a wave number * @param firstWave a wave number
*/ */
void setFirstWave(int firstWave); void setFirstWave(int firstWave);
/** /**
* Get the wave's frequency, i.e. wave number "modulo" * Get the wave's frequency, i.e. wave number "modulo"
* @return a frequency * @return a frequency
*/ */
int getFrequency(); int getFrequency();
/** /**
* Set the wave's frequency * Set the wave's frequency
* @param frequency a frequency * @param frequency a frequency
*/ */
void setFrequency(int frequency); void setFrequency(int frequency);
/** /**
* Get the wave's priority value. * Get the wave's priority value.
* @return a priority * @return a priority
*/ */
int getPriority(); int getPriority();
/** /**
* Set the wave's priority. * Set the wave's priority.
* @param priority a priority * @param priority a priority
*/ */
void setPriority(int priority); void setPriority(int priority);
/** /**
* Get the wave's health multiplier. * Get the wave's health multiplier.
* @return The health multiplier * @return The health multiplier
*/ */
double getHealthMultiplier(); double getHealthMultiplier();
/** /**
* Get the wave's health multiplier. * Get the wave's health multiplier.
* @param healthMultiplier a double in the range ]0;1] * @param healthMultiplier a double in the range ]0;1]
*/ */
void setHealthMultiplier(double healthMultiplier); void setHealthMultiplier(double healthMultiplier);
/** /**
* Get the wave's amount multiplier. * Get the wave's amount multiplier.
* @return The amount multiplier * @return The amount multiplier
*/ */
double getAmountMultiplier(); double getAmountMultiplier();
/** /**
* Set the wave's amount multiplier. * Set the wave's amount multiplier.
* @param amountMultiplier a positive double * @param amountMultiplier a positive double
*/ */
void setAmountMultiplier(double amountMultiplier); void setAmountMultiplier(double amountMultiplier);
/** /**
* Check if this wave matches the wave number. * Check if this wave matches the wave number.
* The SingleWave class does a simple check if its wave == the parameter. * The SingleWave class does a simple check if its wave == the parameter.
@@ -179,4 +179,4 @@ public interface Wave
* @return a copy of the wave * @return a copy of the wave
*/ */
Wave copy(); Wave copy();
} }
@@ -14,38 +14,38 @@ public class WaveManager
private Wave defaultWave, currentWave; private Wave defaultWave, currentWave;
private TreeSet<Wave> recurrentWaves, singleWaves, singleWavesInstance; private TreeSet<Wave> recurrentWaves, singleWaves, singleWavesInstance;
private int wave, finalWave; private int wave, finalWave;
public WaveManager(Arena arena, ConfigurationSection section) { public WaveManager(Arena arena, ConfigurationSection section) {
this.arena = arena; this.arena = arena;
this.section = section; this.section = section;
this.wave = 0; this.wave = 0;
this.finalWave = 0; this.finalWave = 0;
reloadWaves(); reloadWaves();
} }
public TreeSet<Wave> getRecurrentWaves() { public TreeSet<Wave> getRecurrentWaves() {
return recurrentWaves; return recurrentWaves;
} }
public void reset() { public void reset() {
reloadWaves(); reloadWaves();
wave = 0; wave = 0;
singleWavesInstance = new TreeSet<>(singleWaves); singleWavesInstance = new TreeSet<>(singleWaves);
} }
public void reloadWaves() { public void reloadWaves() {
ConfigurationSection rConfig = section.getConfigurationSection("recurrent"); ConfigurationSection rConfig = section.getConfigurationSection("recurrent");
ConfigurationSection sConfig = section.getConfigurationSection("single"); ConfigurationSection sConfig = section.getConfigurationSection("single");
recurrentWaves = WaveParser.parseWaves(arena, rConfig, WaveBranch.RECURRENT); recurrentWaves = WaveParser.parseWaves(arena, rConfig, WaveBranch.RECURRENT);
singleWaves = WaveParser.parseWaves(arena, sConfig, WaveBranch.SINGLE); singleWaves = WaveParser.parseWaves(arena, sConfig, WaveBranch.SINGLE);
// getParent() => go back to the arena-node to access settings // getParent() => go back to the arena-node to access settings
finalWave = section.getParent().getInt("settings.final-wave", 0); finalWave = section.getParent().getInt("settings.final-wave", 0);
if (recurrentWaves.isEmpty()) { if (recurrentWaves.isEmpty()) {
if (singleWaves.isEmpty()) { if (singleWaves.isEmpty()) {
arena.getPlugin().getLogger().warning("Found no waves for arena " + arena.configName() + ", using default wave."); arena.getPlugin().getLogger().warning("Found no waves for arena " + arena.configName() + ", using default wave.");
@@ -60,15 +60,15 @@ public class WaveManager
defaultWave = recurrentWaves.first(); defaultWave = recurrentWaves.first();
} }
} }
/** /**
* Increment the wave number and get the next Wave to be spawned. * Increment the wave number and get the next Wave to be spawned.
* Note that this method is a mutator. * Note that this method is a mutator.
* @return the next Wave * @return the next Wave
*/ */
public Wave next() { public Wave next() {
wave++; wave++;
if (!singleWavesInstance.isEmpty() && singleWavesInstance.first().matches(wave)) { if (!singleWavesInstance.isEmpty() && singleWavesInstance.first().matches(wave)) {
currentWave = singleWavesInstance.pollFirst().copy(); currentWave = singleWavesInstance.pollFirst().copy();
} }
@@ -76,10 +76,10 @@ public class WaveManager
SortedSet<Wave> matches = getMatchingRecurrentWaves(wave); SortedSet<Wave> matches = getMatchingRecurrentWaves(wave);
currentWave = (matches.isEmpty() ? defaultWave : matches.last()).copy(); currentWave = (matches.isEmpty() ? defaultWave : matches.last()).copy();
} }
return currentWave; return currentWave;
} }
/** /**
* Get the next Wave to be spawned. This is an accessor and does not * Get the next Wave to be spawned. This is an accessor and does not
* advance the "counter". Note that the Wave objects, however, are * advance the "counter". Note that the Wave objects, however, are
@@ -88,15 +88,15 @@ public class WaveManager
*/ */
public Wave getNext() { public Wave getNext() {
int next = wave + 1; int next = wave + 1;
if (!singleWavesInstance.isEmpty() && singleWavesInstance.first().matches(next)) { if (!singleWavesInstance.isEmpty() && singleWavesInstance.first().matches(next)) {
return singleWavesInstance.first(); return singleWavesInstance.first();
} }
SortedSet<Wave> matches = getMatchingRecurrentWaves(wave); SortedSet<Wave> matches = getMatchingRecurrentWaves(wave);
return (matches.isEmpty() ? defaultWave : matches.last()); return (matches.isEmpty() ? defaultWave : matches.last());
} }
/** /**
* Get the current wave that's being used. * Get the current wave that's being used.
* Note that the current wave might not have spawned yet. * Note that the current wave might not have spawned yet.
@@ -105,7 +105,7 @@ public class WaveManager
public Wave getCurrent() { public Wave getCurrent() {
return currentWave; return currentWave;
} }
/** /**
* Get the current wave number. * Get the current wave number.
* @return the current wave number * @return the current wave number
@@ -113,7 +113,7 @@ public class WaveManager
public int getWaveNumber() { public int getWaveNumber() {
return wave; return wave;
} }
/** /**
* Get the final wave number. * Get the final wave number.
* @return the final wave number * @return the final wave number
@@ -121,7 +121,7 @@ public class WaveManager
public int getFinalWave() { public int getFinalWave() {
return finalWave; return finalWave;
} }
private SortedSet<Wave> getMatchingRecurrentWaves(int wave) { private SortedSet<Wave> getMatchingRecurrentWaves(int wave) {
TreeSet<Wave> result = new TreeSet<>(WaveUtils.getRecurrentComparator()); TreeSet<Wave> result = new TreeSet<>(WaveUtils.getRecurrentComparator());
for (Wave w : recurrentWaves) { for (Wave w : recurrentWaves) {
@@ -44,40 +44,40 @@ public class WaveParser
public static TreeSet<Wave> parseWaves(Arena arena, ConfigurationSection config, WaveBranch branch) { public static TreeSet<Wave> parseWaves(Arena arena, ConfigurationSection config, WaveBranch branch) {
// Create a TreeSet with the Comparator for the specific branch. // Create a TreeSet with the Comparator for the specific branch.
TreeSet<Wave> result = new TreeSet<>(WaveUtils.getComparator(branch)); TreeSet<Wave> result = new TreeSet<>(WaveUtils.getComparator(branch));
// If the config is null, return the empty set. // If the config is null, return the empty set.
if (config == null) { if (config == null) {
return result; return result;
} }
// If no waves were found, return the empty set. // If no waves were found, return the empty set.
Set<String> waves = config.getKeys(false); Set<String> waves = config.getKeys(false);
if (waves == null) { if (waves == null) {
return result; return result;
} }
// Otherwise, parse each wave in the branch. // Otherwise, parse each wave in the branch.
for (String wave : waves) { for (String wave : waves) {
ConfigurationSection waveSection = config.getConfigurationSection(wave); ConfigurationSection waveSection = config.getConfigurationSection(wave);
Wave w = parseWave(arena, wave, waveSection, branch); Wave w = parseWave(arena, wave, waveSection, branch);
result.add(w); result.add(w);
} }
return result; return result;
} }
public static Wave parseWave(Arena arena, String name, ConfigurationSection config, WaveBranch branch) { public static Wave parseWave(Arena arena, String name, ConfigurationSection config, WaveBranch branch) {
// Grab the WaveType and verify that it isn't null. // Grab the WaveType and verify that it isn't null.
String t = config.getString("type", null); String t = config.getString("type", null);
WaveType type = WaveType.fromString(t); WaveType type = WaveType.fromString(t);
if (type == null) { if (type == null) {
throw new ConfigError("Invalid wave type for wave " + name + " of arena " + arena.configName() + ": " + t); throw new ConfigError("Invalid wave type for wave " + name + " of arena " + arena.configName() + ": " + t);
} }
// Prepare the result // Prepare the result
Wave result = null; Wave result = null;
// Switch on the type of wave. // Switch on the type of wave.
switch (type) { switch (type) {
case DEFAULT: case DEFAULT:
@@ -99,26 +99,26 @@ public class WaveParser
result = parseBossWave(arena, name, config); result = parseBossWave(arena, name, config);
break; break;
} }
// Grab the branch-specific nodes. // Grab the branch-specific nodes.
int priority = config.getInt("priority", -1); int priority = config.getInt("priority", -1);
int frequency = config.getInt("frequency", -1); int frequency = config.getInt("frequency", -1);
int firstWave = config.getInt("wave", frequency); int firstWave = config.getInt("wave", frequency);
// Get multipliers // Get multipliers
double healthMultiplier = config.getDouble("health-multiplier", -1D); double healthMultiplier = config.getDouble("health-multiplier", -1D);
if (healthMultiplier == -1D) { if (healthMultiplier == -1D) {
healthMultiplier = config.getInt("health-multiplier", 1); healthMultiplier = config.getInt("health-multiplier", 1);
} }
double amountMultiplier = config.getDouble("amount-multiplier", -1D); double amountMultiplier = config.getDouble("amount-multiplier", -1D);
if (amountMultiplier == -1D) { if (amountMultiplier == -1D) {
amountMultiplier = config.getInt("amount-multiplier", 1); amountMultiplier = config.getInt("amount-multiplier", 1);
} }
// Grab the specific spawnpoints if any // Grab the specific spawnpoints if any
List<Location> spawnpoints = getSpawnpoints(arena, name, config); List<Location> spawnpoints = getSpawnpoints(arena, name, config);
// Potion effects // Potion effects
List<PotionEffect> effects = getPotionEffects(arena, name, config); List<PotionEffect> effects = getPotionEffects(arena, name, config);
@@ -133,31 +133,31 @@ public class WaveParser
} else if (branch == WaveBranch.SINGLE && firstWave <= 0) { } else if (branch == WaveBranch.SINGLE && firstWave <= 0) {
throw new ConfigError("Missing or invalid 'wave' node for single wave " + name + " of arena " + arena.configName()); throw new ConfigError("Missing or invalid 'wave' node for single wave " + name + " of arena " + arena.configName());
} }
// Set the important required values. // Set the important required values.
result.setName(name); result.setName(name);
result.setBranch(branch); result.setBranch(branch);
result.setFirstWave(firstWave); result.setFirstWave(firstWave);
result.setPriority(priority); result.setPriority(priority);
result.setFrequency(frequency); result.setFrequency(frequency);
// And the multipliers. // And the multipliers.
result.setHealthMultiplier(healthMultiplier); result.setHealthMultiplier(healthMultiplier);
result.setAmountMultiplier(amountMultiplier); result.setAmountMultiplier(amountMultiplier);
// Aaand the spawnpoints // Aaand the spawnpoints
result.setSpawnpoints(spawnpoints); result.setSpawnpoints(spawnpoints);
// Potions // Potions
result.setEffects(effects); result.setEffects(effects);
return result; return result;
} }
private static Wave parseDefaultWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseDefaultWave(Arena arena, String name, ConfigurationSection config) {
// Grab the monster map. // Grab the monster map.
SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config); SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config);
// Create the wave. // Create the wave.
DefaultWave result = new DefaultWave(monsters); DefaultWave result = new DefaultWave(monsters);
@@ -167,7 +167,7 @@ public class WaveParser
result.setFixed(true); result.setFixed(true);
return result; return result;
} }
// Grab the WaveGrowth // Grab the WaveGrowth
String grw = config.getString("growth", null); String grw = config.getString("growth", null);
if (grw != null && !grw.isEmpty()) { if (grw != null && !grw.isEmpty()) {
@@ -180,21 +180,21 @@ public class WaveParser
} else { } else {
result.setGrowth(WaveGrowth.MEDIUM); result.setGrowth(WaveGrowth.MEDIUM);
} }
return result; return result;
} }
private static Wave parseSpecialWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseSpecialWave(Arena arena, String name, ConfigurationSection config) {
SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config); SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config);
return new SpecialWave(monsters); return new SpecialWave(monsters);
} }
private static Wave parseSwarmWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseSwarmWave(Arena arena, String name, ConfigurationSection config) {
MACreature monster = getSingleMonster(arena, name, config); MACreature monster = getSingleMonster(arena, name, config);
SwarmWave result = new SwarmWave(monster); SwarmWave result = new SwarmWave(monster);
// Grab SwarmAmount // Grab SwarmAmount
String amnt = config.getString("amount", null); String amnt = config.getString("amount", null);
if (amnt != null && !amnt.isEmpty()) { if (amnt != null && !amnt.isEmpty()) {
@@ -207,15 +207,15 @@ public class WaveParser
} else { } else {
result.setAmount(SwarmAmount.LOW); result.setAmount(SwarmAmount.LOW);
} }
return result; return result;
} }
private static Wave parseSupplyWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseSupplyWave(Arena arena, String name, ConfigurationSection config) {
SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config); SortedMap<Integer,MACreature> monsters = getMonsterMap(arena, name, config);
SupplyWave result = new SupplyWave(monsters); SupplyWave result = new SupplyWave(monsters);
// Grab the loot. // Grab the loot.
List<String> loot = config.getStringList("drops"); List<String> loot = config.getStringList("drops");
if (loot == null || loot.isEmpty()) { if (loot == null || loot.isEmpty()) {
@@ -236,28 +236,28 @@ public class WaveParser
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
result.setDropList(stacks); result.setDropList(stacks);
return result; return result;
} }
private static Wave parseUpgradeWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseUpgradeWave(Arena arena, String name, ConfigurationSection config) {
ThingManager thingman = arena.getPlugin().getThingManager(); ThingManager thingman = arena.getPlugin().getThingManager();
Map<String,List<Thing>> upgrades = getUpgradeMap(config, name, arena, thingman); Map<String,List<Thing>> upgrades = getUpgradeMap(config, name, arena, thingman);
return new UpgradeWave(upgrades); return new UpgradeWave(upgrades);
} }
private static Wave parseBossWave(Arena arena, String name, ConfigurationSection config) { private static Wave parseBossWave(Arena arena, String name, ConfigurationSection config) {
MACreature monster = getSingleMonster(arena, name, config); MACreature monster = getSingleMonster(arena, name, config);
BossWave result = new BossWave(monster); BossWave result = new BossWave(monster);
// Check if there's a specific boss name // Check if there's a specific boss name
String bossName = config.getString("name", null); String bossName = config.getString("name", null);
if (bossName != null && !bossName.isEmpty()) { if (bossName != null && !bossName.isEmpty()) {
result.setBossName(ChatColor.translateAlternateColorCodes('&', bossName)); result.setBossName(ChatColor.translateAlternateColorCodes('&', bossName));
} }
// Grab the boss health // Grab the boss health
String healthString = config.getString("health", null); String healthString = config.getString("health", null);
if (healthString != null && !healthString.isEmpty()) { if (healthString != null && !healthString.isEmpty()) {
@@ -274,7 +274,7 @@ public class WaveParser
} else { } else {
result.setHealth(BossHealth.MEDIUM); result.setHealth(BossHealth.MEDIUM);
} }
// And the abilities. // And the abilities.
List<String> abilities = config.getStringList("abilities"); List<String> abilities = config.getStringList("abilities");
if (abilities == null || abilities.isEmpty()) { if (abilities == null || abilities.isEmpty()) {
@@ -298,11 +298,11 @@ public class WaveParser
return ability; return ability;
}) })
.forEach(result::addBossAbility); .forEach(result::addBossAbility);
// As well as the ability interval and ability announce. // As well as the ability interval and ability announce.
result.setAbilityInterval(config.getInt("ability-interval", 3) * 20); result.setAbilityInterval(config.getInt("ability-interval", 3) * 20);
result.setAbilityAnnounce(config.getBoolean("ability-announce", true)); result.setAbilityAnnounce(config.getBoolean("ability-announce", true));
// Rewards! // Rewards!
String rew = config.getString("reward", null); String rew = config.getString("reward", null);
if (rew != null && !rew.isEmpty()) { if (rew != null && !rew.isEmpty()) {
@@ -335,10 +335,10 @@ public class WaveParser
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
result.setDrops(stacks); result.setDrops(stacks);
return result; return result;
} }
/** /**
* Scan the ConfigSection for a "monster" (singular) node, which * Scan the ConfigSection for a "monster" (singular) node, which
* must be exactly a single monster. * must be exactly a single monster.
@@ -350,14 +350,14 @@ public class WaveParser
if (monster == null || monster.isEmpty()) { if (monster == null || monster.isEmpty()) {
throw new ConfigError("Missing 'monster' node for wave " + name + " of arena " + arena.configName()); throw new ConfigError("Missing 'monster' node for wave " + name + " of arena " + arena.configName());
} }
MACreature result = MACreature.fromString(monster); MACreature result = MACreature.fromString(monster);
if (result == null) { if (result == null) {
throw new ConfigError("Failed to parse monster for wave " + name + " of arena " + arena.configName() + ": " + monster); throw new ConfigError("Failed to parse monster for wave " + name + " of arena " + arena.configName() + ": " + monster);
} }
return result; return result;
} }
/** /**
* Scan the ConfigSection for a "monsters" (plural) node, which * Scan the ConfigSection for a "monsters" (plural) node, which
* must contain a list of at least one "monster: number" node. * must contain a list of at least one "monster: number" node.
@@ -374,31 +374,31 @@ public class WaveParser
if (monsters == null || monsters.isEmpty()) { if (monsters == null || monsters.isEmpty()) {
throw new ConfigError("Empty 'monsters' node for wave " + name + " of arena " + arena.configName()); throw new ConfigError("Empty 'monsters' node for wave " + name + " of arena " + arena.configName());
} }
// Prepare the map. // Prepare the map.
SortedMap<Integer,MACreature> monsterMap = new TreeMap<>(); SortedMap<Integer,MACreature> monsterMap = new TreeMap<>();
int sum = 0; int sum = 0;
String path = "monsters."; String path = "monsters.";
// Check all the monsters. // Check all the monsters.
for (String monster : monsters) { for (String monster : monsters) {
MACreature creature = MACreature.fromString(monster); MACreature creature = MACreature.fromString(monster);
if (creature == null) { if (creature == null) {
throw new ConfigError("Failed to parse monster for wave " + name + " of arena " + arena.configName() + ": " + monster); throw new ConfigError("Failed to parse monster for wave " + name + " of arena " + arena.configName() + ": " + monster);
} }
int prob = config.getInt(path + monster, -1); int prob = config.getInt(path + monster, -1);
if (prob < 0) { if (prob < 0) {
throw new ConfigError("Failed to parse probability for monster " + monster + " in wave " + name + " of arena " + arena.configName()); throw new ConfigError("Failed to parse probability for monster " + monster + " in wave " + name + " of arena " + arena.configName());
} }
sum += prob; sum += prob;
monsterMap.put(sum, creature); monsterMap.put(sum, creature);
} }
return monsterMap; return monsterMap;
} }
private static List<Location> getSpawnpoints(Arena arena, String name, ConfigurationSection config) { private static List<Location> getSpawnpoints(Arena arena, String name, ConfigurationSection config) {
List<String> spawnpoints = config.getStringList("spawnpoints"); List<String> spawnpoints = config.getStringList("spawnpoints");
if (spawnpoints == null || spawnpoints.isEmpty()) { if (spawnpoints == null || spawnpoints.isEmpty()) {
@@ -408,7 +408,7 @@ public class WaveParser
} }
spawnpoints = Arrays.asList(value.split(";")); spawnpoints = Arrays.asList(value.split(";"));
} }
ArenaRegion region = arena.getRegion(); ArenaRegion region = arena.getRegion();
return spawnpoints.stream() return spawnpoints.stream()
.map(String::trim) .map(String::trim)
@@ -451,7 +451,7 @@ public class WaveParser
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private static Map<String,List<Thing>> getUpgradeMap(ConfigurationSection config, String name, Arena arena, ThingManager thingman) { private static Map<String,List<Thing>> getUpgradeMap(ConfigurationSection config, String name, Arena arena, ThingManager thingman) {
ConfigurationSection section = config.getConfigurationSection("upgrades"); ConfigurationSection section = config.getConfigurationSection("upgrades");
if (section == null) { if (section == null) {
@@ -462,10 +462,10 @@ public class WaveParser
if (classes == null || classes.isEmpty()) { if (classes == null || classes.isEmpty()) {
throw new ConfigError("Empty 'upgrades' node for wave " + name + " of arena " + arena.configName()); throw new ConfigError("Empty 'upgrades' node for wave " + name + " of arena " + arena.configName());
} }
Map<String,List<Thing>> upgrades = new HashMap<>(); Map<String,List<Thing>> upgrades = new HashMap<>();
String path = "upgrades."; String path = "upgrades.";
for (String className : classes) { for (String className : classes) {
// Legacy support // Legacy support
Object val = config.get(path + className, null); Object val = config.get(path + className, null);
@@ -479,7 +479,7 @@ public class WaveParser
upgrades.put(className.toLowerCase(), list); upgrades.put(className.toLowerCase(), list);
} }
} }
return upgrades; return upgrades;
} }
@@ -570,14 +570,14 @@ public class WaveParser
return list; return list;
} }
public static Wave createDefaultWave() { public static Wave createDefaultWave() {
SortedMap<Integer,MACreature> monsters = new TreeMap<>(); SortedMap<Integer,MACreature> monsters = new TreeMap<>();
monsters.put(10, MACreature.ZOMBIE); monsters.put(10, MACreature.ZOMBIE);
monsters.put(20, MACreature.SKELETON); monsters.put(20, MACreature.SKELETON);
monsters.put(30, MACreature.SPIDER); monsters.put(30, MACreature.SPIDER);
monsters.put(40, MACreature.SLIMESMALL); monsters.put(40, MACreature.SLIMESMALL);
DefaultWave result = new DefaultWave(monsters); DefaultWave result = new DefaultWave(monsters);
result.setName("MA_DEFAULT_WAVE"); result.setName("MA_DEFAULT_WAVE");
result.setBranch(WaveBranch.RECURRENT); result.setBranch(WaveBranch.RECURRENT);
@@ -587,7 +587,7 @@ public class WaveParser
result.setGrowth(WaveGrowth.OLD); result.setGrowth(WaveGrowth.OLD);
result.setHealthMultiplier(1D); result.setHealthMultiplier(1D);
result.setAmountMultiplier(1D); result.setAmountMultiplier(1D);
return result; return result;
} }
} }
@@ -21,12 +21,12 @@ public class WaveUtils
public static List<Location> getValidSpawnpoints(Arena arena, List<Location> spawnpoints, Collection<Player> players) { public static List<Location> getValidSpawnpoints(Arena arena, List<Location> spawnpoints, Collection<Player> players) {
MobArena plugin = arena.getPlugin(); MobArena plugin = arena.getPlugin();
List<Location> result = new ArrayList<>(); List<Location> result = new ArrayList<>();
// Ensure that we do have some spawnpoints. // Ensure that we do have some spawnpoints.
if (spawnpoints == null || spawnpoints.isEmpty()) { if (spawnpoints == null || spawnpoints.isEmpty()) {
spawnpoints = arena.getRegion().getSpawnpointList(); spawnpoints = arena.getRegion().getSpawnpointList();
} }
// Loop through each one and check if any players are in range. // Loop through each one and check if any players are in range.
for (Location l : spawnpoints) { for (Location l : spawnpoints) {
for (Player p : players) { for (Player p : players) {
@@ -37,7 +37,7 @@ public class WaveUtils
break; break;
} }
} }
// If no spawnpoints in range, just return all of them. // If no spawnpoints in range, just return all of them.
if (result.isEmpty()) { if (result.isEmpty()) {
String locs = ""; String locs = "";
@@ -50,14 +50,14 @@ public class WaveUtils
} }
return result; return result;
} }
public static Player getClosestPlayer(Arena arena, Entity e) public static Player getClosestPlayer(Arena arena, Entity e)
{ {
// Set up the comparison variable and the result. // Set up the comparison variable and the result.
double dist = 0; double dist = 0;
double current = Double.POSITIVE_INFINITY; double current = Double.POSITIVE_INFINITY;
Player result = null; Player result = null;
/* Iterate through the ArrayList, and update current and result every /* Iterate through the ArrayList, and update current and result every
* time a squared distance smaller than current is found. */ * time a squared distance smaller than current is found. */
for (Player p : arena.getPlayersInArena()) for (Player p : arena.getPlayersInArena())
@@ -68,7 +68,7 @@ public class WaveUtils
p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)"); p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)");
continue; continue;
} }
dist = p.getLocation().distanceSquared(e.getLocation()); dist = p.getLocation().distanceSquared(e.getLocation());
if (dist < current && dist < MobArena.MIN_PLAYER_DISTANCE_SQUARED) if (dist < current && dist < MobArena.MIN_PLAYER_DISTANCE_SQUARED)
{ {
@@ -84,7 +84,7 @@ public class WaveUtils
// Comparators // Comparators
// //
////////////////////////////////////////////////////////////////////*/ ////////////////////////////////////////////////////////////////////*/
/** /**
* Get a comparator based on the WaveBranch parameter. * Get a comparator based on the WaveBranch parameter.
*/ */
@@ -97,7 +97,7 @@ public class WaveUtils
else else
return null; return null;
} }
/** /**
* Get a Comparator that compares Wave objects by wave number. * Get a Comparator that compares Wave objects by wave number.
* If the wave numbers are equal, the waves are equal. This is to * If the wave numbers are equal, the waves are equal. This is to
@@ -118,12 +118,12 @@ public class WaveUtils
} }
}; };
} }
/** /**
* Get a Comparator that compares Wave objects by priority. * Get a Comparator that compares Wave objects by priority.
* If the priorities are equal, the names are compared. This is to * If the priorities are equal, the names are compared. This is to
* ALLOW "duplicates" in the RECURRENT WAVES collection. * ALLOW "duplicates" in the RECURRENT WAVES collection.
* @return Comparator whose compare()-method compares wave priorities. * @return Comparator whose compare()-method compares wave priorities.
*/ */
public static Comparator<Wave> getRecurrentComparator() public static Comparator<Wave> getRecurrentComparator()
{ {
@@ -11,7 +11,7 @@ public @interface AbilityInfo
* This value is printed when a boss executes the ability in the arena. * This value is printed when a boss executes the ability in the arena.
*/ */
String name(); String name();
/** /**
* The config aliases for the ability. * The config aliases for the ability.
* This is used by MobArena to parse ability names from the config-file. * This is used by MobArena to parse ability names from the config-file.
@@ -43,7 +43,7 @@ public class AbilityManager
private static final String ma = "plugins" + File.separator + "MobArena.jar"; private static final String ma = "plugins" + File.separator + "MobArena.jar";
private static final String cb = System.getProperty("java.class.path"); private static final String cb = System.getProperty("java.class.path");
private static final String classpath = ma + System.getProperty("path.separator") + cb; private static final String classpath = ma + System.getProperty("path.separator") + cb;
private static Map<String,Class<? extends Ability>> abilities; private static Map<String,Class<? extends Ability>> abilities;
/** /**
@@ -90,7 +90,7 @@ public class AbilityManager
register(ThrowTarget.class); register(ThrowTarget.class);
register(WarpToPlayer.class); register(WarpToPlayer.class);
} }
/** /**
* Load the custom abilities from the specified directory. * Load the custom abilities from the specified directory.
* @param dataDir main plugin data folder * @param dataDir main plugin data folder
@@ -105,7 +105,7 @@ public class AbilityManager
// Grab the source directory. // Grab the source directory.
File javaDir = new File(classDir, "src"); File javaDir = new File(classDir, "src");
/* If the source directory exists, we need to verify that the system /* If the source directory exists, we need to verify that the system
* has a java compiler before attempting anything. If not, we need to * has a java compiler before attempting anything. If not, we need to
* skip the compiling step and just go straight to loading in the * skip the compiling step and just go straight to loading in the
@@ -117,7 +117,7 @@ public class AbilityManager
Bukkit.getLogger().warning("[MobArena] Found plugins/MobArena/abilities/src/ folder, but no Java compiler. The source files will not be compiled!"); Bukkit.getLogger().warning("[MobArena] Found plugins/MobArena/abilities/src/ folder, but no Java compiler. The source files will not be compiled!");
} }
} }
// Load all the custom abilities. // Load all the custom abilities.
loadClasses(classDir); loadClasses(classDir);
} }
@@ -142,38 +142,38 @@ public class AbilityManager
// Announce custom abilities // Announce custom abilities
if (announce) Bukkit.getLogger().info("[MobArena] Loaded custom ability '" + info.name() + "'"); if (announce) Bukkit.getLogger().info("[MobArena] Loaded custom ability '" + info.name() + "'");
} }
private static void compileAbilities(File javaDir, File classDir) { private static void compileAbilities(File javaDir, File classDir) {
if (!javaDir.exists()) return; if (!javaDir.exists()) return;
// Make ready a new list of files to compile. // Make ready a new list of files to compile.
List<File> toCompile = getSourceFilesToCompile(javaDir, classDir); List<File> toCompile = getSourceFilesToCompile(javaDir, classDir);
// No files to compile? // No files to compile?
if (toCompile.isEmpty()) { if (toCompile.isEmpty()) {
return; return;
} }
// Notify the console. // Notify the console.
Bukkit.getLogger().info("[MobArena] Compiling abilities: " + fileListToString(toCompile)); Bukkit.getLogger().info("[MobArena] Compiling abilities: " + fileListToString(toCompile));
// Get the compiler // Get the compiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// Generate some JavaFileObjects // Generate some JavaFileObjects
try { try {
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(toCompile); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(toCompile);
// Include the MobArena.jar on the classpath, and set the destination folder. // Include the MobArena.jar on the classpath, and set the destination folder.
List<String> options = Arrays.asList("-classpath", classpath, "-d", classDir.getPath()); List<String> options = Arrays.asList("-classpath", classpath, "-d", classDir.getPath());
// Set up the compilation task. // Set up the compilation task.
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
// Call the task. // Call the task.
task.call(); task.call();
// And close the file manager. // And close the file manager.
fileManager.close(); fileManager.close();
} }
@@ -182,17 +182,17 @@ public class AbilityManager
e.printStackTrace(); e.printStackTrace();
} }
} }
private static List<File> getSourceFilesToCompile(File javaDir, File classDir) { private static List<File> getSourceFilesToCompile(File javaDir, File classDir) {
List<File> result = new ArrayList<>(); List<File> result = new ArrayList<>();
if (javaDir == null || !javaDir.exists()) { if (javaDir == null || !javaDir.exists()) {
return result; return result;
} }
// Grab the array of compiled files. // Grab the array of compiled files.
File[] classFiles = classDir.listFiles(); File[] classFiles = classDir.listFiles();
// Go through each source file. // Go through each source file.
for (File javaFile : javaDir.listFiles()) { for (File javaFile : javaDir.listFiles()) {
// Skip if it's not a .java file. // Skip if it's not a .java file.
@@ -200,24 +200,24 @@ public class AbilityManager
Bukkit.getLogger().info("[MobArena] Found invalid ability file: " + javaFile.getName()); Bukkit.getLogger().info("[MobArena] Found invalid ability file: " + javaFile.getName());
continue; continue;
} }
// Find the associated .class file. // Find the associated .class file.
File classFile = findClassFile(javaFile, classFiles); File classFile = findClassFile(javaFile, classFiles);
// If the .class file is newer, we don't need to compile. // If the .class file is newer, we don't need to compile.
if (isClassFileNewer(javaFile, classFile)) { if (isClassFileNewer(javaFile, classFile)) {
continue; continue;
} }
result.add(javaFile); result.add(javaFile);
} }
return result; return result;
} }
private static File findClassFile(File javaFile, File[] classFiles) { private static File findClassFile(File javaFile, File[] classFiles) {
String javaFileName = javaFile.getName(); String javaFileName = javaFile.getName();
String classFileName = javaFileName.substring(0, javaFileName.lastIndexOf(".")) + ".class"; String classFileName = javaFileName.substring(0, javaFileName.lastIndexOf(".")) + ".class";
for (File classFile : classFiles) { for (File classFile : classFiles) {
if (classFile.getName().equals(classFileName)) { if (classFile.getName().equals(classFileName)) {
return classFile; return classFile;
@@ -225,13 +225,13 @@ public class AbilityManager
} }
return null; return null;
} }
private static boolean isClassFileNewer(File javaFile, File classFile) { private static boolean isClassFileNewer(File javaFile, File classFile) {
if (classFile == null) return false; if (classFile == null) return false;
return (classFile.lastModified() > javaFile.lastModified()); return (classFile.lastModified() > javaFile.lastModified());
} }
/** /**
* (Compiles and) loads all custom abilities in the given directory. * (Compiles and) loads all custom abilities in the given directory.
* @param classDir a directory * @param classDir a directory
@@ -240,21 +240,21 @@ public class AbilityManager
// Grab the class loader // Grab the class loader
ClassLoader loader = getLoader(classDir); ClassLoader loader = getLoader(classDir);
if (loader == null) return; if (loader == null) return;
for (File file : classDir.listFiles()) { for (File file : classDir.listFiles()) {
String filename = file.getName(); String filename = file.getName();
// Only load .class files. // Only load .class files.
int dot = filename.lastIndexOf(".class"); int dot = filename.lastIndexOf(".class");
if (dot < 0) continue; if (dot < 0) continue;
// Trim off the .class extension // Trim off the .class extension
String name = filename.substring(0, file.getName().lastIndexOf(".")); String name = filename.substring(0, file.getName().lastIndexOf("."));
try { try {
// Load the class // Load the class
Class<?> cls = loader.loadClass(name); Class<?> cls = loader.loadClass(name);
// Verify that it's an Ability, then register it // Verify that it's an Ability, then register it
if (Ability.class.isAssignableFrom(cls)) { if (Ability.class.isAssignableFrom(cls)) {
register(cls.asSubclass(Ability.class), true); register(cls.asSubclass(Ability.class), true);
@@ -262,7 +262,7 @@ public class AbilityManager
} catch (Exception e) {} } catch (Exception e) {}
} }
} }
/** /**
* Get a ClassLoader for the given directory. * Get a ClassLoader for the given directory.
* @param dir a directory * @param dir a directory
@@ -274,30 +274,30 @@ public class AbilityManager
return loader; return loader;
} }
catch (Exception e) {} catch (Exception e) {}
return null; return null;
} }
private static String fileListToString(List<File> list) { private static String fileListToString(List<File> list) {
return fileListToString(list, null); return fileListToString(list, null);
} }
private static String fileListToString(List<File> list, String exclude) { private static String fileListToString(List<File> list, String exclude) {
if (list.isEmpty()) return ""; if (list.isEmpty()) return "";
StringBuffer buffy = new StringBuffer(); StringBuffer buffy = new StringBuffer();
for (File file : list) { for (File file : list) {
String name = file.getName(); String name = file.getName();
int dot = name.lastIndexOf("."); int dot = name.lastIndexOf(".");
if (exclude != null && name.contains(exclude)) { if (exclude != null && name.contains(exclude)) {
continue; continue;
} }
buffy.append(", " + name.substring(0, dot)); buffy.append(", " + name.substring(0, dot));
} }
// Trim off the first ", ". // Trim off the first ", ".
return buffy.substring(2); return buffy.substring(2);
} }
@@ -14,7 +14,7 @@ import java.util.Random;
public class AbilityUtils public class AbilityUtils
{ {
public static Random random = new Random(); public static Random random = new Random();
/** /**
* Get the target player of the LivingEntity if possible. * Get the target player of the LivingEntity if possible.
* @param the arena * @param the arena
@@ -25,18 +25,18 @@ public class AbilityUtils
public static LivingEntity getTarget(Arena arena, LivingEntity entity, boolean random) { public static LivingEntity getTarget(Arena arena, LivingEntity entity, boolean random) {
if (entity instanceof Creature) { if (entity instanceof Creature) {
LivingEntity target = ((Creature) entity).getTarget(); LivingEntity target = ((Creature) entity).getTarget();
if (target instanceof Player && arena.inArena((Player) target)) { if (target instanceof Player && arena.inArena((Player) target)) {
return target; return target;
} }
} }
if (random) { if (random) {
return getRandomPlayer(arena); return getRandomPlayer(arena);
} }
return null; return null;
} }
/** /**
* Get a random arena player. * Get a random arena player.
* @param arena the arena * @param arena the arena
@@ -45,10 +45,10 @@ public class AbilityUtils
public static Player getRandomPlayer(Arena arena) { public static Player getRandomPlayer(Arena arena) {
List<Player> list = new ArrayList<>(arena.getPlayersInArena()); List<Player> list = new ArrayList<>(arena.getPlayersInArena());
if (list.isEmpty()) return null; if (list.isEmpty()) return null;
return list.get(random.nextInt(list.size())); return list.get(random.nextInt(list.size()));
} }
/** /**
* Get a list of nearby players * Get a list of nearby players
* @param arena the arena * @param arena the arena
@@ -65,12 +65,12 @@ public class AbilityUtils
} }
return result; return result;
} }
/** /**
* Get a list of distant players * Get a list of distant players
* @param arena the arena * @param arena the arena
* @param boss the boss * @param boss the boss
* @param x the 'radius' in which to exclude players * @param x the 'radius' in which to exclude players
* @return a list of distant players * @return a list of distant players
*/ */
public static List<Player> getDistantPlayers(Arena arena, Entity boss, int x) { public static List<Player> getDistantPlayers(Arena arena, Entity boss, int x) {
@@ -18,43 +18,43 @@ import java.util.List;
public class ChainLightning implements Ability public class ChainLightning implements Ability
{ {
/** /**
* How many blocks the chain lightning can spread over. * How many blocks the chain lightning can spread over.
* Must be greater than 0. * Must be greater than 0.
*/ */
private static final int RADIUS = 4; private static final int RADIUS = 4;
/** /**
* How many server ticks between each lightning strike. * How many server ticks between each lightning strike.
* Must be greater than 0. * Must be greater than 0.
*/ */
private static final int TICKS = 10; private static final int TICKS = 10;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
final LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true); final LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true);
if (target == null || !(target instanceof Player)) if (target == null || !(target instanceof Player))
return; return;
strikeLightning(arena, (Player) target, new ArrayList<>()); strikeLightning(arena, (Player) target, new ArrayList<>());
} }
private void strikeLightning(final Arena arena, final Player p, final List<Player> done) { private void strikeLightning(final Arena arena, final Player p, final List<Player> done) {
arena.scheduleTask(new Runnable() { arena.scheduleTask(new Runnable() {
public void run() { public void run() {
if (!arena.isRunning() || !arena.inArena(p)) if (!arena.isRunning() || !arena.inArena(p))
return; return;
// Smite the target // Smite the target
arena.getWorld().strikeLightning(p.getLocation()); arena.getWorld().strikeLightning(p.getLocation());
done.add(p); done.add(p);
// Grab all nearby players // Grab all nearby players
List<Player> nearby = AbilityUtils.getNearbyPlayers(arena, p, RADIUS); List<Player> nearby = AbilityUtils.getNearbyPlayers(arena, p, RADIUS);
// Remove all that are "done", and return if empty // Remove all that are "done", and return if empty
nearby.removeAll(done); nearby.removeAll(done);
if (nearby.isEmpty()) return; if (nearby.isEmpty()) return;
// Otherwise, smite the next target! // Otherwise, smite the next target!
strikeLightning(arena, nearby.get(0), done); strikeLightning(arena, nearby.get(0), done);
} }
@@ -18,7 +18,7 @@ public class DisorientDistant implements Ability
* How far away players must be to be affected by the ability. * How far away players must be to be affected by the ability.
*/ */
private static final int RADIUS = 8; private static final int RADIUS = 8;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) {
@@ -19,12 +19,12 @@ public class DisorientNearby implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), false); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), false);
if (target == null) return; if (target == null) return;
for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) {
Location loc = p.getLocation(); Location loc = p.getLocation();
loc.setYaw(loc.getYaw() + 45 + AbilityUtils.random.nextInt(270)); loc.setYaw(loc.getYaw() + 45 + AbilityUtils.random.nextInt(270));
@@ -18,12 +18,12 @@ public class DisorientTarget implements Ability
* If the boss has no target, should a random player be selected? * If the boss has no target, should a random player be selected?
*/ */
private static final boolean RANDOM = false; private static final boolean RANDOM = false;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM);
if (target == null) return; if (target == null) return;
Location loc = target.getLocation(); Location loc = target.getLocation();
loc.setYaw(loc.getYaw() + 45 + AbilityUtils.random.nextInt(270)); loc.setYaw(loc.getYaw() + 45 + AbilityUtils.random.nextInt(270));
target.teleport(loc); target.teleport(loc);
@@ -18,11 +18,11 @@ public class FetchDistant implements Ability
* How far away players must be to be affected by the ability. * How far away players must be to be affected by the ability.
*/ */
private static final int RADIUS = 8; private static final int RADIUS = 8;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) {
p.teleport(bLoc); p.teleport(bLoc);
} }
@@ -18,11 +18,11 @@ public class FetchNearby implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) {
p.teleport(bLoc); p.teleport(bLoc);
} }
@@ -17,12 +17,12 @@ public class FetchTarget implements Ability
* If the boss has no target, should a random player be selected? * If the boss has no target, should a random player be selected?
*/ */
private static final boolean RANDOM = true; private static final boolean RANDOM = true;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM);
if (target == null) return; if (target == null) return;
target.teleport(boss.getEntity()); target.teleport(boss.getEntity());
} }
} }
@@ -17,12 +17,12 @@ public class FireAura implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
/** /**
* How many ticks the players should be on fire for. * How many ticks the players should be on fire for.
*/ */
private static final int TICKS = 20; private static final int TICKS = 20;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS))
@@ -19,7 +19,7 @@ public class Flood implements Ability
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Player p = AbilityUtils.getRandomPlayer(arena); Player p = AbilityUtils.getRandomPlayer(arena);
Block block = p.getLocation().getBlock(); Block block = p.getLocation().getBlock();
if (block.getType() == Material.AIR) { if (block.getType() == Material.AIR) {
block.setType(Material.WATER); block.setType(Material.WATER);
arena.addBlock(block); arena.addBlock(block);
@@ -18,7 +18,7 @@ public class LightningAura implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
World world = arena.getWorld(); World world = arena.getWorld();
@@ -18,29 +18,29 @@ public class LivingBomb implements Ability
* How many ticks before the bomb goes off. * How many ticks before the bomb goes off.
*/ */
private static final int FUSE = 60; private static final int FUSE = 60;
/** /**
* How close players must be to be affected by the bomb. * How close players must be to be affected by the bomb.
*/ */
private static final int RADIUS = 3; private static final int RADIUS = 3;
/** /**
* How many ticks players affected by the bomb should burn. * How many ticks players affected by the bomb should burn.
*/ */
private static final int AFTERBURN = 40; private static final int AFTERBURN = 40;
@Override @Override
public void execute(final Arena arena, MABoss boss) { public void execute(final Arena arena, MABoss boss) {
// Grab the target, or a random player. // Grab the target, or a random player.
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true);
// We only want players. // We only want players.
if (target == null || !(target instanceof Player)) if (target == null || !(target instanceof Player))
return; return;
final Player p = (Player) target; final Player p = (Player) target;
p.setFireTicks(FUSE + 5); p.setFireTicks(FUSE + 5);
// Create an explosion after 4 seconds // Create an explosion after 4 seconds
arena.scheduleTask(new Runnable() { arena.scheduleTask(new Runnable() {
public void run() { public void run() {
@@ -48,10 +48,10 @@ public class LivingBomb implements Ability
if (!arena.isRunning() || !arena.inArena(p) || p.getFireTicks() <= 0) { if (!arena.isRunning() || !arena.inArena(p) || p.getFireTicks() <= 0) {
return; return;
} }
// Explode! // Explode!
arena.getWorld().createExplosion(p.getLocation(), 1F); arena.getWorld().createExplosion(p.getLocation(), 1F);
// And set every nearby player on fire! // And set every nearby player on fire!
for (Player nearby : AbilityUtils.getNearbyPlayers(arena, p, RADIUS)) { for (Player nearby : AbilityUtils.getNearbyPlayers(arena, p, RADIUS)) {
nearby.setFireTicks(AFTERBURN); nearby.setFireTicks(AFTERBURN);
@@ -23,12 +23,12 @@ public class ObsidianBomb implements Ability
* How many ticks before the bomb goes off. * How many ticks before the bomb goes off.
*/ */
private static final int FUSE = 80; private static final int FUSE = 80;
@Override @Override
public void execute(final Arena arena, MABoss boss) { public void execute(final Arena arena, MABoss boss) {
// Grab the target, or a random player. // Grab the target, or a random player.
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true);
final World world = arena.getWorld(); final World world = arena.getWorld();
final Location loc; final Location loc;
@@ -53,7 +53,7 @@ public class ObsidianBomb implements Ability
public void run() { public void run() {
if (!arena.isRunning()) if (!arena.isRunning())
return; return;
world.getBlockAt(loc).setType(Material.AIR); world.getBlockAt(loc).setType(Material.AIR);
world.createExplosion(loc, 3F); world.createExplosion(loc, 3F);
} }
@@ -19,19 +19,19 @@ public class PullDistant implements Ability
* How far away players must be to be affected by the ability. * How far away players must be to be affected by the ability.
*/ */
private static final int RADIUS = 8; private static final int RADIUS = 8;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) {
Location loc = p.getLocation(); Location loc = p.getLocation();
Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ()); Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ());
double a = Math.abs(bLoc.getX() - loc.getX()); double a = Math.abs(bLoc.getX() - loc.getX());
double b = Math.abs(bLoc.getZ() - loc.getZ()); double b = Math.abs(bLoc.getZ() - loc.getZ());
double c = Math.sqrt((a*a + b*b)); double c = Math.sqrt((a*a + b*b));
p.setVelocity(v.normalize().multiply(c*0.3).setY(0.8)); p.setVelocity(v.normalize().multiply(c*0.3).setY(0.8));
} }
} }
@@ -19,19 +19,19 @@ public class PullNearby implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) {
Location loc = p.getLocation(); Location loc = p.getLocation();
Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ()); Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ());
double a = Math.abs(bLoc.getX() - loc.getX()); double a = Math.abs(bLoc.getX() - loc.getX());
double b = Math.abs(bLoc.getZ() - loc.getZ()); double b = Math.abs(bLoc.getZ() - loc.getZ());
double c = Math.sqrt((a*a + b*b)); double c = Math.sqrt((a*a + b*b));
p.setVelocity(v.normalize().multiply(c*0.3).setY(0.8)); p.setVelocity(v.normalize().multiply(c*0.3).setY(0.8));
} }
} }
@@ -19,20 +19,20 @@ public class PullTarget implements Ability
* If the boss has no target, should a random player be selected? * If the boss has no target, should a random player be selected?
*/ */
private static final boolean RANDOM = false; private static final boolean RANDOM = false;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM);
if (target == null) return; if (target == null) return;
Location loc = target.getLocation(); Location loc = target.getLocation();
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ()); Vector v = new Vector(bLoc.getX() - loc.getX(), 0, bLoc.getZ() - loc.getZ());
double a = Math.abs(bLoc.getX() - loc.getX()); double a = Math.abs(bLoc.getX() - loc.getX());
double b = Math.abs(bLoc.getZ() - loc.getZ()); double b = Math.abs(bLoc.getZ() - loc.getZ());
double c = Math.sqrt((a*a + b*b)); double c = Math.sqrt((a*a + b*b));
target.setVelocity(v.normalize().multiply(c*0.3).setY(0.8)); target.setVelocity(v.normalize().multiply(c*0.3).setY(0.8));
} }
} }
@@ -20,12 +20,12 @@ public class RootTarget implements Ability
* How long the the potions last (in ticks). * How long the the potions last (in ticks).
*/ */
private static final int DURATION = 30; private static final int DURATION = 30;
/** /**
* The amplifier for the potions. * The amplifier for the potions.
*/ */
private static final int AMPLIFIER = 100; private static final int AMPLIFIER = 100;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
final LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true); final LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), true);
@@ -23,16 +23,16 @@ public class ShufflePositions implements Ability
// Grab the players and add the boss // Grab the players and add the boss
List<LivingEntity> entities = new ArrayList<>(arena.getPlayersInArena()); List<LivingEntity> entities = new ArrayList<>(arena.getPlayersInArena());
entities.add(boss.getEntity()); entities.add(boss.getEntity());
// Grab the locations // Grab the locations
List<Location> locations = new LinkedList<>(); List<Location> locations = new LinkedList<>();
for (LivingEntity e : entities) { for (LivingEntity e : entities) {
locations.add(e.getLocation()); locations.add(e.getLocation());
} }
// Shuffle the entities list. // Shuffle the entities list.
Collections.shuffle(entities); Collections.shuffle(entities);
/* The entities are shuffled, but the locations are not, so if /* The entities are shuffled, but the locations are not, so if
* we remove the first element of each list, chances are they * we remove the first element of each list, chances are they
* will not match, i.e. shuffle achieved! */ * will not match, i.e. shuffle achieved! */
@@ -19,11 +19,11 @@ public class ThrowDistant implements Ability
* How far away players must be to be affected by the ability. * How far away players must be to be affected by the ability.
*/ */
private static final int RADIUS = 8; private static final int RADIUS = 8;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getDistantPlayers(arena, boss.getEntity(), RADIUS)) {
Location loc = p.getLocation(); Location loc = p.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ()); Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
@@ -19,11 +19,11 @@ public class ThrowNearby implements Ability
* How close players must be to be affected by the ability. * How close players must be to be affected by the ability.
*/ */
private static final int RADIUS = 5; private static final int RADIUS = 5;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) { for (Player p : AbilityUtils.getNearbyPlayers(arena, boss.getEntity(), RADIUS)) {
Location loc = p.getLocation(); Location loc = p.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ()); Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
@@ -19,7 +19,7 @@ public class ThrowTarget implements Ability
* If the boss has no target, should a random player be selected? * If the boss has no target, should a random player be selected?
*/ */
private static final boolean RANDOM = false; private static final boolean RANDOM = false;
@Override @Override
public void execute(Arena arena, MABoss boss) { public void execute(Arena arena, MABoss boss) {
LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM); LivingEntity target = AbilityUtils.getTarget(arena, boss.getEntity(), RANDOM);
@@ -28,7 +28,7 @@ public class ThrowTarget implements Ability
Location bLoc = boss.getEntity().getLocation(); Location bLoc = boss.getEntity().getLocation();
Location loc = target.getLocation(); Location loc = target.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ()); Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
target.setVelocity(v.normalize().setY(0.8)); target.setVelocity(v.normalize().setY(0.8));
} }
} }
@@ -4,16 +4,16 @@ public enum BossHealth
{ {
VERYLOW(4), LOW(8), MEDIUM(15), HIGH(25), VERYHIGH(40), PSYCHO(60); VERYLOW(4), LOW(8), MEDIUM(15), HIGH(25), VERYHIGH(40), PSYCHO(60);
private int multiplier; private int multiplier;
BossHealth(int multiplier) { BossHealth(int multiplier) {
this.multiplier = multiplier; this.multiplier = multiplier;
} }
public int getMax(int playerCount) { public int getMax(int playerCount) {
return (playerCount + 1) * 20 * multiplier; return (playerCount + 1) * 20 * multiplier;
} }
public int getMultiplier() { public int getMultiplier() {
return multiplier; return multiplier;
} }
} }
@@ -4,12 +4,12 @@ public enum SwarmAmount
{ {
LOW(10), MEDIUM(20), HIGH(30), PSYCHO(60); LOW(10), MEDIUM(20), HIGH(30), PSYCHO(60);
private int multiplier; private int multiplier;
SwarmAmount(int multiplier) { SwarmAmount(int multiplier) {
this.multiplier = multiplier; this.multiplier = multiplier;
} }
public int getAmount(int playerCount) { public int getAmount(int playerCount) {
return Math.max(1, playerCount / 2) * multiplier; return Math.max(1, playerCount / 2) * multiplier;
} }
} }
@@ -10,7 +10,7 @@ public enum WaveBranch
return (w.getFirstWave() == wave); return (w.getFirstWave() == wave);
} }
}, },
RECURRENT { RECURRENT {
@Override @Override
public boolean matches(int wave, Wave w) { public boolean matches(int wave, Wave w) {
@@ -20,6 +20,6 @@ public enum WaveBranch
return ((wave - w.getFirstWave()) % w.getFrequency() == 0); return ((wave - w.getFirstWave()) % w.getFrequency() == 0);
} }
}; };
public abstract boolean matches(int wave, Wave w); public abstract boolean matches(int wave, Wave w);
} }

Some files were not shown because too many files have changed in this diff Show More