diff --git a/language files/announcements_da.properties b/language files/announcements_da.properties new file mode 100644 index 0000000..42d61f2 --- /dev/null +++ b/language files/announcements_da.properties @@ -0,0 +1,51 @@ +ARENA_START=Lad massakren begynde! +ARENA_END=Arena slut. +ARENA_DOES_NOT_EXIST=Arenaen findes ikke. Skriv /ma arenas for en liste. +JOIN_PLAYER_JOINED=Du joinede arenaen! +JOIN_NOT_ENABLED=MobArena er ikke aktiveret. +JOIN_IN_OTHER_ARENA=Du er allerede i en arena. Forlad den først. +JOIN_ARENA_NOT_ENABLED=Arenaen er deaktiveret. +JOIN_ARENA_NOT_SETUP=Arenaen er ikke blevet sat op endnu. +JOIN_ARENA_PERMISSION=Du har ikke rettigheder til den arena! +JOIN_FEE_REQUIRED=Du er for fattig. Pris: % +JOIN_FEE_PAID=Prisen for at joine var: % +JOIN_ARENA_IS_RUNNING=Arenaen er allerede startet. +JOIN_ALREADY_PLAYING=Du spiller allerede! +JOIN_ARG_NEEDED=Arenanavn pÃ¥krævet. Skriv /ma arenas for en liste. +JOIN_TOO_FAR=Du er for langt fra denne arena til at kunne joine. +JOIN_EMPTY_INV=Du skal tømme dit inventory før du kan joine arenaen. +JOIN_PLAYER_LIMIT_REACHED=Der kan ikke være flere spillere i arenaen. +JOIN_STORE_INV_FAIL=Kunne ikke gemme dit inventory. Prøv igen. +LEAVE_PLAYER_LEFT=Du forlod arenaen. +LEAVE_NOT_PLAYING=Du er ikke i en arena. +PLAYER_DIED=% døde! +SPEC_PLAYER_SPECTATE=Nyd forestillingen! +SPEC_NOT_RUNNING=Arenaen er ikke startet. +SPEC_ARG_NEEDED=Arenanavn pÃ¥krævet. Skriv /ma arenas for en liste. +SPEC_EMPTY_INV=Du skal tømme dit inventory først. +SPEC_ALREADY_PLAYING=Du spiller allerede! +NOT_READY_PLAYERS=Ikke klar: % +FORCE_START_STARTED=Arena tvunget til at starte. +FORCE_START_RUNNING=Arenaen er allerede startet. +FORCE_START_NOT_READY=Ingen spillere er klar. +FORCE_END_ENDED=Arena tvunget til at slutte. +FORCE_END_EMPTY=Der er ingen i arenaen. +FORCE_END_IDLE=Du var ikke hurtig nok! +REWARDS_GIVE=Her er alle dine præmier! +LOBBY_CLASS_PICKED=Du har valgt % som din klasse! +LOBBY_CLASS_RANDOM=Du fÃ¥r tildelt en klasse ved arena start. +LOBBY_CLASS_PERMISSION=Du har ikke rettigheder til den klasse! +LOBBY_PLAYER_READY=Du er markeret som klar! +LOBBY_DROP_ITEM=Du kan ikke dele items i lobbyen! +LOBBY_PICK_CLASS=Du skal først vælge en klasse! +LOBBY_RIGHT_CLICK=SlÃ¥ skiltene; ikke højre-klik. +WARP_TO_ARENA=Du kan ikke warpe til arenaen efter, den er startet. +WARP_FROM_ARENA=Du kan ikke warpe fra arenaen. +WAVE_DEFAULT=Bølge #%! +WAVE_SPECIAL=Bølge #%! [SPECIEL] +WAVE_REWARD=Du har lige vundet en præmie: % +MISC_LIST_ARENAS=Tilgængelige arenaer: % +MISC_LIST_PLAYERS=Levende spillere: % +MISC_COMMAND_NOT_ALLOWED=Du kan ikke bruge den kommando i arenaen. +MISC_NO_ACCESS=Du har ikke adgang til den kommando. +MISC_NONE= diff --git a/language files/announcements_fr.properties b/language files/announcements_fr.properties new file mode 100644 index 0000000..6f2b9d3 --- /dev/null +++ b/language files/announcements_fr.properties @@ -0,0 +1,51 @@ +ARENA_START=Que le massacre commence ! +ARENA_END=L'arène est terminée. +ARENA_DOES_NOT_EXIST=Cette arène n'existe pas. Entrez "/ma arenas" pour la liste. +JOIN_PLAYER_JOINED=Vous avez rejoint l'arène. Prennez plaisir ! +JOIN_NOT_ENABLED=MobArena n'est pas actif. +JOIN_IN_OTHER_ARENA=Vous êtes déjà dans l'arène! Quittez-la avant. +JOIN_ARENA_NOT_ENABLED=Cetta arène n'est pas active. +JOIN_ARENA_NOT_SETUP=Cette arène n'a pas encore été configurée. +JOIN_ARENA_PERMISSION=Vous n'avez pas la permission pour rejoindre cette arène. +JOIN_FEE_REQUIRED=Pas assez d'argent. Prix: % +JOIN_FEE_PAID=Le prix pour rejoindre était de: % +JOIN_ARENA_IS_RUNNING=L'arène est déjà occupée. +JOIN_ALREADY_PLAYING=Vous êtes déjà en train de jouer. +JOIN_ARG_NEEDED=Vous devez spécifier une arène. Entrez "/ma arenas" pour la liste. +JOIN_TOO_FAR=Vous êtes trop loins de l'arène pour pouvoir joindre en tant que joueur ou specateur. +JOIN_EMPTY_INV=Vous devez vider votre inventaire afin de joindre l'arène. +JOIN_PLAYER_LIMIT_REACHED=La limite de joueur pour cette arène a été atteinte. +JOIN_STORE_INV_FAIL=La sauvegarde de l'inventaire a échouée. Essayez encore. +LEAVE_PLAYER_LEFT=Vous avez quitté l'arène. Merci d'avoir joué ! +LEAVE_NOT_PLAYING=Vous n'êtes pas dans l'arène. +PLAYER_DIED=% est mort ! +SPEC_PLAYER_SPECTATE=Profitez bien du spectacle ! +SPEC_NOT_RUNNING=Cette arène n'est pas en cours. +SPEC_ARG_NEEDED=Vous devez spécifier une arène. Entrez "/ma arenas" pour la liste. +SPEC_EMPTY_INV=Vous devez vider votre inventaire. +SPEC_ALREADY_PLAYING=Vous ne pouvez pas être spectateur en tant que joueur de l'arène ! +NOT_READY_PLAYERS=Non prêt: % +FORCE_START_STARTED=Début forcé de l'arène. +FORCE_START_RUNNING=L'arène a commencée. +FORCE_START_NOT_READY=Ne peut pas forcer le début, il n'y a pas de joueurs prêts. +FORCE_END_ENDED=Fin forcée de l'arène. +FORCE_END_EMPTY=Il n'y a personne dans l'arène. +FORCE_END_IDLE=Vous n'avez pas été assez rapide ! +REWARDS_GIVE=Voici vos récompenses ! +LOBBY_CLASS_PICKED=Vous avez choisi % comme classe ! +LOBBY_CLASS_RANDOM=Une classe aléatoire va vous être attribuée. +LOBBY_CLASS_PERMISSION=Vous n'avez pas les permissions pour utiliser cette classe ! +LOBBY_PLAYER_READY=Vous avez été marqué comme prêt ! +LOBBY_DROP_ITEM=Pas de partage avant le début de l'arène ! +LOBBY_PICK_CLASS=Vous devez d'abord choisir une classe ! +LOBBY_RIGHT_CLICK=Vous devez frapper le panneau, pas cliquer du droit dessus. +WARP_TO_ARENA=Vous ne pouvez pas vous téléporter à l'arène pendant la bataille ! +WARP_FROM_ARENA=La téléportation est interdite dans l'arène ! +WAVE_DEFAULT=Soyez prêt pour la vague #% ! +WAVE_SPECIAL=Soyez prêt pour la vague #% ! [SPECIALE] +WAVE_REWARD=Vous avez gagné une récompense: % +MISC_LIST_ARENAS=Les arènes disponibles: % +MISC_LIST_PLAYERS=Les joueurs en live: % +MISC_COMMAND_NOT_ALLOWED=Vous ne pouvez pas utiliser cette commande dans l'arène ! +MISC_NO_ACCESS=Vous n'avez pas accès à cette commande. +MISC_NONE= diff --git a/language files/announcements_pirate.properties b/language files/announcements_pirate.properties new file mode 100644 index 0000000..0afaf05 --- /dev/null +++ b/language files/announcements_pirate.properties @@ -0,0 +1,51 @@ +ARENA_START=Hearts alive, men! +ARENA_END=Land ho! +ARENA_DOES_NOT_EXIST=Thar be no ship by that name! +JOIN_PLAYER_JOINED=Ahoy, matey! +JOIN_NOT_ENABLED=We be swabbing down the decks on all ships, matey. +JOIN_IN_OTHER_ARENA=Ye're already at sea, scallywag! +JOIN_ARENA_NOT_ENABLED=We be swabbing down the decks on this ship, matey. +JOIN_ARENA_NOT_SETUP=Arrrgh! We be missing the top sail! +JOIN_ARENA_PERMISSION=Arrgh! Ye can't board this ship, scurvy dog! +JOIN_FEE_REQUIRED=Ye don't own enough doubloons, matey! Price: % +JOIN_FEE_PAID=Booty ye gave up to join: % +JOIN_ARENA_IS_RUNNING=That ship has sailed, landlubber! +JOIN_ALREADY_PLAYING=Ye be aboard already, ye scurvy dog! +JOIN_ARG_NEEDED=Which ship are ye boarding? Type /ma arenas for a list, arrgh! +JOIN_TOO_FAR=Ye be too far from the docks, landlubber! +JOIN_EMPTY_INV=Throw ye belongings overboard, scallywag! +JOIN_PLAYER_LIMIT_REACHED=Thar be too many men aboard this ship already, landlubber! +JOIN_STORE_INV_FAIL=Ye belongings didn't fit in the storage deck, arrgh! +LEAVE_PLAYER_LEFT=Ye abandonned the ship! Arrrgh! +LEAVE_NOT_PLAYING=Ye're already on land, matey! +PLAYER_DIED=% walked the plank! +SPEC_PLAYER_SPECTATE=Welcome to the Crow's Nest! Grab ye spyglass! +SPEC_NOT_RUNNING=Thar be no one aboard that ship! +SPEC_ARG_NEEDED=Which ship are ye boarding? Type /ma arenas for a list, arrgh! +SPEC_EMPTY_INV=Throw ye belongings overboard, scallywag! +SPEC_ALREADY_PLAYING=Ye don't need ye spyglass aboard this ship, harr! +NOT_READY_PLAYERS=Landlubbers: % +FORCE_START_STARTED=Set sail! +FORCE_START_RUNNING=The ship has already set sail! +FORCE_START_NOT_READY=Thar be no scurvy dogs ready to set sail! +FORCE_END_ENDED=Forced the men to walk the plank! +FORCE_END_EMPTY=Thar be no one aboard the ship! +FORCE_END_IDLE=Arrrgh! Too slow, matey! +REWARDS_GIVE=Here's ye booty, seadog! +LOBBY_CLASS_PICKED=Ye be the %! +LOBBY_CLASS_RANDOM= +LOBBY_CLASS_PERMISSION=Ye can't use that cutlass, scurvy dog! +LOBBY_PLAYER_READY=Ready to sail! Arrrgh! +LOBBY_DROP_ITEM=Don't be sharing ye rum yet, scallywag! +LOBBY_PICK_CLASS=Grab ye cutlass first, matey! +LOBBY_RIGHT_CLICK=Ye can't be right-clickin', landlubber. +WARP_TO_ARENA=Ye can't board this ship, wench! +WARP_FROM_ARENA=Walk the plank if ye want to leave, arrrgh! +WAVE_DEFAULT=Wave %: Blow them all down! +WAVE_SPECIAL=Wave %: Thar she blows! +WAVE_REWARD=Ye earned yerself some booty: % +MISC_LIST_ARENAS=Ships: % +MISC_LIST_PLAYERS=Buccaneers: % +MISC_COMMAND_NOT_ALLOWED=Ye can't be usin' that command on the ship, landlubber! +MISC_NO_ACCESS=Only the captain uses these commands, wench! +MISC_NONE= diff --git a/src/com/garbagemule/MobArena/AbstractArena.java b/src/com/garbagemule/MobArena/AbstractArena.java new file mode 100644 index 0000000..f7a6122 --- /dev/null +++ b/src/com/garbagemule/MobArena/AbstractArena.java @@ -0,0 +1,40 @@ +package com.garbagemule.MobArena; + +import org.bukkit.entity.Player; + +public abstract class AbstractArena +{ + /** + * Start the arena session. + * This method should warp all players to their respective warp points, start all + * needed timers, clear/populate all sets and lists, and flag all booleans. + */ + public abstract void startArena(); + + /** + * Stop the arena session. + * Distribute rewards, clean up arena floor and reset everything to how it was before + * the arena session was started. + */ + public abstract void endArena(); + + /** + * Player joins the arena/lobby. + */ + public abstract void playerJoin(Player p); + + /** + * Player leaves the arena/lobby. + */ + public abstract void playerLeave(Player p); + + /** + * Player dies in the arena. + */ + public abstract void playerDeath(Player p); + + /** + * Player signals that they are ready. + */ + public abstract void playerReady(Player p); +} diff --git a/src/com/garbagemule/MobArena/Arena.java b/src/com/garbagemule/MobArena/Arena.java index e604e62..5fc08da 100644 --- a/src/com/garbagemule/MobArena/Arena.java +++ b/src/com/garbagemule/MobArena/Arena.java @@ -5,11 +5,13 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.sql.Timestamp; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Random; import java.util.Set; import org.bukkit.Bukkit; @@ -51,6 +53,7 @@ import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; import org.bukkit.util.config.Configuration; import com.garbagemule.MobArena.MAMessages.Msg; @@ -62,58 +65,76 @@ public class Arena // Setup fields protected String name; protected World world; - protected boolean enabled, running, setup, protect, autoEquip, forceRestore, softRestore, softRestoreDrops, emptyInvJoin, emptyInvSpec, pvp, monsterInfight, allowWarp; - protected boolean edit, waveClear, detCreepers, detDamage, lightning, hellhounds; - protected Location p1, p2, arenaLoc, lobbyLoc, spectatorLoc; + protected boolean enabled, protect, logging, running, setup, lobbySetup, autoEquip, forceRestore, softRestore, softRestoreDrops, emptyInvJoin, emptyInvSpec, pvp, monsterInfight, allowWarp; + protected boolean edit, waveClear, detCreepers, detDamage, lightning, hellhounds, specOnDeath, shareInArena; + protected Location p1, p2, l1, l2, arenaLoc, lobbyLoc, spectatorLoc; protected Map spawnpoints; - // Wave/reward fields + // Wave/reward/entryfee fields protected int spawnTaskId, waveDelay, waveInterval, specialModulo, spawnMonstersInt, maxIdleTime; protected MASpawnThread spawnThread; protected Map> everyWaveMap, afterWaveMap; protected Map distDefault, distSpecial; protected Map classMap; protected Map> classItems, classArmor; + protected Map>> classBonuses; protected Map> rewardMap; + protected List entryFee; // Arena sets/maps - protected Set livePlayers, deadPlayers, readyPlayers, specPlayers; + protected Set /*livePlayers, */deadPlayers, readyPlayers, specPlayers, waitPlayers, hasPaid, arenaPlayers, lobbyPlayers, notifyPlayers, randoms; protected Set monsters; protected Set blocks; protected Set pets; protected Map petMap; - protected Map kills; protected List repairList; // Spawn overriding protected int spawnMonsters; protected boolean allowMonsters, allowAnimals; - // Global settings - protected int repairDelay; + // Other settings + protected int repairDelay, playerLimit, joinDistance; protected List classes = new LinkedList(); protected Map locations = new HashMap(); + // Logging + protected ArenaLog log; + protected List classDistribution = new LinkedList(); + protected Map waveMap = new HashMap(); + protected Map killMap = new HashMap(); + protected Timestamp startTime; + protected Timestamp endTime; + /** * Primary constructor. Requires a name and a world. */ public Arena(String name, World world) { + if (world == null) + throw new NullPointerException("[MobArena] ERROR! World for arena '" + name + "' does not exist!"); + this.name = name; this.world = world; plugin = (MobArena) Bukkit.getServer().getPluginManager().getPlugin("MobArena"); + log = new ArenaLog(plugin, this); - livePlayers = new HashSet(); + arenaPlayers = new HashSet(); + lobbyPlayers = new HashSet(); + notifyPlayers = new HashSet(); + //livePlayers = new HashSet(); deadPlayers = new HashSet(); readyPlayers = new HashSet(); specPlayers = new HashSet(); + waitPlayers = new HashSet(); + hasPaid = new HashSet(); monsters = new HashSet(); blocks = new HashSet(); pets = new HashSet(); petMap = new HashMap(); classMap = new HashMap(); + randoms = new HashSet(); rewardMap = new HashMap>(); - kills = new HashMap(); repairList = new LinkedList(); running = false; @@ -124,23 +145,71 @@ public class Arena spawnMonsters = ((net.minecraft.server.World) ((CraftWorld) world).getHandle()).spawnMonsters; } - public Arena(String name, World world, ArenaMaster am) + public boolean startArena() { - this(name, world); - //classItems = am.classItems; - //classArmor = am.classArmor; + // Sanity-checks + if (running || lobbyPlayers.isEmpty() || !lobbyPlayers.equals(readyPlayers)) + return false; + if (!softRestore && forceRestore && !serializeRegion()) + return false; + + // Populate arenaPlayers and clear the lobby. + arenaPlayers.addAll(lobbyPlayers); + lobbyPlayers.clear(); + readyPlayers.clear(); + + // Assign random classes. + for (Player p : randoms) + assignRandomClass(p); + if (arenaPlayers.isEmpty()) + return false; + + // Teleport players, give full health, initialize maps + for (Player p : arenaPlayers) + { + p.teleport(arenaLoc); + p.setHealth(20); + rewardMap.put(p, new LinkedList()); + waveMap.put(p, 0); + killMap.put(p, 0); + } + + // Spawn pets. + spawnPets(); + + // Start spawning monsters. + startSpawning(); + + // Start logging + if (logging) + log.start(); + + // Set the boolean. + running = true; + + // Announce and notify. + MAUtils.tellAll(this, MAMessages.get(Msg.ARENA_START)); + for (MobArenaListener listener : plugin.getAM().listeners) + listener.onArenaStart(); + + return true; } - public void startArena() - { + /*public void startArena() + { if (running) return; if (!softRestore && forceRestore && !serializeRegion()) return; + // Assign random classes, and if all get kicked, return. + for (Player p : randoms) + assignRandomClass(p); + if (livePlayers.isEmpty()) + return; + // Set the spawn flags to enable monster spawning. - //MAUtils.setSpawnFlags(plugin, world, 1, true, true); MAUtils.setSpawnFlags(plugin, world, 1, allowMonsters, allowAnimals); // Teleport players. @@ -149,6 +218,8 @@ public class Arena p.teleport(arenaLoc); p.setHealth(20); rewardMap.put(p, new LinkedList()); + waveMap.put(p, 0); + killMap.put(p, 0); } running = true; @@ -156,7 +227,10 @@ public class Arena // Spawn pets. for (Map.Entry entry : petMap.entrySet()) { + // Remove the bones from the inventory. Player p = entry.getKey(); + p.getInventory().removeItem(new ItemStack(Material.BONE, entry.getValue())); + for (int i = 0; i < entry.getValue(); i++) { Wolf wolf = (Wolf) world.spawnCreature(p.getLocation(), CreatureType.WOLF); @@ -170,24 +244,83 @@ public class Arena } // Start the spawnThread. - spawnThread = new MASpawnThread(plugin, this); - spawnTaskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, spawnThread, waveDelay, waveInterval); + spawnThread = new MASpawnThread(plugin, this); + spawnTaskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, spawnThread, waveDelay, (!waveClear) ? waveInterval : 60); readyPlayers.clear(); + + // Logging info. + if (logging) + log.start(); + MAUtils.tellAll(this, MAMessages.get(Msg.ARENA_START)); // Notify listeners. for (MobArenaListener listener : plugin.getAM().listeners) listener.onArenaStart(); + }*/ + + public boolean endArena() + { + // Sanity-checks. + if (!running || !arenaPlayers.isEmpty()) + return false; + + // Stop spawning. + stopSpawning(); + + // Set the boolean. + running = false; + + // Stop logging. + if (logging) + { + log.end(); + log.serialize(); + log.clear(); + } + + // Clean arena floor. + cleanup(); + + // Restore region. + if (softRestore) + for (int[] buffer : repairList) + world.getBlockAt(buffer[0], buffer[1], buffer[2]).setTypeIdAndData(buffer[3], (byte) buffer[4], false); + else if (forceRestore) + deserializeRegion(); + + // Announce and clear sets. + MAUtils.tellAll(this, MAMessages.get(Msg.ARENA_END), true); + arenaPlayers.clear(); + notifyPlayers.clear(); + classMap.clear(); + rewardMap.clear(); + + // Notify listeners. + for (MobArenaListener listener : plugin.getAM().listeners) + listener.onArenaEnd(); + + return true; } /** * End this arena's session. */ - public void endArena() + /*public void endArena() { running = false; + MAUtils.tellAll(this, MAMessages.get(Msg.ARENA_END), true); + + // Logging stuff + if (logging) + { + log.end(); + log.serialize(); + log.clear(); + } + // If the arena was actually ever started, cancel the spawnthread. if (spawnThread != null) { @@ -206,6 +339,7 @@ public class Arena // Clear all the sets and maps. livePlayers.clear(); deadPlayers.clear(); + waitPlayers.clear(); pets.clear(); classMap.clear(); rewardMap.clear(); @@ -218,12 +352,11 @@ public class Arena // Set the spawn flags to restore monster spawning. MAUtils.setSpawnFlags(plugin, world, spawnMonsters, allowMonsters, allowAnimals); - MAUtils.tellAll(this, MAMessages.get(Msg.ARENA_END)); // Notify listeners. for (MobArenaListener listener : plugin.getAM().listeners) listener.onArenaEnd(); - } + }*/ /** * Force an arena start by forcing all not-ready players to leave. @@ -233,33 +366,74 @@ public class Arena { // Set operations. Set tmp = new HashSet(); - tmp.addAll(livePlayers); + //tmp.addAll(livePlayers); tmp.removeAll(readyPlayers); // Force leave. for (Player p : tmp) + { + plugin.getAM().arenaMap.remove(p); playerLeave(p); + } } /** * Force an arena end by forcing all players to leave. * @precondition - livePlayers must not be empty. */ - public void forceEnd() + /*public void forceEnd() { // Force leave. for (Player p : getAllPlayers()) + { + plugin.getAM().arenaMap.remove(p); playerLeave(p); + } + }*/ + + public void forceEnd() + { + for (Player p : getAllPlayers()) + { + plugin.getAM().arenaMap.remove(p); + playerLeave(p); + } } - /** - * Warp the player to the arena lobby and add to the set of live players. - */ public void playerJoin(Player p, Location loc) { if (!locations.containsKey(p)) locations.put(p,loc); + // Update chunk. + updateChunk(lobbyLoc); + + MAUtils.sitPets(p); + lobbyPlayers.add(p); + p.teleport(lobbyLoc); + + // Notify listeners. + for (MobArenaListener listener : plugin.getAM().listeners) + listener.onPlayerJoin(p); + } + + /** + * Warp the player to the arena lobby and add to the set of live players. + */ + /*public void playerJoin(Player p, Location loc) + { + if (!locations.containsKey(p)) + locations.put(p,loc); + + if (livePlayers.isEmpty()) + { + Chunk chunk = world.getChunkAt(lobbyLoc); + if (!world.isChunkLoaded(chunk)) + world.loadChunk(chunk); + else + world.refreshChunk(chunk.getX(), chunk.getZ()); + } + MAUtils.sitPets(p); livePlayers.add(p); p.teleport(lobbyLoc); @@ -267,19 +441,25 @@ public class Arena // Notify listeners. for (MobArenaListener listener : plugin.getAM().listeners) listener.onPlayerJoin(p); - } + }*/ /** * Add the player to the set of ready players. * If every is ready, the arena starts. */ public void playerReady(Player p) + { + readyPlayers.add(p); + startArena(); + } + + /*public void playerReady(Player p) { readyPlayers.add(p); if (readyPlayers.equals(livePlayers)) startArena(); - } + }*/ /** * Remove the player from all the player sets, and clear his inventory if necessary. @@ -287,21 +467,101 @@ public class Arena * If the set of ready players becomes equal to the set of live players, start the arena. */ public void playerLeave(Player p) + { + // Clear class inventory, restore old inventory and fork over rewards. + restoreInvAndGiveRewards(p, !specPlayers.contains(p)); + + // Grab the player's entry location, and warp them there. + Location entry = locations.get(p); + if (entry != null) + { + updateChunk(entry); + p.teleport(entry); + } + locations.remove(p); + + // Remove from the arenaMap and all the sets. + plugin.getAM().arenaMap.remove(p); + removePlayer(p); + + // End the arena if conditions are met. + endArena(); + } + + public void playerDeath(final Player p) + { + // If spectate-on-death: false, pass on to playerLeave. + if (!specOnDeath) + { + p.teleport(arenaLoc); + playerLeave(p); + return; + } + + // Clear class inventory, restore old inventory and fork over rewards. + restoreInvAndGiveRewards(p, true); + + // Remove player from sets, warp to spectator area, then add to specPlayers. + removePlayer(p); + p.teleport(arenaLoc); // This will sometimes force players to drop any items held (not confirmed) + p.teleport(spectatorLoc); + specPlayers.add(p); + + // Update the monster targets. + if (running && spawnThread != null) + spawnThread.updateTargets(); + + // Announce and notify + MAUtils.tellAll(this, MAMessages.get(Msg.PLAYER_DIED, p.getName())); + for (MobArenaListener listener : plugin.getAM().listeners) + listener.onPlayerDeath(p); + + // End the arena if conditions are met. + endArena(); + } + + /*public void playerLeave(Player p) { boolean clear = false; - p.teleport(locations.get(p)); + Location old = locations.get(p); + if (old != null) + { + Chunk chunk = old.getWorld().getChunkAt(old); + if (!old.getWorld().isChunkLoaded(chunk)) + old.getWorld().loadChunk(chunk); + else + old.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); + + p.teleport(old); + } locations.remove(p); // get, then remove, because of Teleport Event // Only clear the inventory if the player has class items. if (readyPlayers.remove(p)) clear = true; if (livePlayers.remove(p)) clear = true; - if (deadPlayers.remove(p)) clear = false; - if (specPlayers.remove(p)) clear = false; + deadPlayers.remove(p); + specPlayers.remove(p); + hasPaid.remove(p); removePets(p); - if (clear) MAUtils.clearInventory(p); - if (!emptyInvJoin) MAUtils.restoreInventory(p); + // Update the monster targets. + if (running && spawnThread != null) + spawnThread.updateTargets(); + + // Clear inventory and record current wave + if (clear) + { + if (running) waveMap.put(p, spawnThread.wave - 1); + MAUtils.clearInventory(p); + } + + // Try to restore inventory. + if (!emptyInvJoin) + MAUtils.restoreInventory(p); + + // Grant rewards. + MAUtils.giveRewards(p, rewardMap.get(p), plugin); if (running && livePlayers.isEmpty()) endArena(); @@ -311,25 +571,11 @@ public class Arena // Notify listeners. for (MobArenaListener listener : plugin.getAM().listeners) listener.onPlayerLeave(p); - } + }*/ - public void playerQuit(Player p) - { - p.teleport(locations.get(p)); - readyPlayers.remove(p); - livePlayers.remove(p); - deadPlayers.remove(p); - specPlayers.remove(p); - removePets(p); - - if (running && livePlayers.isEmpty()) - endArena(); - else if (!readyPlayers.isEmpty() && readyPlayers.equals(livePlayers)) - startArena(); - } - - public void playerDeath(final Player p) + /*public void playerDeath(final Player p) { + p.teleport(arenaLoc); // This will sometimes force players to drop any items held (not confirmed) p.teleport(spectatorLoc); p.setFireTicks(0); p.setHealth(20); @@ -338,23 +584,35 @@ public class Arena livePlayers.remove(p); deadPlayers.add(p); removePets(p); + + // Update the monster targets. + if (running && spawnThread != null) + spawnThread.updateTargets(); // Has to be delayed for TombStone not to fuck shit up. - if (running && livePlayers.isEmpty()) Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, - new Runnable() + new Runnable() + { + public void run() { - public void run() + if (!specOnDeath) { - MAUtils.restoreInventory(p); - endArena(); + plugin.getAM().arenaMap.remove(p); + playerLeave(p); } - }, 10); + else MAUtils.restoreInventory(p); + + if (livePlayers.isEmpty()) + endArena(); + } + }, 8); + + MAUtils.tellAll(this, MAMessages.get(Msg.PLAYER_DIED, p.getName())); // Notify listeners. for (MobArenaListener listener : plugin.getAM().listeners) listener.onPlayerDeath(p); - } + }*/ public void playerSpec(Player p, Location loc) { @@ -366,9 +624,107 @@ public class Arena p.teleport(spectatorLoc); } - public void playerKill(Player p, LivingEntity e) + public void removePlayer(Player p) { - kills.put(p, kills.get(p) + 1); + // Heal and put out fire. + p.setFireTicks(0); + p.setHealth(20); + + // Remove pets. + removePets(p); + + // readyPlayers before lobbyPlayers because of startArena sanity-checks + readyPlayers.remove(p); + specPlayers.remove(p); + arenaPlayers.remove(p); + lobbyPlayers.remove(p); + + // arenaPlayers is empty if lobbyPlayers isn’t, and vice versa + /*if (arenaPlayers.remove(p)) + endArena2(); + if (lobbyPlayers.remove(p)) + startArena2();*/ + } + + public void spawnPets() + { + for (Map.Entry entry : petMap.entrySet()) + { + // Remove the bones from the inventory. + Player p = entry.getKey(); + p.getInventory().removeItem(new ItemStack(Material.BONE, entry.getValue())); + + // Spawn wolves, set owner and health, and add to pet set. + for (int i = 0; i < entry.getValue(); i++) + { + Wolf wolf = (Wolf) world.spawnCreature(p.getLocation(), CreatureType.WOLF); + wolf.setTamed(true); + wolf.setOwner(p); + wolf.setHealth(20); + if (hellhounds) + wolf.setFireTicks(32768); + pets.add(wolf); + } + } + } + + public void startSpawning() + { + // Set the spawn flags to enable monster spawning. + MAUtils.setSpawnFlags(plugin, world, 1, allowMonsters, allowAnimals); + + // Start the spawnThread. + spawnThread = new MASpawnThread(plugin, this); + spawnTaskId = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, spawnThread, waveDelay, (!waveClear) ? waveInterval : 60); + } + + public void stopSpawning() + { + // Stop the spawn thread. + if (spawnThread != null) + { + Bukkit.getServer().getScheduler().cancelTask(spawnThread.taskId); + Bukkit.getServer().getScheduler().cancelTask(spawnTaskId); + } + + // Restore spawn flags. + MAUtils.setSpawnFlags(plugin, world, spawnMonsters, allowMonsters, allowAnimals); + } + + public void updateChunk(Location loc) + { + if (!arenaPlayers.isEmpty()) + return; + + Chunk chunk = world.getChunkAt(lobbyLoc); + if (!world.isChunkLoaded(chunk)) + world.loadChunk(chunk); + else + world.refreshChunk(chunk.getX(), chunk.getZ()); + } + + public void playerKill(Player p) + { + killMap.put(p, killMap.get(p) + 1); + } + + public void restoreInvAndGiveRewards(final Player p, final boolean clear) + { + final List rewards = rewardMap.get(p); + + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, + new Runnable() + { + public void run() + { + if (clear) + MAUtils.clearInventory(p); + + if (!emptyInvJoin) + MAUtils.restoreInventory(p); + MAUtils.giveRewards(p, rewards, plugin); + } + }); } @@ -383,20 +739,50 @@ public class Arena { petMap.remove(p); classMap.put(p, className); + MAUtils.clearInventory(p); - MAUtils.giveItems(p, classItems.get(className), autoEquip); - MAUtils.giveItems(p, classArmor.get(className), autoEquip); + + // If random, don't give any items yet. + if (className.equalsIgnoreCase("random")) + { + randoms.add(p); + return; + } + + MAUtils.giveItems(p, classItems.get(className), autoEquip, plugin); + MAUtils.giveItems(p, classArmor.get(className), autoEquip, plugin); int pets = MAUtils.getPetAmount(p); if (pets > 0) petMap.put(p, pets); } - private void giveRewards() + public void assignRandomClass(Player p) { + Random r = new Random(); + List classes = new LinkedList(plugin.getAM().classes); + + String className = classes.remove(r.nextInt(classes.size())); + while (!plugin.has(p, "mobarena.classes." + className)) + { + if (classes.isEmpty()) + { + System.out.println("[MobArena] ERROR! Player '" + p.getName() + "' has no class permissions!"); + playerLeave(p); + return; + } + className = classes.remove(r.nextInt(classes.size())); + } + + assignClass(p, className); + MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_CLASS_PICKED, className)); + } + + private void giveRewards() + { for (Map.Entry> entry : rewardMap.entrySet()) { MAUtils.tellPlayer(entry.getKey(), MAMessages.get(Msg.REWARDS_GIVE)); - MAUtils.giveRewards(entry.getKey(), entry.getValue()); + MAUtils.giveRewards(entry.getKey(), entry.getValue(), plugin); } } @@ -426,14 +812,23 @@ public class Arena private void removePets() { for (Wolf w : pets) + { + w.setOwner(null); w.remove(); + } } private void removePets(Player p) { for (Wolf w : pets) - if (w.getOwner().equals(p)) - w.remove(); + { + if (!((Player) w.getOwner()).getName().equals(p.getName())) + continue; + + w.setOwner(null); + w.remove(); + } + petMap.remove(p); } private void removeEntities() @@ -465,6 +860,7 @@ public class Arena enabled = config.getBoolean(arenaPath + "enabled", true); protect = config.getBoolean(arenaPath + "protect", true); + logging = config.getBoolean(arenaPath + "logging", false); autoEquip = config.getBoolean(arenaPath + "auto-equip-armor", true); waveClear = config.getBoolean(arenaPath + "clear-wave-before-next", false); detCreepers = config.getBoolean(arenaPath + "detonate-creepers", false); @@ -473,12 +869,16 @@ public class Arena forceRestore = config.getBoolean(arenaPath + "force-restore", false); softRestore = config.getBoolean(arenaPath + "soft-restore", false); softRestoreDrops = config.getBoolean(arenaPath + "soft-restore-drops", false); - emptyInvJoin = config.getBoolean(arenaPath + "require-empty-inv-join", false); - emptyInvSpec = config.getBoolean(arenaPath + "require-empty-inv-spec", false); + emptyInvJoin = config.getBoolean(arenaPath + "require-empty-inv-join", true); + emptyInvSpec = config.getBoolean(arenaPath + "require-empty-inv-spec", true); hellhounds = config.getBoolean(arenaPath + "hellhounds", false); pvp = config.getBoolean(arenaPath + "pvp-enabled", false); monsterInfight = config.getBoolean(arenaPath + "monster-infight", false); allowWarp = config.getBoolean(arenaPath + "allow-teleporting", false); + specOnDeath = config.getBoolean(arenaPath + "spectate-on-death", true); + shareInArena = config.getBoolean(arenaPath + "share-items-in-arena", true); + joinDistance = config.getInt(arenaPath + "max-join-distance", 0); + playerLimit = config.getInt(arenaPath + "player-limit", 0); repairDelay = config.getInt(arenaPath + "repair-delay", 5); waveDelay = config.getInt(arenaPath + "first-wave-delay", 5) * 20; waveInterval = config.getInt(arenaPath + "wave-interval", 20) * 20; @@ -489,9 +889,12 @@ public class Arena distSpecial = MAUtils.getArenaDistributions(config, configName, "special"); everyWaveMap = MAUtils.getArenaRewardMap(config, configName, "every"); afterWaveMap = MAUtils.getArenaRewardMap(config, configName, "after"); + entryFee = MAUtils.getEntryFee(config, configName); p1 = MAUtils.getArenaCoord(config, world, configName, "p1"); p2 = MAUtils.getArenaCoord(config, world, configName, "p2"); + l1 = MAUtils.getArenaCoord(config, world, configName, "l1"); + l2 = MAUtils.getArenaCoord(config, world, configName, "l2"); arenaLoc = MAUtils.getArenaCoord(config, world, configName, "arena"); lobbyLoc = MAUtils.getArenaCoord(config, world, configName, "lobby"); spectatorLoc = MAUtils.getArenaCoord(config, world, configName, "spectator"); @@ -503,17 +906,20 @@ public class Arena // Determine if the arena is properly set up. Then add the to arena list. setup = MAUtils.verifyData(this); + lobbySetup = MAUtils.verifyLobby(this); } public void serializeConfig() { - String coords = "arenas." + configName() + ".coords."; + String coords = "arenas." + configName() + ".coords."; Configuration config = plugin.getConfig(); config.setProperty("arenas." + configName() + ".settings.enabled", enabled); config.setProperty("arenas." + configName() + ".settings.protect", protect); if (p1 != null) config.setProperty(coords + "p1", MAUtils.makeCoord(p1)); if (p2 != null) config.setProperty(coords + "p2", MAUtils.makeCoord(p2)); + if (l1 != null) config.setProperty(coords + "l1", MAUtils.makeCoord(l1)); + if (l2 != null) config.setProperty(coords + "l2", MAUtils.makeCoord(l2)); if (arenaLoc != null) config.setProperty(coords + "arena", MAUtils.makeCoord(arenaLoc)); if (lobbyLoc != null) config.setProperty(coords + "lobby", MAUtils.makeCoord(lobbyLoc)); if (spectatorLoc != null) config.setProperty(coords + "spectator", MAUtils.makeCoord(spectatorLoc)); @@ -612,16 +1018,26 @@ public class Arena */ public boolean inRegion(Location loc) { - if (!loc.getWorld().getName().equals(world.getName())) + if (!loc.getWorld().getName().equals(world.getName()) || !setup) return false; - if (!setup) - return false; + int x = loc.getBlockX(); + int y = loc.getBlockY(); + int z = loc.getBlockZ(); + + // Check the lobby first. + if (lobbySetup) + { + if ((x >= l1.getBlockX() && x <= l2.getBlockX()) && + (z >= l1.getBlockZ() && z <= l2.getBlockZ()) && + (y >= l1.getBlockY() && y <= l2.getBlockY())) + return true; + } // Returns false if the location is outside of the region. - return ((loc.getX() >= p1.getX() && loc.getX() <= p2.getX()) && - (loc.getZ() >= p1.getZ() && loc.getZ() <= p2.getZ()) && - (loc.getY() >= p1.getY() && loc.getY() <= p2.getY())); + return ((x >= p1.getBlockX() && x <= p2.getBlockX()) && + (z >= p1.getBlockZ() && z <= p2.getBlockZ()) && + (y >= p1.getBlockY() && y <= p2.getBlockY())); } /** @@ -633,9 +1049,22 @@ public class Arena if (!loc.getWorld().getName().equals(world.getName()) || !setup) return false; - return ((loc.getX() + radius >= p1.getX() && loc.getX() - radius <= p2.getX()) && - (loc.getZ() + radius >= p1.getZ() && loc.getZ() - radius <= p2.getZ()) && - (loc.getY() + radius >= p1.getY() && loc.getY() - radius <= p2.getY())); + int x = loc.getBlockX(); + int y = loc.getBlockY(); + int z = loc.getBlockZ(); + + // Check the lobby first. + if (lobbySetup) + { + if ((x + radius >= l1.getBlockX() && x - radius <= l2.getBlockX()) && + (z + radius >= l1.getBlockZ() && z - radius <= l2.getBlockZ()) && + (y + radius >= l1.getBlockY() && y - radius <= l2.getBlockY())) + return true; + } + + return ((x + radius >= p1.getBlockX() && x - radius <= p2.getBlockX()) && + (z + radius >= p1.getBlockZ() && z - radius <= p2.getBlockZ()) && + (y + radius >= p1.getBlockY() && y - radius <= p2.getBlockY())); } @@ -649,14 +1078,14 @@ public class Arena // Block Listener public void onBlockBreak(BlockBreakEvent event) { - if (edit || !inRegion(event.getBlock().getLocation())) + if (!inRegion(event.getBlock().getLocation()) || edit || (!protect && running)) return; Block b = event.getBlock(); if (blocks.remove(b) || b.getType() == Material.TNT) return; - if (softRestore) + if (softRestore && running) { int[] buffer = new int[5]; buffer[0] = b.getX(); @@ -674,12 +1103,12 @@ public class Arena public void onBlockPlace(BlockPlaceEvent event) { - // If in edit mode or the event didn't happen in this region, return. - if (edit || !inRegion(event.getBlock().getLocation())) + if (!inRegion(event.getBlock().getLocation()) || edit) return; Block b = event.getBlock(); - if (running && livePlayers.contains(event.getPlayer())) + //if (running && livePlayers.contains(event.getPlayer())) + if (running && arenaPlayers.contains(event.getPlayer())) { blocks.add(b); Material mat = b.getType(); @@ -708,17 +1137,28 @@ public class Arena if (!monsters.contains(event.getEntity()) && !inRegionRadius(event.getLocation(), 10)) return; + event.setYield(0); + monsters.remove(event.getEntity()); + // If the arena isn't running if (!running || repairDelay == 0) { event.setCancelled(true); return; } + + // If there is a sign in the blocklist, cancel + for (Block b : event.blockList()) + { + if (!(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN)) + continue; + + event.setCancelled(true); + return; + } // Uncancel, just in case. event.setCancelled(false); - event.setYield(0); - monsters.remove(event.getEntity()); int[] buffer; final HashMap blockMap = new HashMap(); @@ -726,6 +1166,9 @@ public class Arena { Material mat = b.getType(); + if (mat == Material.LAVA) b.setType(Material.STATIONARY_LAVA); + else if (mat == Material.WATER) b.setType(Material.STATIONARY_WATER); + if (mat == Material.WOODEN_DOOR || mat == Material.IRON_DOOR_BLOCK || mat == Material.FIRE || mat == Material.CAKE_BLOCK || mat == Material.WATER || mat == Material.LAVA) { blocks.remove(b); @@ -781,10 +1224,11 @@ public class Arena public void onEntityTarget(EntityTargetEvent event) { - if (!running) return; + if (!running || event.isCancelled()) + return; if (pets.contains(event.getEntity())) - { + { if (event.getReason() != TargetReason.TARGET_ATTACKED_OWNER && event.getReason() != TargetReason.OWNER_ATTACKED_TARGET) return; @@ -811,7 +1255,8 @@ public class Arena } if (event.getReason() == TargetReason.CLOSEST_PLAYER) - if (!livePlayers.contains(event.getTarget())) + //if (!livePlayers.contains(event.getTarget())) + if (!arenaPlayers.contains(event.getTarget())) event.setCancelled(true); return; } @@ -822,7 +1267,8 @@ public class Arena { if (!running) return; - if (!(event.getEntity() instanceof Player) || !livePlayers.contains((Player)event.getEntity())) + //if (!(event.getEntity() instanceof Player) || !livePlayers.contains((Player)event.getEntity())) + if (!(event.getEntity() instanceof Player) || !arenaPlayers.contains((Player)event.getEntity())) return; if (event.getRegainReason() == RegainReason.REGEN) @@ -830,24 +1276,31 @@ public class Arena } public void onEntityDeath(EntityDeathEvent event) - { - if (!running) return; - + { if (event.getEntity() instanceof Player) { Player p = (Player) event.getEntity(); - if (!livePlayers.contains(p)) + //if (!livePlayers.contains(p)) + if (!arenaPlayers.contains(p)) return; event.getDrops().clear(); + waveMap.put(p, spawnThread.wave - 1); playerDeath(p); - p.getInventory().clear(); // For TombStone + //p.getInventory().clear(); // For TombStone return; } if (monsters.remove(event.getEntity())) { + EntityDamageEvent e1 = event.getEntity().getLastDamageCause(); + EntityDamageByEntityEvent e2 = (e1 instanceof EntityDamageByEntityEvent) ? (EntityDamageByEntityEvent) e1 : null; + Entity damager = (e2 != null) ? e2.getDamager() : null; + + if (e2 != null && damager instanceof Player) + playerKill((Player) damager); + event.getDrops().clear(); resetIdleTimer(); return; @@ -870,6 +1323,8 @@ public class Arena damagee.setFireTicks(32768); // For mcMMO event.setCancelled(true); } + if (e != null && damager instanceof Player) + event.setCancelled(true); event.setDamage(0); return; @@ -885,7 +1340,8 @@ public class Arena // Damagee & Damager - Player - cancel if pvp disabled if (damagee instanceof Player && damager instanceof Player) { - if (livePlayers.contains(damagee) && !pvp) + //if (livePlayers.contains(damagee) && !pvp) + if (arenaPlayers.contains(damagee) && !pvp) event.setCancelled(true); return; @@ -903,7 +1359,8 @@ public class Arena // Creeper detonations if (inRegion(damagee.getLocation())) { - if (!detDamage || !(damagee instanceof Player) || !livePlayers.contains((Player) damagee)) + //if (!detDamage || !(damagee instanceof Player) || !livePlayers.contains((Player) damagee)) + if (!detDamage || !(damagee instanceof Player) || !arenaPlayers.contains((Player) damagee)) return; if (event.getCause() == DamageCause.BLOCK_EXPLOSION) @@ -916,10 +1373,11 @@ public class Arena // Lobby Listener public void onPlayerDropItem(PlayerDropItemEvent event) { - if (running) return; + if (running && shareInArena) return; Player p = event.getPlayer(); - if (!inRegion(p.getLocation()) || !livePlayers.contains(p)) + //if (!livePlayers.contains(p)) + if (!arenaPlayers.contains(p) && !lobbyPlayers.contains(p)) return; MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_DROP_ITEM)); @@ -928,7 +1386,8 @@ public class Arena public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { - if (!readyPlayers.contains(event.getPlayer()) && !livePlayers.contains(event.getPlayer())) + //if (!readyPlayers.contains(event.getPlayer()) && !livePlayers.contains(event.getPlayer())) + if (!readyPlayers.contains(event.getPlayer()) && !arenaPlayers.contains(event.getPlayer())) return; if (!running) @@ -943,14 +1402,22 @@ public class Arena } public void onPlayerInteract(PlayerInteractEvent event) - { - if (running || !livePlayers.contains(event.getPlayer())) + { + //if (!livePlayers.contains(event.getPlayer())) + if (!arenaPlayers.contains(event.getPlayer()) && !lobbyPlayers.contains(event.getPlayer())) return; - Player p = event.getPlayer(); - Action a = event.getAction(); - if ((a == Action.RIGHT_CLICK_AIR) || (a == Action.RIGHT_CLICK_BLOCK)) + if (running) { + if (event.hasBlock() && event.getClickedBlock().getType() == Material.SAPLING) + addTrunkAndLeaves(event.getClickedBlock()); + return; + } + + Action a = event.getAction(); + Player p = event.getPlayer(); + if (a == Action.RIGHT_CLICK_AIR || a == Action.RIGHT_CLICK_BLOCK) + { event.setUseItemInHand(Result.DENY); event.setCancelled(true); } @@ -984,10 +1451,10 @@ public class Arena // Check if the first line of the sign is a class name. String className = sign.getLine(0); - if (!classes.contains(className)) + if (!classes.contains(className) && !className.equalsIgnoreCase("random")) return; - if (!MobArena.hasDefTrue(p, "mobarena.classes." + className)) + if (!plugin.hasDefTrue(p, "mobarena.classes." + className) && !className.equalsIgnoreCase("random")) { MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_CLASS_PERMISSION)); return; @@ -995,7 +1462,11 @@ public class Arena // Set the player's class. assignClass(p, className); - MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_CLASS_PICKED, className)); + if (!className.equalsIgnoreCase("random")) + MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_CLASS_PICKED, className)); + else + MAUtils.tellPlayer(p, MAMessages.get(Msg.LOBBY_CLASS_RANDOM)); + return; } } @@ -1004,21 +1475,25 @@ public class Arena public void onPlayerQuit(PlayerQuitEvent event) { Player p = event.getPlayer(); - if (!enabled || !getAllPlayers().contains(p)) + //if (!enabled || !livePlayers.contains(p)) + if (!enabled || (!arenaPlayers.contains(p) && !lobbyPlayers.contains(p))) return; - MAUtils.clearInventory(p); - playerQuit(p); + //MAUtils.clearInventory(p); + plugin.getAM().arenaMap.remove(p); + playerLeave(p); } public void onPlayerKick(PlayerKickEvent event) { Player p = event.getPlayer(); - if (!enabled || !getAllPlayers().contains(p)) + //if (!enabled || !livePlayers.contains(p)) + if (!enabled || (!arenaPlayers.contains(p) && !lobbyPlayers.contains(p))) return; - MAUtils.clearInventory(p); - playerQuit(p); + //MAUtils.clearInventory(p); + plugin.getAM().arenaMap.remove(p); + playerLeave(p); } // Teleport Listener @@ -1035,7 +1510,8 @@ public class Arena Location to = event.getTo(); Location from = event.getFrom(); - if (livePlayers.contains(p)) + //if (livePlayers.contains(p) || specPlayers.contains(p)) + if (arenaPlayers.contains(p) || lobbyPlayers.contains(p) || specPlayers.contains(p)) { if (inRegion(from)) { @@ -1073,7 +1549,8 @@ public class Arena { Player p = event.getPlayer(); - if (!livePlayers.contains(p)) + //if (!livePlayers.contains(p)) + if (!arenaPlayers.contains(p) && !lobbyPlayers.contains(p)) return; String[] args = event.getMessage().split(" "); @@ -1104,26 +1581,37 @@ public class Arena return name; } - public List getAllPlayers() + /*public List getAllPlayers() { List result = new LinkedList(); result.addAll(livePlayers); result.addAll(deadPlayers); result.addAll(specPlayers); return result; + }*/ + + public List getAllPlayers() + { + List result = new LinkedList(); + result.addAll(arenaPlayers); + result.addAll(lobbyPlayers); + result.addAll(specPlayers); + return result; } public List getLivingPlayers() { List result = new LinkedList(); - result.addAll(livePlayers); + //result.addAll(livePlayers); + result.addAll(arenaPlayers); return result; } public List getNonreadyPlayers() { List result = new LinkedList(); - result.addAll(livePlayers); + //result.addAll(livePlayers); + result.addAll(lobbyPlayers); result.removeAll(readyPlayers); return result; } @@ -1156,17 +1644,137 @@ public class Arena // Compare the current size with the previous size. if (monsters.size() < spawnThread.previousSize || spawnThread.previousSize == 0) + { + resetIdleTimer(); return; + } // Clear all player inventories, and "kill" all players. - for (Player p : livePlayers) + //for (Player p : livePlayers) + for (Player p : arenaPlayers) { MAUtils.clearInventory(p); - playerDeath(p); MAUtils.tellPlayer(p, MAMessages.get(Msg.FORCE_END_IDLE)); + playerDeath(p); } } - }, maxIdleTime*20); + }, maxIdleTime); + } + + public void delayRestoreInventory(final Player p, final String method) + { + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, + new Runnable() + { + public void run() + { + if (method.equals("restoreInventory")) + MAUtils.restoreInventory(p); + else if (method.equals("giveRewards")) + MAUtils.giveRewards(p, rewardMap.get(p), plugin); + } + }, 10); + } + + public void addTrunkAndLeaves(Block b) + { + final int x = b.getX(); + final int y = b.getY(); + final int z = b.getZ(); + + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, + new Runnable() + { + public void run() + { + List result = new LinkedList(); + for (int i = x-2; i <= x+2; i++) + for (int j = y; j <= y+10; j++) + for (int k = z-2; k <= z+2; k++) + if (world.getBlockAt(i,j,k).getType() == Material.LOG || world.getBlockAt(i,j,k).getType() == Material.LEAVES) + result.add(world.getBlockAt(i,j,k)); + + if (running) blocks.addAll(result); + } + }, 10); + } + + public boolean canAfford(Player p) + { + if (entryFee.isEmpty()) + return true; + + PlayerInventory inv = p.getInventory(); + for (ItemStack stack : entryFee) + { + // Economy money + if (stack.getTypeId() == MobArena.ECONOMY_MONEY_ID) + { + if (plugin.Methods.hasMethod() && !plugin.Method.getAccount(p.getName()).hasEnough(stack.getAmount())) + return false; + } + // Normal stack + else + { + if (!inv.contains(stack.getTypeId(), stack.getAmount())) + return false; + } + } + + return true; + } + + public boolean takeFee(Player p) + { + if (entryFee.isEmpty()) + return true; + + PlayerInventory inv = p.getInventory(); + for (ItemStack stack : entryFee) + { + // Economy money + if (stack.getTypeId() == MobArena.ECONOMY_MONEY_ID) + { + if (plugin.Methods.hasMethod() && !plugin.Method.getAccount(p.getName()).subtract(stack.getAmount())) + return false; + } + + // Normal stack + else + { + int id = stack.getTypeId(); + int amount = stack.getAmount(); + + while (amount > 0) + { + int pos = inv.first(id); + if (pos == -1) return false; + + ItemStack is = inv.getItem(pos); + if (is.getAmount() > amount) + { + is.setAmount(is.getAmount() - amount); + amount = 0; + } + else + { + amount -= is.getAmount(); + inv.setItem(pos, null); + } + } + } + } + + hasPaid.add(p); + return true; + } + + public void refund(Player p) + { + if (!hasPaid.contains(p)) + return; + + MAUtils.giveItems(p, entryFee, false, plugin); } /** diff --git a/src/com/garbagemule/MobArena/ArenaLog.java b/src/com/garbagemule/MobArena/ArenaLog.java new file mode 100644 index 0000000..3da9500 --- /dev/null +++ b/src/com/garbagemule/MobArena/ArenaLog.java @@ -0,0 +1,137 @@ +package com.garbagemule.MobArena; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.sql.Timestamp; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.bukkit.entity.Player; + +public class ArenaLog +{ + protected MobArena plugin; + protected Arena arena; + protected List log, classDistribution; + protected Timestamp startTime, endTime; + + public ArenaLog(MobArena plugin, Arena arena) + { + this.plugin = plugin; + this.arena = arena; + log = new LinkedList(); + classDistribution = new LinkedList(); + } + + public void start() + { + startTime = new Timestamp((new Date()).getTime()); + + // Class distribution + int length = 0; + for (String c : plugin.getAM().classes) + if (c.length() > length) + length = c.length(); + + List classList = new LinkedList(arena.classMap.values()); + for (String c : plugin.getAM().classes) + { + int count = 0; + int id = classList.indexOf(c); + while (id != -1) + { + classList.remove(id); + count++; + id = classList.indexOf(c); + } + //int percentage = (int) (((double) count) / ((double) arena.livePlayers.size())) * 100; + int percentage = (int) (((double) count) / ((double) arena.arenaPlayers.size())) * 100; + classDistribution.add(MAUtils.padRight(c + ": ", length + 2) + MAUtils.padLeft("" + count, 2) + " (" + percentage + "%)"); + } + } + + public void end() + { + endTime = new Timestamp((new Date()).getTime()); + + // General stuff + log.add("--------------------------------------------------- ENTRY ---"); + log.add("Start: " + startTime); + log.add("End: " + endTime); + log.add("Duration: " + MAUtils.getDuration(endTime.getTime() - startTime.getTime())); + log.add("Last wave: " + (arena.spawnThread.wave - 1)); + log.add(" "); + + // Class distribution + log.add("Class Distribution: " + plugin.getAM().classes.size() + " classes"); + for (String c : classDistribution) + log.add("- " + c); + classDistribution.clear(); + log.add(" "); + + // Player data + int NAME = 12; + int CLASS = 0; + int WAVE = 4; + int KILLS = 5; + for (String c : plugin.getAM().classes) + if (c.length() > CLASS) + CLASS = c.length(); + + log.add("Player Data: " + arena.classMap.keySet().size() + " players"); + log.add("- " + MAUtils.padRight("Name", NAME + 2, ' ') + MAUtils.padRight("Class", CLASS + 2, ' ') + MAUtils.padRight("Wave", WAVE + 2, ' ') + MAUtils.padRight("Kills", KILLS + 2, ' ') + "Rewards"); + for (Map.Entry entry : arena.classMap.entrySet()) + { + Player p = entry.getKey(); + StringBuffer buffy = new StringBuffer(); + buffy.append(" "); + // Name + String name = (p.getName().length() <= NAME) ? p.getName() : p.getName().substring(0, NAME+1); + buffy.append(MAUtils.padRight(name, NAME + 2, ' ')); + // Class + buffy.append(MAUtils.padRight(entry.getValue(), CLASS + 2, ' ')); + // Wave + buffy.append(MAUtils.padLeft(arena.waveMap.remove(p).toString(), WAVE, ' ') + " "); + // Kills + buffy.append(MAUtils.padLeft(arena.killMap.remove(p).toString(), KILLS, ' ') + " "); + // Rewards + buffy.append(MAUtils.listToString(arena.rewardMap.get(p), plugin)); + log.add(buffy.toString()); + } + + log.add(" "); + } + + public void serialize() + { + try + { + new File(plugin.getDataFolder() + File.separator + "logs").mkdir(); + File logFile = new File(plugin.getDataFolder() + File.separator + "logs" + File.separator + arena.configName() + ".log"); + if (logFile.exists()) + logFile.createNewFile(); + + FileWriter fw = new FileWriter(logFile, true); + BufferedWriter bw = new BufferedWriter(fw); + for (String l : log) + { + bw.write(l); + bw.write(System.getProperty("line.separator")); + } + + bw.close(); + } + catch (Exception e) + { + e.printStackTrace(); + System.out.println("[MobArena] ERROR! Could not create log file!"); + return; + } + } + + public void add(String s) { log.add(s); } + public void clear() { log.clear(); } +} diff --git a/src/com/garbagemule/MobArena/ArenaMaster.java b/src/com/garbagemule/MobArena/ArenaMaster.java index cbfbd07..41119e6 100644 --- a/src/com/garbagemule/MobArena/ArenaMaster.java +++ b/src/com/garbagemule/MobArena/ArenaMaster.java @@ -20,14 +20,15 @@ public class ArenaMaster private MobArena plugin; private Configuration config; protected Arena selectedArena; - protected Lobby masterLobby; + //protected Lobby masterLobby; // Settings - protected boolean enabled, updateNotify, autoEquip, emptyInvs, hellhounds; + protected boolean enabled, updateNotify; // Classes protected List classes; protected Map> classItems, classArmor; + protected Map>> classBonuses; protected Map arenaMap; // Location map @@ -58,7 +59,16 @@ public class ArenaMaster // /////////////////////////////////////////////////////////////////////////*/ - public Arena getArenaInLocation(Location loc) + public List getEnabledArenas() + { + List result = new LinkedList(); + for (Arena arena : arenas) + if (arena.enabled) + result.add(arena); + return result; + } + + public Arena getArenaAtLocation(Location loc) { for (Arena arena : arenas) if (arena.inRegion(loc)) @@ -197,9 +207,9 @@ public class ArenaMaster config.setProperty("classes.Chef.items", "stone_sword, bread:6, grilled_pork:4, mushroom_soup, cake:3, cookie:12"); config.setProperty("classes.Chef.armor", "314,315,316,317"); } - classes = config.getKeys("classes"); - classItems = MAUtils.getClassItems(config, "items"); - classArmor = MAUtils.getClassItems(config, "armor"); + classes = config.getKeys("classes"); + classItems = MAUtils.getClassItems(config, "items"); + classArmor = MAUtils.getClassItems(config, "armor"); } /** @@ -227,7 +237,7 @@ public class ArenaMaster world = Bukkit.getServer().getWorld(worldName); } - Arena arena = new Arena(MAUtils.nameConfigToArena(configName), world, this); + Arena arena = new Arena(MAUtils.nameConfigToArena(configName), world); arena.load(config); arenas.add(arena); } @@ -247,6 +257,10 @@ public class ArenaMaster config.setProperty("arenas." + configName + ".settings.protect", true); config.save(); config.load(); + config.setProperty("arenas." + configName + ".settings.entry-fee", ""); + config.save(); + config.load(); + config.setProperty("arenas." + configName + ".settings.logging", false); config.setProperty("arenas." + configName + ".settings.clear-wave-before-next", false); config.setProperty("arenas." + configName + ".settings.detonate-creepers", false); config.setProperty("arenas." + configName + ".settings.detonate-damage", false); @@ -255,12 +269,18 @@ public class ArenaMaster config.setProperty("arenas." + configName + ".settings.force-restore", false); config.setProperty("arenas." + configName + ".settings.soft-restore", false); config.setProperty("arenas." + configName + ".settings.soft-restore-drops", false); - config.setProperty("arenas." + configName + ".settings.require-empty-inv-join", false); - config.setProperty("arenas." + configName + ".settings.require-empty-inv-spec", false); + config.setProperty("arenas." + configName + ".settings.require-empty-inv-join", true); + config.setProperty("arenas." + configName + ".settings.require-empty-inv-spec", true); config.setProperty("arenas." + configName + ".settings.hellhounds", false); config.setProperty("arenas." + configName + ".settings.pvp-enabled", false); config.setProperty("arenas." + configName + ".settings.monster-infight", false); config.setProperty("arenas." + configName + ".settings.allow-teleporting", false); + config.setProperty("arenas." + configName + ".settings.spectate-on-death", true); + config.setProperty("arenas." + configName + ".settings.share-items-in-arena", true); + config.save(); + config.load(); + config.setProperty("arenas." + configName + ".settings.player-limit", 0); + config.setProperty("arenas." + configName + ".settings.max-join-distance", 0); config.save(); config.load(); config.setProperty("arenas." + configName + ".settings.repair-delay", 5); @@ -271,7 +291,7 @@ public class ArenaMaster config.save(); config.load(); - Arena arena = new Arena(MAUtils.nameConfigToArena(configName), world, this); + Arena arena = new Arena(MAUtils.nameConfigToArena(configName), world); arena.load(config); return arena; } diff --git a/src/com/garbagemule/MobArena/MACommands.java b/src/com/garbagemule/MobArena/MACommands.java index 6a6439a..d13fc5c 100644 --- a/src/com/garbagemule/MobArena/MACommands.java +++ b/src/com/garbagemule/MobArena/MACommands.java @@ -2,10 +2,14 @@ package com.garbagemule.MobArena; import java.util.List; import java.util.LinkedList; +import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.DyeColor; +import org.bukkit.Material; import org.bukkit.Server; +import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -20,38 +24,43 @@ public class MACommands implements CommandExecutor public static final List COMMANDS = new LinkedList(); static { - COMMANDS.add("j"); // Join - COMMANDS.add("join"); // Join - COMMANDS.add("l"); // Leave - COMMANDS.add("leave"); // Leave - COMMANDS.add("notready"); // List of players who aren't ready - COMMANDS.add("spec"); // Watch arena - COMMANDS.add("spectate"); // Watch arena - COMMANDS.add("arenas"); // List of arenas - COMMANDS.add("list"); // List of players - COMMANDS.add("players"); // List of players - COMMANDS.add("restore"); // Restore inventory - COMMANDS.add("enable"); // Enabling - COMMANDS.add("disable"); // Disabling - COMMANDS.add("protect"); // Protection on/off - COMMANDS.add("force"); // Force start/end - COMMANDS.add("config"); // Reload config - COMMANDS.add("arena"); // Current arena - COMMANDS.add("setarena"); // Set current arena - COMMANDS.add("addarena"); // Add a new arena - COMMANDS.add("delarena"); // Delete current aren - COMMANDS.add("editarena"); // Editing - COMMANDS.add("setregion"); // Set a region point - COMMANDS.add("setwarp"); // Set arena/lobby/spec - COMMANDS.add("spawnpoints"); // List spawnpoints - COMMANDS.add("addspawn"); // Add a spawnpoint - COMMANDS.add("delspawn"); // Delete a spawnpoint - COMMANDS.add("expandregion"); // Expand the region - COMMANDS.add("reset"); // Reset arena coordinates - COMMANDS.add("auto-generate"); // Auto-generate arena - COMMANDS.add("auto-degenerate"); // Restore cuboid + COMMANDS.add("j"); // Join + COMMANDS.add("join"); // Join + COMMANDS.add("l"); // Leave + COMMANDS.add("leave"); // Leave + COMMANDS.add("notready"); // List of players who aren't ready + COMMANDS.add("spec"); // Watch arena + COMMANDS.add("spectate"); // Watch arena + COMMANDS.add("arenas"); // List of arenas + COMMANDS.add("list"); // List of players + COMMANDS.add("players"); // List of players + COMMANDS.add("info"); // Info/help + COMMANDS.add("help"); // Info/help + COMMANDS.add("restore"); // Restore inventory + COMMANDS.add("enable"); // Enabling + COMMANDS.add("disable"); // Disabling + COMMANDS.add("protect"); // Protection on/off + COMMANDS.add("force"); // Force start/end + COMMANDS.add("config"); // Reload config + COMMANDS.add("arena"); // Current arena + COMMANDS.add("setarena"); // Set current arena + COMMANDS.add("addarena"); // Add a new arena + COMMANDS.add("delarena"); // Delete current aren + COMMANDS.add("editarena"); // Editing + COMMANDS.add("setregion"); // Set a region point + COMMANDS.add("expandregion"); // Expand the region + COMMANDS.add("showregion"); // Show the region + COMMANDS.add("setlobbyregion"); // Set a region point + COMMANDS.add("expandlobbyregion"); // Expand the region + COMMANDS.add("setwarp"); // Set arena/lobby/spec + COMMANDS.add("spawnpoints"); // List spawnpoints + COMMANDS.add("addspawn"); // Add a spawnpoint + COMMANDS.add("delspawn"); // Delete a spawnpoint + COMMANDS.add("reset"); // Reset arena coordinates + COMMANDS.add("auto-generate"); // Auto-generate arena + COMMANDS.add("auto-degenerate"); // Restore cuboid } - private boolean player, op, console, meanAdmins; + private boolean meanAdmins, showingRegion; private Server server; private MobArena plugin; private ArenaMaster am; @@ -80,9 +89,9 @@ public class MACommands implements CommandExecutor } // Determine if the sender is a player (and an op), or the console. - player = (sender instanceof Player); - op = player && ((Player) sender).isOp(); - console = (sender instanceof ConsoleCommandSender); + boolean player = (sender instanceof Player); + boolean op = player && ((Player) sender).isOp(); + boolean console = (sender instanceof ConsoleCommandSender); // Cast the sender to Player if possible. Player p = (player) ? (Player)sender : null; @@ -94,6 +103,7 @@ public class MACommands implements CommandExecutor String base = args[0].toLowerCase(); String arg1 = (args.length > 1) ? args[1].toLowerCase() : ""; String arg2 = (args.length > 2) ? args[2].toLowerCase() : ""; + String arg3 = (args.length > 3) ? args[3].toLowerCase() : ""; @@ -108,91 +118,79 @@ public class MACommands implements CommandExecutor */ if (base.equals("join") || base.equals("j")) { - if (!player || !MobArena.has(p, "mobarena.use.join")) + if (!player || !plugin.has(p, "mobarena.use.join")) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; } + List arenas = am.getEnabledArenas(); + if (!am.enabled || arenas.size() < 1) + { + MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); + return true; + } boolean error; + Arena arena; if (!arg1.isEmpty()) - { - Arena arena = am.getArenaWithName(arg1); - - // Crap-load of sanity-checks. - if (!am.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); - else if (arena == null) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); - else if (am.arenaMap.containsKey(p) && am.arenaMap.get(p).livePlayers.contains(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_IN_OTHER_ARENA)); - else if (!arena.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_ENABLED)); - else if (!arena.setup) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_SETUP)); - else if (arena.running) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_IS_RUNNING)); - else if (arena.livePlayers.contains(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ALREADY_PLAYING)); - else if (arena.emptyInvJoin && !MAUtils.hasEmptyInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_EMPTY_INV)); - else if (!arena.emptyInvJoin && !MAUtils.storeInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_STORE_INV_FAIL)); - else error = false; - - // If there was an error, don't join. - if (error) - return true; - - am.arenaMap.put(p,arena); - arena.playerJoin(p, p.getLocation()); - - MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_PLAYER_JOINED)); - return true; - } + arena = am.getArenaWithName(arg1); + else if (arenas.size() == 1) + arena = arenas.get(0); else + arena = null; + + if (arenas.size() > 1 && arg1.isEmpty()) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARG_NEEDED)); + else if (arena == null) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); + //else if (am.arenaMap.containsKey(p) && am.arenaMap.get(p).livePlayers.contains(p)) + else if (am.arenaMap.containsKey(p) && (am.arenaMap.get(p).arenaPlayers.contains(p) || am.arenaMap.get(p).lobbyPlayers.contains(p))) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_IN_OTHER_ARENA)); + else if (!arena.enabled) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_ENABLED)); + else if (!arena.setup || arena.edit) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_SETUP)); + else if (arena.running && arena.waitPlayers.add(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_IS_RUNNING)); + //else if (arena.livePlayers.contains(p)) + else if (arena.arenaPlayers.contains(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ALREADY_PLAYING)); + else if (!plugin.has(p, "mobarena.arenas." + arena.configName())) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_PERMISSION)); + else if (!arena.canAfford(p) || !arena.takeFee(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_FEE_REQUIRED, MAUtils.listToString(arena.entryFee, plugin))); + //else if (arena.playerLimit > 0 && arena.livePlayers.size() >= arena.playerLimit) + else if (arena.playerLimit > 0 && arena.lobbyPlayers.size() >= arena.playerLimit) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_PLAYER_LIMIT_REACHED)); + else if (arena.emptyInvJoin && !MAUtils.hasEmptyInventory(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_EMPTY_INV)); + else if (!arena.emptyInvJoin && !MAUtils.storeInventory(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_STORE_INV_FAIL)); + else if (arena.joinDistance > 0 && !arena.inRegionRadius(p.getLocation(), arena.joinDistance)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_TOO_FAR)); + else error = false; + + // If there was an error, don't join. + if (error) { - if (am.arenas.size() < 1) - { - MAUtils.tellPlayer(sender, "There are no arenas loaded. Check your config-file."); - return true; - } - - Arena arena = am.arenas.get(0); - - if (!am.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); - else if (am.arenas.size() > 1) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARG_NEEDED)); - else if (arena == null) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); - else if (am.arenaMap.containsKey(p) && am.arenaMap.get(p).livePlayers.contains(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_IN_OTHER_ARENA)); - else if (!arena.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_ENABLED)); - else if (!arena.setup) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_SETUP)); - else if (arena.running) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_IS_RUNNING)); - else if (arena.livePlayers.contains(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ALREADY_PLAYING)); - else if (arena.emptyInvJoin && !MAUtils.hasEmptyInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_EMPTY_INV)); - else if (!arena.emptyInvJoin && !MAUtils.storeInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_STORE_INV_FAIL)); - else error = false; - - // If there was an error, don't join. - if (error) - return true; - - am.arenaMap.put(p,arena); - arena.playerJoin(p, p.getLocation()); - - MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_PLAYER_JOINED)); + if (arena != null) + arena.refund(p); return true; } + + // If player is in a boat/minecart, eject! + if (p.isInsideVehicle()) + p.leaveVehicle(); + + am.arenaMap.put(p,arena); + arena.playerJoin(p, p.getLocation()); + + MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_PLAYER_JOINED)); + if (!arena.entryFee.isEmpty()) + MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_FEE_PAID, MAUtils.listToString(arena.entryFee, plugin))); + + return true; } /* @@ -200,7 +198,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("leave") || base.equals("l")) { - if (!player || !MobArena.has(p, "mobarena.use.leave")) + if (!player || !plugin.has(p, "mobarena.use.leave")) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -230,54 +228,60 @@ public class MACommands implements CommandExecutor * Player spectate */ if (base.equals("spectate") || base.equals("spec")) - { - if (!player || !MobArena.has(p, "mobarena.use.spectate")) + { + if (!player || !plugin.has(p, "mobarena.use.spectate")) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; } + List arenas = am.getEnabledArenas(); + if (!am.enabled || arenas.size() < 1) + { + MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); + return true; + } boolean error; - Arena arena = null; + Arena arena; if (!arg1.isEmpty()) - { arena = am.getArenaWithName(arg1); - - if (!am.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); - else if (am.arenaMap.containsKey(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_ALREADY_PLAYING)); - else if (arena == null) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); - else if (arena.emptyInvSpec && !MAUtils.hasEmptyInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_EMPTY_INV)); - else error = false; - - if (error) - return true; - } + else if (arenas.size() == 1) + arena = arenas.get(0); else - { - arena = am.arenas.get(0); - - if (!am.enabled) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_NOT_ENABLED)); - else if (am.arenaMap.containsKey(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_ALREADY_PLAYING)); - else if (am.arenas.size() > 1) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARG_NEEDED)); - else if (arena == null) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); - else if (arena.emptyInvSpec && !MAUtils.hasEmptyInventory(p)) - error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_EMPTY_INV)); - else error = false; - - if (error) - return true; - } - + arena = null; + + if (arenas.size() > 1 && arg1.isEmpty()) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARG_NEEDED)); + else if (arena == null) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); + //else if (am.arenaMap.containsKey(p) && am.arenaMap.get(p).livePlayers.contains(p)) + else if (am.arenaMap.containsKey(p) && (am.arenaMap.get(p).arenaPlayers.contains(p) || am.arenaMap.get(p).lobbyPlayers.contains(p))) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_IN_OTHER_ARENA)); + else if (!arena.enabled) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_ENABLED)); + else if (!arena.setup || arena.edit) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_ARENA_NOT_SETUP)); + //else if (arena.livePlayers.contains(p)) + else if (arena.arenaPlayers.contains(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_ALREADY_PLAYING)); + else if (arena.emptyInvSpec && !MAUtils.hasEmptyInventory(p)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_EMPTY_INV)); + else if (arena.joinDistance > 0 && !arena.inRegionRadius(p.getLocation(), arena.joinDistance)) + error = MAUtils.tellPlayer(p, MAMessages.get(Msg.JOIN_TOO_FAR)); + else error = false; + + // If there was an error, don't spec. + if (error) + return true; + + // If player is in a boat/minecart, eject! + if (p.isInsideVehicle()) + p.leaveVehicle(); + + am.arenaMap.put(p,arena); arena.playerSpec(p, p.getLocation()); + MAUtils.tellPlayer(p, MAMessages.get(Msg.SPEC_PLAYER_SPECTATE)); return true; } @@ -287,7 +291,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("arenas")) { - String list = MAUtils.listToString(am.arenas); + String list = MAUtils.listToString(am.arenas, plugin); MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_LIST_ARENAS, list)); return true; } @@ -306,14 +310,16 @@ public class MACommands implements CommandExecutor return true; } - String list = MAUtils.listToString(arena.getLivingPlayers()); + String list = MAUtils.listToString(arena.getLivingPlayers(), plugin); MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_LIST_PLAYERS, list)); } else { StringBuffer buffy = new StringBuffer(); + List players = new LinkedList(); for (Arena arena : am.arenas) - buffy.append(MAUtils.listToString(arena.getLivingPlayers(), false)); + players.addAll(arena.getLivingPlayers()); + buffy.append(MAUtils.listToString(players, plugin)); MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_LIST_PLAYERS, buffy.toString())); } return true; @@ -349,7 +355,7 @@ public class MACommands implements CommandExecutor return true; } - String list = MAUtils.listToString(arena.getNonreadyPlayers()); + String list = MAUtils.listToString(arena.getNonreadyPlayers(), plugin); MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_LIST_PLAYERS, list)); return true; } @@ -367,7 +373,7 @@ public class MACommands implements CommandExecutor */ if ((base.equals("enable") || base.equals("disable"))) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.enable")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.enable")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -397,33 +403,37 @@ public class MACommands implements CommandExecutor } /* - * Enable or disable protection + * Kick player from whichever arena they are in. */ - if (base.equals("protect")) + if (base.equals("kick")) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.protect")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.kick")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; } - if (arg1.isEmpty() || !arg1.matches("^[a-zA-Z][a-zA-Z0-9_]*$") || !(arg2.equals("true") || arg2.equals("false"))) + + if (arg1.isEmpty()) { - MAUtils.tellPlayer(sender, "Usage: /ma protect [true|false]"); + MAUtils.tellPlayer(sender, "Usage: /ma kick "); return true; } - Arena arena = am.getArenaWithName(arg1); + Arena arena = am.getArenaWithPlayer(arg1); if (arena == null) { - MAUtils.tellPlayer(sender, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); + MAUtils.tellPlayer(sender, "That player is not in an arena."); + return true; + } + else + { + Player pl = server.getPlayer(arg1); + am.arenaMap.remove(pl); + arena.playerLeave(pl); + MAUtils.tellPlayer(sender, "Player '" + arg1 + "' was kicked from arena '" + arena.configName() + "'."); + MAUtils.tellPlayer(pl, "You were kicked by " + ((player) ? p.getName() : "the server.")); return true; } - - arena.protect = arg2.equals("true"); - arena.serializeConfig(); - arena.load(plugin.getConfig()); - MAUtils.tellPlayer(sender, "Protection for arena '" + arg1 + "' set to " + arg2); - return true; } /* @@ -431,7 +441,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("restore")) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.restore")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.restore")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -454,11 +464,11 @@ public class MACommands implements CommandExecutor /* * Force start/end arenas. */ - if (base.equals("force") && arg1.equals("end")) + if (base.equals("force")) { if (arg1.equals("end")) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.force.end")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.force.end")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -480,7 +490,8 @@ public class MACommands implements CommandExecutor return true; } - if (arena.livePlayers.isEmpty()) + //if (arena.livePlayers.isEmpty()) + if (arena.arenaPlayers.isEmpty()) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.FORCE_END_EMPTY)); return true; @@ -492,7 +503,7 @@ public class MACommands implements CommandExecutor } else if (arg1.equals("start")) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.force.start")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.force.start")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -538,7 +549,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("config")) { - if (!console && !(player && MobArena.has(p, "mobarena.admin.config.reload")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.admin.config.reload")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -560,7 +571,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("arena")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.arena")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.arena")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -586,7 +597,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("setarena")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.setarena")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.setarena")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -615,7 +626,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("addarena")) { - if (!(player && MobArena.has(p, "mobarena.setup.addarena")) && !op) + if (!(player && plugin.has(p, "mobarena.setup.addarena")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -643,7 +654,7 @@ public class MACommands implements CommandExecutor if (base.equals("delarena")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.delarena")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.delarena")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -674,28 +685,137 @@ public class MACommands implements CommandExecutor return true; } - if (base.equals("editarena")) + /* + * Enable or disable protection + */ + if (base.equals("protect")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.editarena")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.protect")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; } - if (arg1.isEmpty() || !(arg2.equals("true") || arg2.equals("false"))) + + Arena arena; + + // No arguments + if (arg1.isEmpty()) { - MAUtils.tellPlayer(sender, "Usage: /ma editarena [true|false]"); + arena = am.selectedArena; + arena.protect = !arena.protect; + } + + // One argument + else if (arg2.isEmpty()) + { + // true/false + if (arg1.equals("true") || arg1.equals("false")) + { + arena = am.selectedArena; + arena.protect = arg1.equals("true"); + } + // Arena name + else + { + arena = am.getArenaWithName(arg1); + if (arena == null) + { + MAUtils.tellPlayer(sender, "There is no arena with that name."); + MAUtils.tellPlayer(sender, "Usage: /ma protect ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma protect ([true|false])"); + return true; + } + arena.protect = !arena.protect; + } + } + + // Two arguments + else + { + if (!(arg2.equals("true") || arg2.equals("false"))) + { + MAUtils.tellPlayer(sender, "Usage: /ma protect ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma protect ([true|false])"); + return true; + } + arena = am.getArenaWithName(arg1); + if (arena == null) + { + MAUtils.tellPlayer(sender, "There is no arena with that name."); + MAUtils.tellPlayer(sender, "Usage: /ma protect ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma protect ([true|false])"); + return true; + } + arena.protect = arg2.equals("true"); + } + + arena.serializeConfig(); + MAUtils.tellPlayer(sender, "Protection for arena '" + arena.configName() + "': " + ((arena.protect) ? ChatColor.GREEN + "on" : ChatColor.RED + "off")); + return true; + } + + if (base.equals("editarena")) + { + if (!console && !(player && plugin.has(p, "mobarena.setup.editarena")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; } - Arena arena = am.getArenaWithName(arg1); - if (arena == null) + Arena arena; + + // No arguments. + if (arg1.isEmpty()) { - MAUtils.tellPlayer(sender, "There is no arena with that name."); - return true; + arena = am.selectedArena; + arena.edit = !arena.edit; } - arena.edit = arg2.equals("true"); - MAUtils.tellPlayer(sender, "Edit mode for arena '" + arg1 + "': " + ((arena.edit) ? ChatColor.GREEN + "true" : ChatColor.RED + "false")); + // One argument. + else if (arg2.isEmpty()) + { + // Argument is [true|false] + if (arg1.equals("true") || arg1.equals("false")) + { + arena = am.selectedArena; + arena.edit = arg1.equals("true"); + } + // Argument is + else + { + arena = am.getArenaWithName(arg1); + if (arena == null) + { + MAUtils.tellPlayer(sender, "There is no arena with that name."); + MAUtils.tellPlayer(sender, "Usage: /ma editarena ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma editarena ([true|false])"); + return true; + } + arena.edit = !arena.edit; + } + } + + // Two arguments + else + { + if (!(arg2.equals("true") || arg2.equals("false"))) + { + MAUtils.tellPlayer(sender, "Usage: /ma editarena ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma editarena ([true|false])"); + return true; + } + arena = am.getArenaWithName(arg1); + if (arena == null) + { + MAUtils.tellPlayer(sender, "There is no arena with that name."); + MAUtils.tellPlayer(sender, "Usage: /ma editarena ([true|false])"); + MAUtils.tellPlayer(sender, " or /ma editarena ([true|false])"); + return true; + } + arena.edit = arg2.equals("true"); + } + + MAUtils.tellPlayer(sender, "Edit mode for arena '" + arena.configName() + "': " + ((arena.edit) ? ChatColor.GREEN + "true" : ChatColor.RED + "false")); if (arena.edit) MAUtils.tellPlayer(sender, "Remember to turn it back off after editing!"); return true; } @@ -705,7 +825,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("setregion")) { - if (!(player && MobArena.has(p, "mobarena.setup.setregion")) && !op) + if (!(player && plugin.has(p, "mobarena.setup.setregion")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -727,7 +847,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("expandregion")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.expandregion")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.expandregion")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -737,6 +857,11 @@ public class MACommands implements CommandExecutor MAUtils.tellPlayer(sender, "Usage: /ma expandregion [up|down|out]"); return true; } + if (am.selectedArena.p1 == null || am.selectedArena.p2 == null) + { + MAUtils.tellPlayer(sender, "You must first define p1 and p2"); + return true; + } if (arg2.equals("up")) { @@ -765,12 +890,128 @@ public class MACommands implements CommandExecutor return true; } + if (base.equals("showregion")) + { + if (!(player && plugin.has(p, "mobarena.setup.showregion")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); + return true; + } + if (am.selectedArena.p1 == null || am.selectedArena.p2 == null) + { + MAUtils.tellPlayer(sender, "The region is not defined for the selected arena."); + return true; + } + if (showingRegion || !am.selectedArena.edit) + { + MAUtils.tellPlayer(sender, "Must be in edit mode."); + return true; + } + + Material mat = Material.WOOL; + byte color = (byte)0; + + if (arg1.equals("glowstone")) + mat = Material.GLOWSTONE; + else if (arg1.equals("white") || arg1.equals("red") || arg1.equals("blue")) + color = DyeColor.valueOf(arg1.toUpperCase()).getData(); + else if (arg1.equals("green")) // Dark green sucks + color = 0x5; + else + mat = Material.GLASS; + + // Set the variable so we don't overwrite the region. + showingRegion = true; + + // Show the frame. + final World world = am.selectedArena.world; + final Set blocks = MAUtils.showRegion(world, am.selectedArena.p1, am.selectedArena.p2, mat.getId(), color); + + // And hide the frame. + plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, + new Runnable() + { + public void run() + { + for (int[] buffer : blocks) + world.getBlockAt(buffer[0], buffer[1], buffer[2]).setTypeIdAndData(buffer[3], (byte) 0, false); + showingRegion = false; + } + }, 2*20); + + return true; + } + + if (base.equals("setlobbyregion")) + { + if (!(player && plugin.has(p, "mobarena.setup.setlobbyregion")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); + return true; + } + + if (!(arg1.equals("l1") || arg1.equals("l2"))) + { + MAUtils.tellPlayer(sender, "Usage: /ma setlobbyregion [l1|l2]"); + return true; + } + + MAUtils.setArenaCoord(plugin.getConfig(), am.selectedArena, arg1, p.getLocation()); + MAUtils.tellPlayer(sender, "Set lobby point " + arg1 + " for arena '" + am.selectedArena.configName() + "'"); + return true; + } + + if (base.equals("expandlobbyregion")) + { + if (!console && !(player && plugin.has(p, "mobarena.setup.expandlobbyregion")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); + return true; + } + if (args.length != 3 || !arg1.matches("[0-9]+")) + { + MAUtils.tellPlayer(sender, "Usage: /ma expandlobbyregion [up|down|out]"); + return true; + } + if (am.selectedArena.l1 == null || am.selectedArena.l2 == null) + { + MAUtils.tellPlayer(sender, "You must first define l1 and l2"); + return true; + } + + if (arg2.equals("up")) + { + am.selectedArena.l2.setY(Math.min(127, am.selectedArena.l2.getY() + Integer.parseInt(arg1))); + } + else if (arg2.equals("down")) + { + am.selectedArena.l1.setY(Math.max(0, am.selectedArena.l1.getY() - Integer.parseInt(arg1))); + } + else if (arg2.equals("out")) + { + am.selectedArena.l1.setX(am.selectedArena.l1.getX() - Integer.parseInt(arg1)); + am.selectedArena.l1.setZ(am.selectedArena.l1.getZ() - Integer.parseInt(arg1)); + am.selectedArena.l2.setX(am.selectedArena.l2.getX() + Integer.parseInt(arg1)); + am.selectedArena.l2.setZ(am.selectedArena.l2.getZ() + Integer.parseInt(arg1)); + } + else + { + MAUtils.tellPlayer(sender, "Usage: /ma expandlobbyregion [up|down|out]"); + return true; + } + + MAUtils.tellPlayer(sender, "Lobby region for '" + am.selectedArena.configName() + "' expanded " + arg2 + " by " + arg1 + " blocks."); + am.selectedArena.serializeConfig(); + am.selectedArena.load(plugin.getConfig()); + return true; + } + /* * Set warp points [arena|lobby|spectator] for the current arena. */ if (base.equals("setwarp")) { - if (!(player && MobArena.has(p, "mobarena.setup.setwarp")) && !op) + if (!(player && plugin.has(p, "mobarena.setup.setwarp")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -780,8 +1021,8 @@ public class MACommands implements CommandExecutor MAUtils.tellPlayer(sender, "Usage: /ma setwarp [arena|lobby|spectator]"); return true; } - - MAUtils.setArenaCoord(plugin.getConfig(), am.selectedArena, arg1, p.getLocation().getBlock().getRelative(0,1,0).getLocation()); + + MAUtils.setArenaCoord(plugin.getConfig(), am.selectedArena, arg1, p.getLocation()); MAUtils.tellPlayer(sender, "Set warp point " + arg1 + " for arena '" + am.selectedArena.configName() + "'"); return true; } @@ -791,7 +1032,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("spawnpoints")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.spawnpoints")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.spawnpoints")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -822,7 +1063,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("addspawn")) { - if (!(player && MobArena.has(p, "mobarena.setup.addspawn")) && !op) + if (!(player && plugin.has(p, "mobarena.setup.addspawn")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -843,7 +1084,7 @@ public class MACommands implements CommandExecutor */ if (base.equals("delspawn")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.delspawn")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.delspawn")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -863,7 +1104,7 @@ public class MACommands implements CommandExecutor if (base.equals("auto-generate")) { - if (!(player && MobArena.has(p, "mobarena.setup.autogenerate")) && !op) + if (!(player && plugin.has(p, "mobarena.setup.autogenerate")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -888,7 +1129,7 @@ public class MACommands implements CommandExecutor if (base.equals("auto-degenerate")) { - if (!console && !(player && MobArena.has(p, "mobarena.setup.autodegenerate")) && !op) + if (!console && !(player && plugin.has(p, "mobarena.setup.autodegenerate")) && !op) { MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); return true; @@ -916,6 +1157,55 @@ public class MACommands implements CommandExecutor return true; } + if (base.equals("dooooo") && arg1.equals("it") && arg2.equals("hippie") && arg3.equals("monster")) + { + if (!(player && plugin.has(p, "mobarena.setup.autogenerate")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); + return true; + } + + String name = "a0"; + do name = name.substring(0,1) + (Integer.parseInt(name.substring(1,2)) + 1); + while (am.getArenaWithName(name) != null); + + if (MAUtils.doooooItHippieMonster(p.getLocation(), 13, name, plugin)) + MAUtils.tellPlayer(sender, "Arena with name '" + name + "' generated."); + else + MAUtils.tellPlayer(sender, "Could not auto-generate arena."); + return true; + } + + if (base.equals("undo") && arg1.equals("it") && arg2.equals("hippie") && arg3.equals("monster")) + { + if (!(player && plugin.has(p, "mobarena.setup.autodegenerate")) && !op) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.MISC_NO_ACCESS)); + return true; + } + if (am.arenas.size() < 2) + { + MAUtils.tellPlayer(sender, "At least one arena must exist!"); + return true; + } + if (am.getArenaWithName("a1") == null) + { + MAUtils.tellPlayer(sender, MAMessages.get(Msg.ARENA_DOES_NOT_EXIST)); + return true; + } + + String name = "a1"; + while (am.getArenaWithName(name) != null) + name = name.substring(0,1) + (Integer.parseInt(name.substring(1,2)) + 1); + name = name.substring(0,1) + (Integer.parseInt(name.substring(1,2)) - 1); + + if (MAUtils.undoItHippieMonster(name, plugin, true)) + MAUtils.tellPlayer(sender, "Arena with name '" + name + "' degenerated."); + else + MAUtils.tellPlayer(sender, "Could not degenerate arena."); + return true; + } + MAUtils.tellPlayer(sender, "Command not found."); return true; } diff --git a/src/com/garbagemule/MobArena/MAMessages.java b/src/com/garbagemule/MobArena/MAMessages.java index 0a735b2..71e5015 100644 --- a/src/com/garbagemule/MobArena/MAMessages.java +++ b/src/com/garbagemule/MobArena/MAMessages.java @@ -3,8 +3,9 @@ package com.garbagemule.MobArena; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; -import java.io.FileReader; +import java.io.FileInputStream; import java.io.FileWriter; +import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; @@ -22,10 +23,15 @@ public class MAMessages JOIN_IN_OTHER_ARENA, JOIN_ARENA_NOT_ENABLED, JOIN_ARENA_NOT_SETUP, + JOIN_ARENA_PERMISSION, + JOIN_FEE_REQUIRED, + JOIN_FEE_PAID, JOIN_ARENA_IS_RUNNING, JOIN_ALREADY_PLAYING, JOIN_ARG_NEEDED, + JOIN_TOO_FAR, JOIN_EMPTY_INV, + JOIN_PLAYER_LIMIT_REACHED, JOIN_STORE_INV_FAIL, LEAVE_PLAYER_LEFT, LEAVE_NOT_PLAYING, @@ -44,6 +50,7 @@ public class MAMessages FORCE_END_IDLE, REWARDS_GIVE, LOBBY_CLASS_PICKED, + LOBBY_CLASS_RANDOM, LOBBY_CLASS_PERMISSION, LOBBY_PLAYER_READY, LOBBY_DROP_ITEM, @@ -54,7 +61,6 @@ public class MAMessages WAVE_DEFAULT, WAVE_SPECIAL, WAVE_REWARD, - // Misc MISC_LIST_ARENAS, MISC_LIST_PLAYERS, MISC_COMMAND_NOT_ALLOWED, @@ -72,10 +78,15 @@ public class MAMessages defaults.put(Msg.JOIN_IN_OTHER_ARENA, "You are already in an arena! Leave that one first."); defaults.put(Msg.JOIN_ARENA_NOT_ENABLED, "This arena is not enabled."); defaults.put(Msg.JOIN_ARENA_NOT_SETUP, "This arena has not been set up yet."); + defaults.put(Msg.JOIN_ARENA_PERMISSION, "You don't have permission to join this arena."); + defaults.put(Msg.JOIN_FEE_REQUIRED, "Insufficient funds. Price: %"); + defaults.put(Msg.JOIN_FEE_PAID, "Price to join was: %"); defaults.put(Msg.JOIN_ARENA_IS_RUNNING, "This arena is in already progress."); defaults.put(Msg.JOIN_ALREADY_PLAYING, "You are already playing!"); defaults.put(Msg.JOIN_ARG_NEEDED, "You must specify an arena. Type /ma arenas for a list."); + defaults.put(Msg.JOIN_TOO_FAR, "You are too far away from the arena to join/spectate."); defaults.put(Msg.JOIN_EMPTY_INV, "You must empty your inventory to join the arena."); + defaults.put(Msg.JOIN_PLAYER_LIMIT_REACHED, "The player limit of this arena has been reached."); defaults.put(Msg.JOIN_STORE_INV_FAIL, "Failed to store inventory. Try again."); defaults.put(Msg.JOIN_PLAYER_JOINED, "You joined the arena. Have fun!"); defaults.put(Msg.LEAVE_NOT_PLAYING, "You are not in the arena."); @@ -94,11 +105,12 @@ public class MAMessages defaults.put(Msg.FORCE_END_ENDED, "Forced arena end."); defaults.put(Msg.FORCE_END_IDLE, "You weren't quick enough!"); defaults.put(Msg.REWARDS_GIVE, "Here are all of your rewards!"); - defaults.put(Msg.LOBBY_DROP_ITEM, "No sharing before the arena starts!"); + defaults.put(Msg.LOBBY_DROP_ITEM, "No sharing allowed at this time!"); defaults.put(Msg.LOBBY_PLAYER_READY, "You have been flagged as ready!"); defaults.put(Msg.LOBBY_PICK_CLASS, "You must first pick a class!"); defaults.put(Msg.LOBBY_RIGHT_CLICK, "Punch the sign. Don't right-click."); defaults.put(Msg.LOBBY_CLASS_PICKED, "You have chosen % as your class!"); + defaults.put(Msg.LOBBY_CLASS_RANDOM, "You will get a random class on arena start."); defaults.put(Msg.LOBBY_CLASS_PERMISSION, "You don't have permission to use this class!"); defaults.put(Msg.WARP_TO_ARENA, "Can't warp to the arena during battle!"); defaults.put(Msg.WARP_FROM_ARENA, "Warping not allowed in the arena!"); @@ -108,7 +120,7 @@ public class MAMessages defaults.put(Msg.MISC_LIST_PLAYERS, "Live players: %"); defaults.put(Msg.MISC_LIST_ARENAS, "Available arenas: %"); defaults.put(Msg.MISC_COMMAND_NOT_ALLOWED, "You can't use that command in the arena!"); - defaults.put(Msg.MISC_NO_ACCESS, "You don't have access to this comand."); + defaults.put(Msg.MISC_NO_ACCESS, "You don't have access to this command."); defaults.put(Msg.MISC_NONE, ""); } @@ -132,10 +144,7 @@ public class MAMessages System.out.println("[MobArena] Announcements-file not found. Creating one..."); msgFile.createNewFile(); - FileWriter fw = new FileWriter(msgFile); - BufferedWriter bw = new BufferedWriter(fw); - - // Write default announcements to the file. + BufferedWriter bw = new BufferedWriter(new FileWriter(msgFile)); for (Msg m : Msg.values()) { bw.write(m.toString() + "=" + defaults.get(m)); @@ -148,26 +157,29 @@ public class MAMessages } catch (Exception e) { - System.out.println("[MobArena] ERROR: Couldn't initialize announcements-file. Using defaults."); + System.out.println("[MobArena] ERROR! Couldn't initialize announcements-file. Using defaults."); return; } // If the file was found, populate the msgMap. try { - FileReader fr = new FileReader(msgFile); - BufferedReader br = new BufferedReader(fr); + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(msgFile), "UTF-8")); + // Check for BOM character. + br.mark(1); int bom = br.read(); + if (bom != 65279) br.reset(); + String s; while ((s = br.readLine()) != null) - { process(s); - } + br.close(); } catch (Exception e) { - System.out.println("[MobArena] ERROR: Problem with announcements-file. Using defaults."); + e.printStackTrace(); + System.out.println("[MobArena] ERROR! Problem with announcements-file. Using defaults."); return; } } @@ -209,7 +221,7 @@ public class MAMessages String[] split = s.split("="); if (split.length != 2) { - System.out.println("[MobArena] ERROR: Couldn't parse \"" + s + "\". Check announcements-file."); + System.out.println("[MobArena] ERROR! Couldn't parse \"" + s + "\". Check announcements-file."); return; } @@ -225,7 +237,7 @@ public class MAMessages } catch (Exception e) { - System.out.println("[MobArena] ERROR: " + key + " is not a valid key. Check announcements-file."); + System.out.println("[MobArena] ERROR! " + key + " is not a valid key. Check announcements-file."); return; } } diff --git a/src/com/garbagemule/MobArena/MAPlayerListener.java b/src/com/garbagemule/MobArena/MAPlayerListener.java index 9cb29dd..71d9720 100644 --- a/src/com/garbagemule/MobArena/MAPlayerListener.java +++ b/src/com/garbagemule/MobArena/MAPlayerListener.java @@ -24,7 +24,7 @@ public class MAPlayerListener extends PlayerListener } public void onPlayerInteract(PlayerInteractEvent event) - { + { if (!am.enabled) return; for (Arena arena : am.arenas) arena.onPlayerInteract(event); @@ -75,7 +75,7 @@ public class MAPlayerListener extends PlayerListener if (!am.updateNotify || !event.getPlayer().isOp()) return; final Player p = event.getPlayer(); - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, + Bukkit.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() { public void run() diff --git a/src/com/garbagemule/MobArena/MASpawnThread.java b/src/com/garbagemule/MobArena/MASpawnThread.java index 23c6a64..1baaba0 100644 --- a/src/com/garbagemule/MobArena/MASpawnThread.java +++ b/src/com/garbagemule/MobArena/MASpawnThread.java @@ -2,6 +2,7 @@ package com.garbagemule.MobArena; import java.util.ArrayList; import java.util.HashSet; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; @@ -40,7 +41,6 @@ public class MASpawnThread implements Runnable private Random random; private MobArena plugin; private Arena arena; - private final double MIN_DISTANCE = 256; public MASpawnThread(MobArena plugin, Arena arena) { @@ -51,11 +51,13 @@ public class MASpawnThread implements Runnable taskId = -32768; - noOfPlayers = arena.livePlayers.size(); + //noOfPlayers = arena.livePlayers.size(); + noOfPlayers = arena.arenaPlayers.size(); wave = 1; random = new Random(); // Set up the distribution variables for the random spawner. + // Note: Updating these means MAUtils.getArenaDistributions() must also be updated! dZombies = arena.distDefault.get("zombies"); dSkeletons = dZombies + arena.distDefault.get("skeletons"); dSpiders = dSkeletons + arena.distDefault.get("spiders"); @@ -72,16 +74,18 @@ public class MASpawnThread implements Runnable } public void run() - { + { + List tmp = new LinkedList(arena.monsters); + for (Entity e : tmp) + if (e.isDead()) + arena.monsters.remove(e); + // Check if wave needs to be cleared first. If so, return! if (arena.waveClear && wave > 1) - { + { if (!arena.monsters.isEmpty()) return; } - - // If maxIdleTime is defined, reset the timer. - //if (arena.maxIdleTime > 0) arena.resetIdleTimer(); // Check if we need to grant more rewards with the recurrent waves. for (Map.Entry> entry : arena.everyWaveMap.entrySet()) @@ -115,7 +119,7 @@ public class MASpawnThread implements Runnable } wave++; - if (arena.maxIdleTime > 0) arena.resetIdleTimer(); + if (arena.maxIdleTime > 0 && arena.monsters.isEmpty()) arena.resetIdleTimer(); } /** @@ -123,12 +127,30 @@ public class MASpawnThread implements Runnable */ private void addReward(List rewards) { - for (Player p : arena.livePlayers) + //for (Player p : arena.livePlayers) + for (Player p : arena.arenaPlayers) { + if (arena.rewardMap.get(p) == null) + continue; + ItemStack reward = MAUtils.getRandomReward(rewards); arena.rewardMap.get(p).add(reward); - MAUtils.tellPlayer(p, MAMessages.get(Msg.WAVE_REWARD, MAUtils.toCamelCase(reward.getType().toString()) + ":" + reward.getAmount())); + if (reward == null) + { + MAUtils.tellPlayer(p, "ERROR! Problem with economy rewards. Notify server host!"); + System.out.println("[MobArena] ERROR! Could not add null reward. Please check the config-file!"); + } + else if (reward.getTypeId() == MobArena.ECONOMY_MONEY_ID) + { + if (plugin.Methods.hasMethod()) + MAUtils.tellPlayer(p, MAMessages.get(Msg.WAVE_REWARD, plugin.Method.format(reward.getAmount()))); + else System.out.println("[MobArena] ERROR! No economy plugin detected!"); + } + else + { + MAUtils.tellPlayer(p, MAMessages.get(Msg.WAVE_REWARD, MAUtils.toCamelCase(reward.getType().toString()) + ":" + reward.getAmount())); + } } } @@ -163,6 +185,9 @@ public class MASpawnThread implements Runnable LivingEntity e = arena.world.spawnCreature(loc,mob); arena.monsters.add(e); + if (mob == CreatureType.WOLF) + ((Wolf)e).setOwner(null); + // Grab a random target. Creature c = (Creature) e; c.setTarget(getClosestPlayer(e)); @@ -195,7 +220,6 @@ public class MASpawnThread implements Runnable else if (ran < dGhasts) mob = CreatureType.GHAST; else return; - // 5 on purpose - Ghasts act weird in Overworld. switch(mob) { case CREEPER: @@ -237,7 +261,7 @@ public class MASpawnThread implements Runnable arena.monsters.add(e); if (slime) ((Slime)e).setSize(2); - if (wolf) ((Wolf)e).setAngry(true); + if (wolf) { ((Wolf)e).setAngry(true); ((Wolf)e).setOwner(null); } if (ghast) ((Ghast)e).setHealth(Math.min(noOfPlayers*25, 200)); if (creeper) ((Creeper)e).setPowered(true); @@ -294,9 +318,18 @@ public class MASpawnThread implements Runnable for (Location s : arena.spawnpoints.values()) { - for (Player p : arena.livePlayers) + //for (Player p : arena.livePlayers) + for (Player p : arena.arenaPlayers) { - if (s.distanceSquared(p.getLocation()) > MIN_DISTANCE) + if (!arena.world.equals(p.getWorld())) + { + System.out.println("[MobArena] MASpawnThread:291: Player '" + p.getName() + "' is not in the right world. Force leaving..."); + arena.playerLeave(p); + MAUtils.tellPlayer(p, "You warped out of the arena world."); + continue; + } + + if (s.distanceSquared(p.getLocation()) > MobArena.MIN_PLAYER_DISTANCE) continue; result.add(s); @@ -324,11 +357,18 @@ public class MASpawnThread implements Runnable /* Iterate through the ArrayList, and update current and result every * time a squared distance smaller than current is found. */ - for (Player p : arena.livePlayers) + //for (Player p : arena.livePlayers) + for (Player p : arena.arenaPlayers) { - dist = p.getLocation().distance(e.getLocation()); - //double dist = MAUtils.distance(p.getLocation(), e.getLocation()); - if (dist < current && dist < 256) + if (!arena.world.equals(p.getWorld())) + { + System.out.println("[MobArena] MASpawnThread:329: Player '" + p.getName() + "' is not in the right world. Force leaving..."); + arena.playerLeave(p); + MAUtils.tellPlayer(p, "You warped out of the arena world."); + continue; + } + dist = p.getLocation().distanceSquared(e.getLocation()); + if (dist < current && dist < MobArena.MIN_PLAYER_DISTANCE) { current = dist; result = p; @@ -336,4 +376,27 @@ public class MASpawnThread implements Runnable } return result; } + + /** + * Update the targets of all monsters, if their targets aren't alive. + */ + public void updateTargets() + { + Creature c; + Entity target; + for (Entity e : arena.monsters) + { + if (!(e instanceof Creature)) + continue; + + c = (Creature) e; + target = c.getTarget(); + + //if (target instanceof Player && arena.livePlayers.contains(target)) + if (target instanceof Player && arena.arenaPlayers.contains(target)) + continue; + + c.setTarget(getClosestPlayer(e)); + } + } } \ No newline at end of file diff --git a/src/com/garbagemule/MobArena/MAUtils.java b/src/com/garbagemule/MobArena/MAUtils.java index 04b3a41..b4b0a7f 100644 --- a/src/com/garbagemule/MobArena/MAUtils.java +++ b/src/com/garbagemule/MobArena/MAUtils.java @@ -23,6 +23,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.DyeColor; import org.bukkit.World; import org.bukkit.Material; import org.bukkit.Location; @@ -96,6 +97,7 @@ public class MAUtils HELMETS_TYPE.add(Material.CHAINMAIL_HELMET); HELMETS_TYPE.add(Material.IRON_HELMET); HELMETS_TYPE.add(Material.DIAMOND_HELMET); + HELMETS_TYPE.add(Material.PUMPKIN); CHESTPLATES_TYPE.add(Material.LEATHER_CHESTPLATE); CHESTPLATES_TYPE.add(Material.GOLD_CHESTPLATE); @@ -159,6 +161,11 @@ public class MAUtils return result; } + public static List getEntryFee(Configuration config, String arena) + { + return makeItemStackList(config.getString("arenas." + arena + ".settings.entry-fee", null)); + } + /** * Takes a comma-separated list of items in the : format and * returns a list of ItemStacks created from that data. @@ -166,8 +173,9 @@ public class MAUtils public static List makeItemStackList(String string) { List result = new LinkedList(); - if (string == null) return result; + if (string == null || string.isEmpty()) return result; + // Trim commas and whitespace, and split items by commas string = string.trim(); if (string.endsWith(",")) string = string.substring(0, string.length()-1); @@ -175,20 +183,27 @@ public class MAUtils for (String item : items) { + // Trim whitespace and split by colons. item = item.trim(); String[] parts = item.split(":"); // Grab the amount. - int amount = (parts.length == 2 && parts[1].matches("[0-9]+")) ? - Integer.parseInt(parts[1]) : - 1; + int amount = 1; + if (parts.length == 1 && parts[0].matches("\\$[0-9]+")) + amount = Integer.parseInt(parts[0].substring(1, parts[0].length())); + else if (parts.length == 2 && parts[1].matches("(-)?[0-9]+")) + amount = Integer.parseInt(parts[1]); + else if (parts.length == 3 && parts[2].matches("(-)?[0-9]+")) + amount = Integer.parseInt(parts[2]); + // Make the ItemStack. - ItemStack stack = (parts[0].matches("[0-9]+")) ? - makeItemStack(Integer.parseInt(parts[0]), amount) : + ItemStack stack = (parts.length == 3) ? + makeItemStack(parts[0], amount, parts[1]) : makeItemStack(parts[0], amount); - result.add(stack); + if (stack != null) + result.add(stack); } return result; } @@ -241,33 +256,26 @@ public class MAUtils */ public static Map getArenaDistributions(Configuration config, String arena, String wave) { - //config.load(); String arenaPath = "arenas." + arena + ".waves." + wave; Map result = new HashMap(); - List dists = config.getKeys(arenaPath); + List dists = (config.getKeys(arenaPath) != null) ? config.getKeys(arenaPath) : new LinkedList(); - // If there are no distributions yet, add them. - if (dists == null) + String[] monsters = (wave.equals("default")) ? new String[]{"zombies", "skeletons", "spiders", "creepers", "wolves"} + : new String[]{"powered-creepers", "zombie-pigmen", "slimes", "humans", "angry-wolves", "giants", "ghasts"}; + boolean update = false; + for (String monster : monsters) { - if (wave.equals("default")) - { - config.setProperty(arenaPath + ".zombies", 10); - config.setProperty(arenaPath + ".skeletons", 10); - config.setProperty(arenaPath + ".spiders", 10); - config.setProperty(arenaPath + ".creepers", 10); - config.setProperty(arenaPath + ".wolves", 10); - } - else if (wave.equals("special")) - { - config.setProperty(arenaPath + ".powered-creepers", 10); - config.setProperty(arenaPath + ".zombie-pigmen", 10); - config.setProperty(arenaPath + ".slimes", 10); - config.setProperty(arenaPath + ".humans", 10); - config.setProperty(arenaPath + ".angry-wolves", 10); - config.setProperty(arenaPath + ".giants", 0); - config.setProperty(arenaPath + ".ghasts", 0); - } - //config.save(); + if (dists.contains(monster)) + continue; + + //if (config.getInt(arenaPath + "." + m, -1) == -1) + config.setProperty(arenaPath + "." + monster, (monster.equals("giants") || monster.equals("ghasts")) ? 0 : 10); + update = true; + } + + if (update) + { + config.save(); dists = config.getKeys(arenaPath); } @@ -283,8 +291,8 @@ public class MAUtils value = 0; config.setProperty(arenaPath + "." + monster, value); - //config.save(); } + config.save(); result.put(monster, value); } @@ -329,14 +337,14 @@ public class MAUtils // Grab the contents. ItemStack[] armor = p.getInventory().getArmorContents(); ItemStack[] items = p.getInventory().getContents(); - + String invPath = "plugins" + sep + "MobArena" + sep + "inventories"; new File(invPath).mkdir(); File backupFile = new File(invPath + sep + p.getName() + ".inv"); try { - if (backupFile.exists()) + if (backupFile.exists() && !restoreInventory(p)) return false; backupFile.createNewFile(); @@ -443,12 +451,26 @@ public class MAUtils /** * Gives the player all of the items in the list of ItemStacks. */ - public static void giveItems(Player p, List stacks, boolean autoEquip, boolean rewards) + public static void giveItems(Player p, List stacks, boolean autoEquip, boolean rewards, MobArena plugin) { - PlayerInventory inv = p.getInventory(); + if (stacks == null) + return; + PlayerInventory inv = p.getInventory(); for (ItemStack stack : stacks) { + if (stack == null) + continue; + + // If this is money, don't add to inventory. + if (stack.getTypeId() == MobArena.ECONOMY_MONEY_ID) + { + if (plugin != null && plugin.Methods.hasMethod()) + plugin.Method.getAccount(p.getName()).add(stack.getAmount()); + + continue; + } + // If these are rewards, don't tamper with them. if (rewards) { @@ -456,30 +478,28 @@ public class MAUtils continue; } - // If this is an armor piece, equip it and continue. + // If this is an armor piece, equip it. if (autoEquip && ARMORS_TYPE.contains(stack.getType())) { equipArmorPiece(stack, inv); continue; } - // If this is a sword, set its durability to "unlimited". - //if (SWORDS_TYPE.contains(stack.getType())) + // If this is a weapon, set its durability to "unlimited". if (WEAPONS_TYPE.contains(stack.getType())) stack.setDurability((short) -32768); - + inv.addItem(stack); } } - - public static void giveItems(Player p, List stacks, boolean autoEquip) + public static void giveRewards(Player p, List stacks, MobArena plugin) { - giveItems(p, stacks, autoEquip, false); + giveItems(p, stacks, false, true, plugin); } - public static void giveRewards(Player p, List stacks) + public static void giveItems(Player p, List stacks, boolean autoEquip, MobArena plugin) { - giveItems(p, stacks, false, true); + giveItems(p, stacks, autoEquip, false, plugin); } public static int getPetAmount(Player p) @@ -513,12 +533,29 @@ public class MAUtils } /* Helper methods for making ItemStacks out of strings and ints */ - private static ItemStack makeItemStack(String name, int amount) + public static ItemStack makeItemStack(String name, int amount, String data) { + // If this is economy money, create a dummy ItemStack. + if (name.matches("\\$[0-9]+")) + return new ItemStack(MobArena.ECONOMY_MONEY_ID, amount); + try { - Material material = Material.valueOf(name.toUpperCase()); - return new ItemStack(material, amount); + byte offset = 0; + + Material material = (name.matches("[0-9]+")) ? + Material.getMaterial(Integer.parseInt(name)) : + Material.valueOf(name.toUpperCase()); + + if (material == Material.INK_SACK) + offset = 15; + + DyeColor dye = (data.matches("[0-9]+")) ? + DyeColor.getByData((byte) Math.abs(offset - Integer.parseInt(data))) : + DyeColor.valueOf(data.toUpperCase()); + + //return new ItemStack(material, amount, (byte) Math.abs((offset - dye.getData()))); + return new ItemStack(material, amount, (byte) Math.abs(offset - dye.getData())); } catch (Exception e) { @@ -526,24 +563,17 @@ public class MAUtils return null; } } - - private static ItemStack makeItemStack(int id, int amount) + public static ItemStack makeItemStack(String name, int amount) { - try - { - Material material = Material.getMaterial(id); - return new ItemStack(material, amount); - } - catch (Exception e) - { - System.out.println("[MobArena] ERROR! Could not create item with id " + id + ". Check config.yml"); - return null; - } + return makeItemStack(name, amount, "0"); } /* Helper method for grabbing a random reward */ public static ItemStack getRandomReward(List rewards) { + if (rewards.isEmpty()) + return null; + Random ran = new Random(); return rewards.get(ran.nextInt(rewards.size())); } @@ -561,21 +591,27 @@ public class MAUtils */ public static void sitPets(Player p) { + if (p == null) + { + System.out.println("Player is null!"); + return; + } + List entities = p.getNearbyEntities(80, 40, 80); for (Entity e : entities) { if (!(e instanceof Wolf)) continue; - Wolf w = (Wolf) e; - if (w.getOwner().equals(p)) + Wolf w = (Wolf) e; + if (w.isTamed() && w.getOwner() != null && w.getOwner().equals(p)) w.setSitting(true); } } /** * Removes all the pets belonging to this player. - */ + *//* public static void clearPets(Arena arena, Player p) { for (Wolf w : arena.pets) @@ -583,7 +619,7 @@ public class MAUtils if (w.getOwner().equals(p)) w.remove(); } - } + }*/ @@ -593,6 +629,91 @@ public class MAUtils // ///////////////////////////////////////////////////////////////////// */ + /** + * Create a frame spanned by the two input coordinates. + * @return An int arry holding x,y,z and the original type IDs of each block. + */ + public static Set showRegion(World world, Location p1, Location p2, int id, byte color) + { + Set result = new HashSet(); + + int x1 = p1.getBlockX(); int y1 = p1.getBlockY(); int z1 = p1.getBlockZ(); + int x2 = p2.getBlockX(); int y2 = p2.getBlockY(); int z2 = p2.getBlockZ(); + + int[] buffer; + + for (int i = x1; i <= x2; i++) + { + buffer = new int[] {i, y1, z1, world.getBlockTypeIdAt(i, y1, z1)}; + result.add(buffer); + world.getBlockAt(i, y1, z1).setTypeIdAndData(id, color, false); + + buffer = new int[] {i, y2, z1, world.getBlockTypeIdAt(i, y2, z1)}; + result.add(buffer); + world.getBlockAt(i, y2, z1).setTypeIdAndData(id, color, false); + + buffer = new int[] {i, y1, z2, world.getBlockTypeIdAt(i, y1, z2)}; + result.add(buffer); + world.getBlockAt(i, y1, z2).setTypeIdAndData(id, color, false); + + buffer = new int[] {i, y2, z2, world.getBlockTypeIdAt(i, y2, z2)}; + result.add(buffer); + world.getBlockAt(i, y2, z2).setTypeIdAndData(id, color, false); + } + for (int j = y1+1; j <= y2-1; j++) + { + buffer = new int[] {x1, j, z1, world.getBlockTypeIdAt(x1, j, z1)}; + result.add(buffer); + world.getBlockAt(x1, j, z1).setTypeIdAndData(id, color, false); + + buffer = new int[] {x2, j, z1, world.getBlockTypeIdAt(x2, j, z1)}; + result.add(buffer); + world.getBlockAt(x2, j, z1).setTypeIdAndData(id, color, false); + + buffer = new int[] {x1, j, z2, world.getBlockTypeIdAt(x1, j, z2)}; + result.add(buffer); + world.getBlockAt(x1, j, z2).setTypeIdAndData(id, color, false); + + buffer = new int[] {x2, j, z2, world.getBlockTypeIdAt(x2, j, z2)}; + result.add(buffer); + world.getBlockAt(x2, j, z2).setTypeIdAndData(id, color, false); + } + for (int k = z1+1; k <= z2-1; k++) + { + buffer = new int[] {x1, y1, k, world.getBlockTypeIdAt(x1, y1, k)}; + result.add(buffer); + world.getBlockAt(x1, y1, k).setTypeIdAndData(id, color, false); + + buffer = new int[] {x2, y1, k, world.getBlockTypeIdAt(x2, y1, k)}; + result.add(buffer); + world.getBlockAt(x2, y1, k).setTypeIdAndData(id, color, false); + + buffer = new int[] {x1, y2, k, world.getBlockTypeIdAt(x1, y2, k)}; + result.add(buffer); + world.getBlockAt(x1, y2, k).setTypeIdAndData(id, color, false); + + buffer = new int[] {x2, y2, k, world.getBlockTypeIdAt(x2, y2, k)}; + result.add(buffer); + world.getBlockAt(x2, y2, k).setTypeIdAndData(id, color, false); + } + + return result; + } + + public static Set showRegion(World world, Location p1, Location p2, int id) + { + return showRegion(world, p1, p2, id, (byte) 0); + } + + /** + * Take all the blocks with coordinates (buffer[0], buffer[1], buffer[2]) and set + * their type ID to buffer[3]. Used to hide regions shown by showRegion. + */ + public static void hideRegion(int[] buffer) + { + + } + /** * Create a Location object from the config-file. */ @@ -610,12 +731,17 @@ public class MAUtils */ public static void setArenaCoord(Configuration config, Arena arena, String coord, Location loc) { + if (coord.equals("arena") || coord.equals("lobby") || coord.equals("spectator")) + loc.setY(loc.getY() + 1); + config.setProperty("arenas." + arena.configName() + ".coords." + coord, makeCoord(loc)); config.save(); arena.load(config); if (coord.equals("p1") || coord.equals("p2")) fixRegion(config, loc.getWorld(), arena); + if (coord.equals("l1") || coord.equals("l2")) + fixLobby(config, loc.getWorld(), arena); } public static boolean delArenaCoord(Configuration config, Arena arena, String coord) @@ -658,6 +784,35 @@ public class MAUtils arena.load(config); } + private static void fixLobby(Configuration config, World world, Arena arena) + { + if (arena.l1 == null || arena.l2 == null) + return; + + if (arena.l1.getX() > arena.l2.getX()) + { + double tmp = arena.l1.getX(); + arena.l1.setX(arena.l2.getX()); + arena.l2.setX(tmp); + } + + if (arena.l1.getZ() > arena.l2.getZ()) + { + double tmp = arena.l1.getZ(); + arena.l1.setZ(arena.l2.getZ()); + arena.l2.setZ(tmp); + } + + if (arena.l1.getY() > arena.l2.getY()) + { + double tmp = arena.l1.getY(); + arena.l1.setY(arena.l2.getY()); + arena.l2.setY(tmp); + } + arena.serializeConfig(); + arena.load(config); + } + /** * Create a Location from the input String in the input World. */ @@ -665,14 +820,14 @@ public class MAUtils { String[] parts = str.split(","); - double x = Double.parseDouble(parts[0]); - double y = Double.parseDouble(parts[1]); - double z = Double.parseDouble(parts[2]); + double x = Double.parseDouble(parts[0].trim()); + double y = Double.parseDouble(parts[1].trim()); + double z = Double.parseDouble(parts[2].trim()); - if (extras && parts.length == 5) + if (extras && parts.length > 3) { - float yaw = Float.parseFloat(parts[3]); - float pitch = Float.parseFloat(parts[4]); + float yaw = Float.parseFloat(parts[3].trim()); + float pitch = Float.parseFloat(parts[4].trim()); return new Location(world, x, y, z, yaw, pitch); } @@ -745,13 +900,17 @@ public class MAUtils /** * Sends a message to all players in and around the arena. */ - public static void tellAll(Arena arena, String msg) + public static void tellAll(Arena arena, String msg) { tellAll(arena, msg, false); } + public static void tellAll(Arena arena, String msg, boolean waitPlayers) { Set tmp = new HashSet(); - tmp.addAll(arena.livePlayers); + //tmp.addAll(arena.livePlayers); + tmp.addAll(arena.arenaPlayers); + tmp.addAll(arena.lobbyPlayers); tmp.addAll(arena.deadPlayers); tmp.addAll(arena.specPlayers); tmp.addAll(arena.readyPlayers); + if (waitPlayers) tmp.addAll(arena.waitPlayers); for (Player p : tmp) tellPlayer(p, msg); } @@ -764,9 +923,18 @@ public class MAUtils /* Iterate through the ArrayList, and update current and result every * time a squared distance smaller than current is found. */ - for (Player p : arena.livePlayers) + //for (Player p : arena.livePlayers) + for (Player p : arena.arenaPlayers) { - double dist = p.getLocation().distanceSquared(e.getLocation()); //distance(p.getLocation(), e.getLocation()); + if (!arena.world.equals(p.getWorld())) + { + System.out.println("[MobArena] MAUtils:908: Player '" + p.getName() + "' is not in the right world. Force leaving..."); + arena.playerLeave(p); + tellPlayer(p, "You warped out of the arena world."); + continue; + } + + double dist = p.getLocation().distanceSquared(e.getLocation()); if (dist < current && dist < 256) { current = dist; @@ -776,15 +944,6 @@ public class MAUtils return result; } - public static double distance(Location loc1, Location loc2) - { - double x = loc1.getX() - loc2.getX(); - double y = loc1.getY() - loc2.getY(); - double z = loc1.getZ() - loc2.getZ(); - - return x*x + y*y + z*z; - } - /** * Convert a proper arena name to a config-file name. * All spaces are replaced by underscores, and the whole String is @@ -830,25 +989,63 @@ public class MAUtils /** * Turn a list into a space-separated string-representation of the list. - */ - public static String listToString(List list) - { - return listToString(list, true); - } - - public static String listToString(List list, boolean none) + */ + public static String listToString(List list, boolean none, MobArena plugin) { - if (none && list.isEmpty()) - return MAMessages.get(Msg.MISC_NONE); + if (list == null || list.isEmpty()) + { + if (none) + return MAMessages.get(Msg.MISC_NONE); + else + return ""; + } StringBuffer buffy = new StringBuffer(); - for (E e : list) + int trimLength = 0; + + E type = list.get(0); + if (type instanceof Player) { - buffy.append(e.toString()); - buffy.append(" "); + for (E e : list) + { + buffy.append(((Player) e).getName()); + buffy.append(" "); + } } - return buffy.toString(); + else if (type instanceof ItemStack) + { + trimLength = 2; + ItemStack stack; + for (E e : list) + { + stack = (ItemStack) e; + if (stack.getTypeId() == MobArena.ECONOMY_MONEY_ID) + { + if (plugin.Methods.hasMethod()) + { + buffy.append(plugin.Method.format(stack.getAmount())); + buffy.append(", "); + } + continue; + } + + buffy.append(stack.getType().toString().toLowerCase()); + buffy.append(":"); + buffy.append(stack.getAmount()); + buffy.append(", "); + } + } + else + { + for (E e : list) + { + buffy.append(e.toString()); + buffy.append(" "); + } + } + return buffy.toString().substring(0, buffy.length() - trimLength); } + public static String listToString(List list, MobArena plugin) { return listToString(list, true, plugin); } /** * Returns a String-list version of a comma-separated list. @@ -873,7 +1070,8 @@ public class MAUtils public static Player getRandomPlayer(Arena arena) { Random random = new Random(); - Player[] array = (Player[]) arena.livePlayers.toArray(); + //Player[] array = (Player[]) arena.livePlayers.toArray(); + Player[] array = (Player[]) arena.arenaPlayers.toArray(); return array[random.nextInt(array.length)]; } @@ -891,6 +1089,12 @@ public class MAUtils (arena.p2 != null) && (arena.spawnpoints.size() > 0)); } + + public static boolean verifyLobby(Arena arena) + { + return ((arena.l1 != null) && + (arena.l2 != null)); + } /** * Checks if there is a new update of MobArena and notifies the @@ -898,7 +1102,7 @@ public class MAUtils */ public static void checkForUpdates(MobArena plugin, final Player p, boolean response) { - String site = "http://forums.bukkit.org/threads/818.19144/"; + String site = "http://forums.bukkit.org/threads/19144/"; try { // Make a URI of the site address @@ -951,6 +1155,36 @@ public class MAUtils ws.allowAnimals = allowAnimals; } + public static String getDuration(long duration) + { + long seconds = duration / 1000; + long secs = seconds % 60; + long mins = (seconds - secs) / 60 % 60; + long hrs = ((seconds - secs) - (mins * 60)) / 60 / 60; + return hrs + ":" + ((mins < 10) ? "0" + mins : mins) + ":" + ((secs < 10) ? "0" + secs : secs); + } + + public static String padRight(String s, int length) { return padRight(s, length, ' '); } + public static String padRight(String s, int length, char pad) + { + StringBuffer buffy = new StringBuffer(); + buffy.append(s); + for (int i = s.length(); i < length; i++) + buffy.append(pad); + return buffy.toString(); + } + + public static String padLeft(String s, int length) { return padLeft(s, length, ' '); } + public static String padLeft(String s, int length, char pad) + { + StringBuffer buffy = new StringBuffer(); + for (int i = 0; i < length - s.length(); i++) + buffy.append(pad); + buffy.append(s); + return buffy.toString(); + } + + /** * Stand back, I'm going to try science! */ @@ -1010,7 +1244,7 @@ public class MAUtils catch (Exception e) { e.printStackTrace(); - System.out.println("Couldn't create backup file. Aborting auto-generate..."); + System.out.println("[MobArena] ERROR! Couldn't create backup file. Aborting auto-generate..."); return false; } @@ -1115,7 +1349,7 @@ public class MAUtils MAUtils.setArenaCoord(plugin.getConfig(), arena, "p1", new Location(world, x1, ly1, z1)); MAUtils.setArenaCoord(plugin.getConfig(), arena, "p2", new Location(world, x2, y2+1, z2)); MAUtils.setArenaCoord(plugin.getConfig(), arena, "arena", new Location(world, loc.getX(), y1+1, loc.getZ())); - MAUtils.setArenaCoord(plugin.getConfig(), arena, "lobby", new Location(world, x1+2, y1-3, z1+2)); + MAUtils.setArenaCoord(plugin.getConfig(), arena, "lobby", new Location(world, x1+2, ly1+1, z1+2)); MAUtils.setArenaCoord(plugin.getConfig(), arena, "spectator", new Location(world, loc.getX(), y2+1, loc.getZ())); MAUtils.setArenaCoord(plugin.getConfig(), arena, "spawnpoints.s1", new Location(world, x1+3, y1+2, z1+3)); MAUtils.setArenaCoord(plugin.getConfig(), arena, "spawnpoints.s2", new Location(world, x1+3, y1+2, z2-3)); @@ -1143,7 +1377,7 @@ public class MAUtils } catch (Exception e) { - if (error) System.out.println("Couldn't find backup file for arena '" + name + "'"); + if (error) System.out.println("[MobArena] ERROR! Couldn't find backup file for arena '" + name + "'"); return false; } diff --git a/src/com/garbagemule/MobArena/MobArena.java b/src/com/garbagemule/MobArena/MobArena.java index 1d705e7..be9a23d 100644 --- a/src/com/garbagemule/MobArena/MobArena.java +++ b/src/com/garbagemule/MobArena/MobArena.java @@ -16,6 +16,8 @@ import org.bukkit.util.config.Configuration; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; +import com.garbagemule.register.payment.Method; +import com.garbagemule.register.payment.Methods; /** * MobArena @@ -27,11 +29,15 @@ public class MobArena extends JavaPlugin private ArenaMaster am; // Permissions stuff - protected static PermissionHandler permissionHandler; + private PermissionHandler permissionHandler; - public MobArena() - { - } + // Economy stuff + protected Methods Methods; + protected Method Method; + + // Global variables + protected static final double MIN_PLAYER_DISTANCE = 256.0; + protected static final int ECONOMY_MONEY_ID = -29; public void onEnable() { @@ -46,6 +52,14 @@ public class MobArena extends JavaPlugin // Permissions setupPermissions(); + // Economy + Methods = new Methods(); + if (!Methods.hasMethod() && Methods.setMethod(this)) + { + Method = Methods.getMethod(); + System.out.println("[MobArena] Payment method found (" + Method.getName() + " version: " + Method.getVersion() + ")"); + } + // Bind the /ma, /marena, and /mobarena commands to MACommands. MACommands commandExecutor = new MACommands(this, am); getCommand("ma").setExecutor(commandExecutor); @@ -68,7 +82,7 @@ public class MobArena extends JavaPlugin pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Highest, this); pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Priority.Highest, this); - pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Highest, this); + pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.High, this); // mcMMO is "Highest" pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); // Lowest because of Tombstone pm.registerEvent(Event.Type.ENTITY_REGAIN_HEALTH, entityListener, Priority.Normal, this); pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Highest, this); @@ -81,11 +95,20 @@ public class MobArena extends JavaPlugin } public void onDisable() - { + { + // Force all arenas to end. for (Arena arena : am.arenas) arena.forceEnd(); am.arenaMap.clear(); + // Permissions & Economy + permissionHandler = null; + if (Methods != null && Methods.hasMethod()) + { + Methods = null; + System.out.println("[MobArena] Payment method was disabled. No longer accepting payments."); + } + System.out.println("[MobArena] disabled."); } @@ -143,13 +166,13 @@ public class MobArena extends JavaPlugin } // Permissions stuff - public static boolean has(Player p, String s) + public boolean has(Player p, String s) { //return (permissionHandler != null && permissionHandler.has(p, s)); return (permissionHandler == null || permissionHandler.has(p, s)); } - public static boolean hasDefTrue(Player p, String s) + public boolean hasDefTrue(Player p, String s) { return (permissionHandler == null || permissionHandler.has(p, s)); } diff --git a/src/com/garbagemule/MobArena/MobArenaHandler.java b/src/com/garbagemule/MobArena/MobArenaHandler.java index 80f4b3b..e399183 100644 --- a/src/com/garbagemule/MobArena/MobArenaHandler.java +++ b/src/com/garbagemule/MobArena/MobArenaHandler.java @@ -1,105 +1,126 @@ package com.garbagemule.MobArena; -import java.util.List; - import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; public class MobArenaHandler { MobArena plugin; + boolean ma = false; + /** + * Primary constructor. + * The boolean 'ma' is flagged true, and the field 'plugin' is initalized, if the server is running MobArena. + */ public MobArenaHandler() { - plugin = (MobArena) Bukkit.getServer().getPluginManager().getPlugin("MobArena"); - } + Plugin maPlugin = (MobArena) Bukkit.getServer().getPluginManager().getPlugin("MobArena"); + + if (maPlugin == null) + return; - // Check if there is an active arena session running. - public boolean isRunning(String arenaName) - { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); - - return arena.running; + ma = true; + plugin = (MobArena) maPlugin; } - // Check if the specified player is in an arena. - public boolean isPlaying(Player p) { return (plugin.getAM().getArenaWithPlayer(p) != null); } - - // Arena getters - public Arena getArenaWithName(String arenaName) { return plugin.getAM().getArenaWithName(arenaName); } - public Arena getArenaWithPlayer(Player p) { return plugin.getAM().getArenaWithPlayer(p); } - public Arena getArenaWithPet(Entity wolf) { return plugin.getAM().getArenaWithPet(wolf); } - public Arena getArenaWithMonster(Entity monster) { return plugin.getAM().getArenaWithMonster(monster); } - public Arena getArenaInLocation(Location l) { return plugin.getAM().getArenaInLocation(l); } - - // Player lists - public List getAllPlayers() { return plugin.getAM().getAllPlayers(); } - public List getAllLivingPlayers() { return plugin.getAM().getAllLivingPlayers(); } - public List getAllPlayersInArena(String arenaName) { return plugin.getAM().getAllPlayersInArena(arenaName); } - public List getLivingPlayersInArena(String arenaName) { return plugin.getAM().getLivingPlayersInArena(arenaName); } - - // Warp locations. - public Location getArenaLocation(String arenaName) + /** + * Check if a Location is inside of an arena region. + * @param loc A location. + * @return true, if the Location is inside of any arena region. + */ + public boolean inRegion(Location loc) { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); + // If the plugin doesn't exist, always return false. + if (!ma || plugin.getAM() == null) return false; - return arena.arenaLoc; - } - public Location getLobbyLocation(String arenaName) - { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); - - return arena.lobbyLoc; - } - public Location getSpectatorLocation(String arenaName) - { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); - - return arena.spectatorLoc; - } - - // Get the current wave number. - public int getWave(Arena arena) { return arena.spawnThread.wave; } - - public int getWave(String arenaName) - { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); - - if (arena.spawnThread == null) - throw new NullPointerException("Arena with name '" + arenaName + "' has not started!"); - - return arena.spawnThread.wave; - } - - // Check if a location is within any arena regions. - - public boolean inRegion(Location l, Arena arena) { return arena.inRegion(l); } - - public boolean inRegion(Location l, String arenaName) - { - Arena arena = plugin.getAM().getArenaWithName(arenaName); - if (arena == null) - throw new NullPointerException("Arena with name '" + arenaName + "' does not exist!"); - - return arena.inRegion(l); - } - public boolean inRegion(Location l) - { + // Return true if location is within just one arena's region. for (Arena arena : plugin.getAM().arenas) - if (arena.inRegion(l)) + if (arena.inRegion(loc)) return true; + return false; } + + /** + * Check if a Location is inside of a specific arena region. + * @param arena An Arena object + * @param loc A location + * @return true, if the Location is inside of the arena region. + */ + public boolean inRegion(Arena arena, Location loc) { return (ma && arena != null && arena.inRegion(loc)); } + + /** + * Check if a Location is inside of the region of an arena that is currently running. + * @param loc A location. + * @return true, if the Location is inside of the region of an arena that is currently running. + */ + public boolean inRunningRegion(Location loc) { return inRegion(loc, false, true); } + + /** + * Check if a Location is inside of the region of an arena that is currently enabled. + * @param loc A location. + * @return true, if the Location is inside of the region of an arena that is currently enabled. + */ + public boolean inEnabledRegion(Location loc) { return inRegion(loc, true, false); } + + /** + * Private helper method for inRunningRegion and inEnabledRegion + * @param loc A location + * @param enabled if true, the method will check if the arena is enabled + * @param running if true, the method will check if the arena is running, overrides enabled + * @return true, if the location is inside of the region of an arena that is currently enabled/running, depending on the parameters. + */ + private boolean inRegion(Location loc, boolean enabled, boolean running) + { + // If the plugin doesn't exist, always return false. + if (!ma || plugin.getAM() == null) return false; + + // Return true if location is within just one arena's region. + for (Arena arena : plugin.getAM().arenas) + if (arena.inRegion(loc)) + if ((running && arena.running) || (enabled && arena.enabled)) + return true; + + return false; + } + + /** + * Get an Arena object at the given location. + * @param loc A location + * @return an Arena object, or null + */ + public Arena getArenaAtLocation(Location loc) { return (ma) ? plugin.getAM().getArenaAtLocation(loc) : null; } + + /** + * Get the Arena object that the given player is currently in. + * @param p A player + * @return an Arena object, or null + */ + public Arena getArenaWithPlayer(Player p) { return (ma) ? plugin.getAM().getArenaWithPlayer(p) : null; } + + /** + * Get the Arena object that the given pet is currently in. + * @param wolf A pet wolf + * @return an Arena object, or null + */ + public Arena getArenaWithPet(Entity wolf) { return (ma) ? plugin.getAM().getArenaWithPet(wolf) : null; } + + /** + * Get the Arena object that the given monster is currently in. + * @param monster A monster + * @return an Arena object, or null + */ + public Arena getArenaWithMonster(Entity monster) { return (ma) ? plugin.getAM().getArenaWithMonster(monster) : null; } + + /** + * Check if the server is running MobArena. + * @return true, if MobArena exists on the server. + */ + public boolean hasMA() + { + return ma; + } } diff --git a/src/com/garbagemule/register/payment/Method.java b/src/com/garbagemule/register/payment/Method.java new file mode 100644 index 0000000..921b9cf --- /dev/null +++ b/src/com/garbagemule/register/payment/Method.java @@ -0,0 +1,62 @@ +package com.garbagemule.register.payment; + +import org.bukkit.plugin.Plugin; + +/** + * Method.java + * Interface for all sub-methods for payment. + * + * @author: Nijikokun (@nijikokun) + * @copyright: Copyright (C) 2011 + * @license: GNUv3 Affero License + */ +public interface Method { + public Object getPlugin(); + public String getName(); + public String getVersion(); + public String format(double amount); + public boolean hasBanks(); + public boolean hasBank(String bank); + public boolean hasAccount(String name); + public boolean hasBankAccount(String bank, String name); + public MethodAccount getAccount(String name); + public MethodBankAccount getBankAccount(String bank, String name); + public boolean isCompatible(Plugin plugin); + public void setPlugin(Plugin plugin); + + public interface MethodAccount { + public double balance(); + public boolean set(double amount); + public boolean add(double amount); + public boolean subtract(double amount); + public boolean multiply(double amount); + public boolean divide(double amount); + public boolean hasEnough(double amount); + public boolean hasOver(double amount); + public boolean hasUnder(double amount); + public boolean isNegative(); + public boolean remove(); + + @Override + public String toString(); + } + + public interface MethodBankAccount { + public double balance(); + public String getBankName(); + public int getBankId(); + public boolean set(double amount); + public boolean add(double amount); + public boolean subtract(double amount); + public boolean multiply(double amount); + public boolean divide(double amount); + public boolean hasEnough(double amount); + public boolean hasOver(double amount); + public boolean hasUnder(double amount); + public boolean isNegative(); + public boolean remove(); + + @Override + public String toString(); + } +} diff --git a/src/com/garbagemule/register/payment/Methods.java b/src/com/garbagemule/register/payment/Methods.java new file mode 100644 index 0000000..a8eb99f --- /dev/null +++ b/src/com/garbagemule/register/payment/Methods.java @@ -0,0 +1,141 @@ +package com.garbagemule.register.payment; + +import com.garbagemule.register.payment.methods.BOSE6; +import com.garbagemule.register.payment.methods.BOSE7; + +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + +import java.util.HashSet; +import java.util.Set; + +/** + * Methods.java + * Controls the getting / setting of methods & the method of payment used. + * + * @author: Nijikokun (@nijikokun) + * @copyright: Copyright (C) 2011 + * @license: GNUv3 Affero License + */ +public class Methods { + private boolean self = false; + private Method Method = null; + private String preferred = ""; + private Set Methods = new HashSet(); + private Set Dependencies = new HashSet(); + private Set Attachables = new HashSet(); + + public Methods() { + this._init(); + } + + /** + * Allows you to set which economy plugin is most preferred. + * + * @param preferred - preferred economy plugin + */ + public Methods(String preferred) { + this._init(); + + if(this.Dependencies.contains(preferred)) { + this.preferred = preferred; + } + } + + private void _init() { + this.addMethod("iConomy", new com.garbagemule.register.payment.methods.iCo4()); + this.addMethod("iConomy", new com.garbagemule.register.payment.methods.iCo5()); + this.addMethod("BOSEconomy", new BOSE6()); + this.addMethod("BOSEconomy", new BOSE7()); + this.addMethod("Essentials", new com.garbagemule.register.payment.methods.EE17()); + } + + public Set getDependencies() { + return Dependencies; + } + + public Method createMethod(Plugin plugin) { + for (Method method: Methods) { + if (method.isCompatible(plugin)) { + method.setPlugin(plugin); + return method; + } + } + + return null; + } + + private void addMethod(String name, Method method) { + Dependencies.add(name); + Methods.add(method); + } + + public boolean hasMethod() { + return (Method != null); + } + + public boolean setMethod(Plugin method) { + if(hasMethod()) return true; + if(self) { self = false; return false; } + + int count = 0; + boolean match = false; + Plugin plugin; + PluginManager manager = method.getServer().getPluginManager(); + + for(String name: this.getDependencies()) { + if(hasMethod()) break; + if(method.getDescription().getName().equals(name)) plugin = method; else plugin = manager.getPlugin(name); + if(plugin == null) continue; + + Method current = this.createMethod(plugin); + if(current == null) continue; + + if(this.preferred.isEmpty()) + this.Method = current; + else { + this.Attachables.add(current); + } + } + + if(!this.preferred.isEmpty()) { + do { + if(hasMethod()) { + match = true; + } else { + for(Method attached: this.Attachables) { + if(attached == null) continue; + + if(hasMethod()) { + match = true; + break; + } + + if(this.preferred.isEmpty()) this.Method = attached; + + if(count == 0) { + if(this.preferred.equalsIgnoreCase(attached.getName())) + this.Method = attached; + } else { + this.Method = attached; + } + } + + count++; + } + } while(!match); + } + + return hasMethod(); + } + + public Method getMethod() { + return Method; + } + + public boolean checkDisabled(Plugin method) { + if(!hasMethod()) return true; + if (Method.isCompatible(method)) Method = null; + return (Method == null); + } +} diff --git a/src/com/garbagemule/register/payment/methods/BOSE.java b/src/com/garbagemule/register/payment/methods/BOSE.java new file mode 100644 index 0000000..1b73443 --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/BOSE.java @@ -0,0 +1,196 @@ +package com.garbagemule.register.payment.methods; + +import com.garbagemule.register.payment.Method; + +import cosine.boseconomy.BOSEconomy; +import org.bukkit.plugin.Plugin; + +public class BOSE implements Method { + private BOSEconomy BOSEconomy; + + public BOSEconomy getPlugin() { + return this.BOSEconomy; + } + + public String getName() { + return "BOSEconomy"; + } + + public String getVersion() { + return "0.6.2"; + } + + public String format(double amount) { + String currency = this.BOSEconomy.getMoneyNamePlural(); + if(amount == 1) currency = this.BOSEconomy.getMoneyName(); + return amount + " " + currency; + } + + public boolean hasBanks() { + return true; + } + + public boolean hasBank(String bank) { + return this.BOSEconomy.bankExists(bank); + } + + public boolean hasAccount(String name) { + return this.BOSEconomy.playerRegistered(name, false); + } + + public boolean hasBankAccount(String bank, String name) { + return this.BOSEconomy.isBankOwner(bank, name); + } + + public MethodAccount getAccount(String name) { + if(!hasAccount(name)) return null; + return new BOSEAccount(name, this.BOSEconomy); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + return new BOSEBankAccount(bank, name, BOSEconomy); + } + + public boolean isCompatible(Plugin plugin) { + return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") && plugin instanceof BOSEconomy; + } + + public void setPlugin(Plugin plugin) { + BOSEconomy = (BOSEconomy)plugin; + } + + public class BOSEAccount implements MethodAccount { + private String name; + private BOSEconomy BOSEconomy; + + public BOSEAccount(String name, BOSEconomy bOSEconomy) { + this.name = name; + this.BOSEconomy = bOSEconomy; + } + + public double balance() { + return Double.valueOf(this.BOSEconomy.getPlayerMoney(this.name)); + } + + public boolean set(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); + } + + public boolean add(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); + } + + public boolean subtract(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); + } + + public boolean multiply(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); + } + + public boolean divide(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return false; + } + } + + public class BOSEBankAccount implements MethodBankAccount { + private String bank; + private String name; + private BOSEconomy BOSEconomy; + + public BOSEBankAccount(String bank, String name, BOSEconomy bOSEconomy) { + this.name = name; + this.bank = bank; + this.BOSEconomy = bOSEconomy; + } + + public String getBankName() { + return this.bank; + } + + public int getBankId() { + return -1; + } + + public double balance() { + return Double.valueOf(this.BOSEconomy.getBankMoney(name)); + } + + public boolean set(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setBankMoney(name, IntAmount, true); + } + + public boolean add(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(this.name, (balance + IntAmount), false); + } + + public boolean subtract(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(this.name, (balance - IntAmount), false); + } + + public boolean multiply(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(this.name, (balance * IntAmount), false); + } + + public boolean divide(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(this.name, (balance / IntAmount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return this.BOSEconomy.removeBank(bank); + } + } +} \ No newline at end of file diff --git a/src/com/garbagemule/register/payment/methods/BOSE6.java b/src/com/garbagemule/register/payment/methods/BOSE6.java new file mode 100644 index 0000000..3ca97f6 --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/BOSE6.java @@ -0,0 +1,195 @@ +package com.garbagemule.register.payment.methods; + +import com.garbagemule.register.payment.Method; + +import cosine.boseconomy.BOSEconomy; +import org.bukkit.plugin.Plugin; + +public class BOSE6 implements Method { + private BOSEconomy BOSEconomy; + + public BOSEconomy getPlugin() { + return this.BOSEconomy; + } + + public String getName() { + return "BOSEconomy"; + } + + public String getVersion() { + return "0.6.2"; + } + + public String format(double amount) { + String currency = this.BOSEconomy.getMoneyNamePlural(); + if(amount == 1) currency = this.BOSEconomy.getMoneyName(); + return amount + " " + currency; + } + + public boolean hasBanks() { + return true; + } + + public boolean hasBank(String bank) { + return this.BOSEconomy.bankExists(bank); + } + + public boolean hasAccount(String name) { + return this.BOSEconomy.playerRegistered(name, false); + } + + public boolean hasBankAccount(String bank, String name) { + return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); + } + + public MethodAccount getAccount(String name) { + if(!hasAccount(name)) return null; + return new BOSEAccount(name, this.BOSEconomy); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + if(!hasBankAccount(bank, name)) return null; + return new BOSEBankAccount(bank, BOSEconomy); + } + + public boolean isCompatible(Plugin plugin) { + return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") && plugin instanceof BOSEconomy && plugin.getDescription().getVersion().equals("0.6.2"); + } + + public void setPlugin(Plugin plugin) { + BOSEconomy = (BOSEconomy)plugin; + } + + public class BOSEAccount implements MethodAccount { + private String name; + private BOSEconomy BOSEconomy; + + public BOSEAccount(String name, BOSEconomy bOSEconomy) { + this.name = name; + this.BOSEconomy = bOSEconomy; + } + + public double balance() { + return Double.valueOf(this.BOSEconomy.getPlayerMoney(this.name)); + } + + public boolean set(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setPlayerMoney(this.name, IntAmount, false); + } + + public boolean add(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.addPlayerMoney(this.name, IntAmount, false); + } + + public boolean subtract(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance - IntAmount), false); + } + + public boolean multiply(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance * IntAmount), false); + } + + public boolean divide(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance / IntAmount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return false; + } + } + + public class BOSEBankAccount implements MethodBankAccount { + private String bank; + private BOSEconomy BOSEconomy; + + public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) { + this.bank = bank; + this.BOSEconomy = bOSEconomy; + } + + public String getBankName() { + return this.bank; + } + + public int getBankId() { + return -1; + } + + public double balance() { + return Double.valueOf(this.BOSEconomy.getBankMoney(bank)); + } + + public boolean set(double amount) { + int IntAmount = (int)Math.ceil(amount); + return this.BOSEconomy.setBankMoney(bank, IntAmount, true); + } + + public boolean add(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance + IntAmount), false); + } + + public boolean subtract(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance - IntAmount), false); + } + + public boolean multiply(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance * IntAmount), false); + } + + public boolean divide(double amount) { + int IntAmount = (int)Math.ceil(amount); + int balance = (int)this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance / IntAmount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return this.BOSEconomy.removeBank(bank); + } + } +} \ No newline at end of file diff --git a/src/com/garbagemule/register/payment/methods/BOSE7.java b/src/com/garbagemule/register/payment/methods/BOSE7.java new file mode 100644 index 0000000..18e98fa --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/BOSE7.java @@ -0,0 +1,189 @@ +package com.garbagemule.register.payment.methods; + +import com.garbagemule.register.payment.Method; + +import cosine.boseconomy.BOSEconomy; +import org.bukkit.plugin.Plugin; + +/** + * @author Acrobot + */ + +public class BOSE7 implements Method { + private BOSEconomy BOSEconomy; + + public BOSEconomy getPlugin() { + return this.BOSEconomy; + } + + public String getName() { + return "BOSEconomy"; + } + + public String getVersion() { + return "0.7.0"; + } + + public String format(double amount) { + String currency = this.BOSEconomy.getMoneyNamePlural(); + if(amount == 1) currency = this.BOSEconomy.getMoneyName(); + return amount + " " + currency; + } + + public boolean hasBanks() { + return true; + } + + public boolean hasBank(String bank) { + return this.BOSEconomy.bankExists(bank); + } + + public boolean hasAccount(String name) { + return this.BOSEconomy.playerRegistered(name, false); + } + + public boolean hasBankAccount(String bank, String name) { + return this.BOSEconomy.isBankOwner(bank, name) || this.BOSEconomy.isBankMember(bank, name); + } + + public MethodAccount getAccount(String name) { + if(!hasAccount(name)) return null; + return new BOSEAccount(name, this.BOSEconomy); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + if(!hasBankAccount(bank, name)) return null; + return new BOSEBankAccount(bank, BOSEconomy); + } + + public boolean isCompatible(Plugin plugin) { + return plugin.getDescription().getName().equalsIgnoreCase("boseconomy") && plugin instanceof BOSEconomy && !plugin.getDescription().getVersion().equals("0.6.2"); + } + + public void setPlugin(Plugin plugin) { + BOSEconomy = (BOSEconomy)plugin; + } + + public class BOSEAccount implements MethodAccount { + private String name; + private BOSEconomy BOSEconomy; + + public BOSEAccount(String name, BOSEconomy bOSEconomy) { + this.name = name; + this.BOSEconomy = bOSEconomy; + } + + public double balance() { + return this.BOSEconomy.getPlayerMoneyDouble(this.name); + } + + public boolean set(double amount) { + return this.BOSEconomy.setPlayerMoney(this.name, amount, false); + } + + public boolean add(double amount) { + return this.BOSEconomy.addPlayerMoney(this.name, amount, false); + } + + public boolean subtract(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance - amount), false); + } + + public boolean multiply(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance * amount), false); + } + + public boolean divide(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setPlayerMoney(this.name, (balance / amount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return false; + } + } + + public class BOSEBankAccount implements MethodBankAccount { + private String bank; + private BOSEconomy BOSEconomy; + + public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) { + this.bank = bank; + this.BOSEconomy = bOSEconomy; + } + + public String getBankName() { + return this.bank; + } + + public int getBankId() { + return -1; + } + + public double balance() { + return this.BOSEconomy.getBankMoneyDouble(bank); + } + + public boolean set(double amount) { + return this.BOSEconomy.setBankMoney(bank, amount, true); + } + + public boolean add(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance + amount), false); + } + + public boolean subtract(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance - amount), false); + } + + public boolean multiply(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance * amount), false); + } + + public boolean divide(double amount) { + double balance = this.balance(); + return this.BOSEconomy.setBankMoney(bank, (balance / amount), false); + } + + public boolean hasEnough(double amount) { + return (this.balance() >= amount); + } + + public boolean hasOver(double amount) { + return (this.balance() > amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return (this.balance() < 0); + } + + public boolean remove() { + return this.BOSEconomy.removeBank(bank); + } + } +} \ No newline at end of file diff --git a/src/com/garbagemule/register/payment/methods/EE17.java b/src/com/garbagemule/register/payment/methods/EE17.java new file mode 100644 index 0000000..388483f --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/EE17.java @@ -0,0 +1,200 @@ +package com.garbagemule.register.payment.methods; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.api.Economy; +import com.earth2me.essentials.api.NoLoanPermittedException; +import com.earth2me.essentials.api.UserDoesNotExistException; +import com.garbagemule.register.payment.Method; + + +import org.bukkit.plugin.Plugin; + +public class EE17 implements Method { + private Essentials Essentials; + + public Essentials getPlugin() { + return this.Essentials; + } + + public String getName() { + return "Essentials"; + } + + public String getVersion() { + return "2.2"; + } + + public String format(double amount) { + return Economy.format(amount); + } + + public boolean hasBanks() { + return false; + } + + public boolean hasBank(String bank) { + return false; + } + + public boolean hasAccount(String name) { + return Economy.playerExists(name); + } + + public boolean hasBankAccount(String bank, String name) { + return false; + } + + public MethodAccount getAccount(String name) { + if(!hasAccount(name)) return null; + return new EEcoAccount(name); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + return null; + } + + public boolean isCompatible(Plugin plugin) { + try { Class.forName("com.earth2me.essentials.api.Economy"); } + catch(Exception e) { return false; } + + return plugin.getDescription().getName().equalsIgnoreCase("essentials") && plugin instanceof Essentials; + } + + public void setPlugin(Plugin plugin) { + Essentials = (Essentials)plugin; + } + + public class EEcoAccount implements MethodAccount { + private String name; + + public EEcoAccount(String name) { + this.name = name; + } + + public double balance() { + Double balance = 0.0; + + try { + balance = Economy.getMoney(this.name); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] Failed to grab balance in Essentials Economy: " + ex.getMessage()); + } + + return balance; + } + + public boolean set(double amount) { + try { + Economy.setMoney(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + return false; + } catch (NoLoanPermittedException ex) { + System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); + return false; + } + + return true; + } + + public boolean add(double amount) { + try { + Economy.add(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + return false; + } catch (NoLoanPermittedException ex) { + System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); + return false; + } + + return true; + } + + public boolean subtract(double amount) { + try { + Economy.subtract(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + return false; + } catch (NoLoanPermittedException ex) { + System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); + return false; + } + + return true; + } + + public boolean multiply(double amount) { + try { + Economy.multiply(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + return false; + } catch (NoLoanPermittedException ex) { + System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); + return false; + } + + return true; + } + + public boolean divide(double amount) { + try { + Economy.divide(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + return false; + } catch (NoLoanPermittedException ex) { + System.out.println("[REGISTER] No loan permitted in Essentials Economy: " + ex.getMessage()); + return false; + } + + return true; + } + + public boolean hasEnough(double amount) { + try { + return Economy.hasEnough(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + } + + return false; + } + + public boolean hasOver(double amount) { + try { + return Economy.hasMore(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + } + + return false; + } + + public boolean hasUnder(double amount) { + try { + return Economy.hasLess(name, amount); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + } + + return false; + } + + public boolean isNegative() { + try { + return Economy.isNegative(name); + } catch (UserDoesNotExistException ex) { + System.out.println("[REGISTER] User does not exist in Essentials Economy: " + ex.getMessage()); + } + + return false; + } + + public boolean remove() { + return false; + } + } +} \ No newline at end of file diff --git a/src/com/garbagemule/register/payment/methods/iCo4.java b/src/com/garbagemule/register/payment/methods/iCo4.java new file mode 100644 index 0000000..2c96115 --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/iCo4.java @@ -0,0 +1,128 @@ +package com.garbagemule.register.payment.methods; + +import com.garbagemule.register.payment.Method; +import com.nijiko.coelho.iConomy.iConomy; +import com.nijiko.coelho.iConomy.system.Account; + + +import org.bukkit.plugin.Plugin; + +public class iCo4 implements Method { + private iConomy iConomy; + + public iConomy getPlugin() { + return this.iConomy; + } + + public String getName() { + return "iConomy"; + } + + public String getVersion() { + return "4"; + } + + public String format(double amount) { + return this.iConomy.getBank().format(amount); + } + + public boolean hasBanks() { + return false; + } + + public boolean hasBank(String bank) { + return false; + } + + public boolean hasAccount(String name) { + return this.iConomy.getBank().hasAccount(name); + } + + public boolean hasBankAccount(String bank, String name) { + return false; + } + + public MethodAccount getAccount(String name) { + return new iCoAccount(this.iConomy.getBank().getAccount(name)); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + return null; + } + + public boolean isCompatible(Plugin plugin) { + return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && !plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy; + } + + public void setPlugin(Plugin plugin) { + iConomy = (iConomy)plugin; + } + + public class iCoAccount implements MethodAccount { + private Account account; + + public iCoAccount(Account account) { + this.account = account; + } + + public Account getiCoAccount() { + return account; + } + + public double balance() { + return this.account.getBalance(); + } + + public boolean set(double amount) { + if(this.account == null) return false; + this.account.setBalance(amount); + return true; + } + + public boolean add(double amount) { + if(this.account == null) return false; + this.account.add(amount); + return true; + } + + public boolean subtract(double amount) { + if(this.account == null) return false; + this.account.subtract(amount); + return true; + } + + public boolean multiply(double amount) { + if(this.account == null) return false; + this.account.multiply(amount); + return true; + } + + public boolean divide(double amount) { + if(this.account == null) return false; + this.account.divide(amount); + return true; + } + + public boolean hasEnough(double amount) { + return this.account.hasEnough(amount); + } + + public boolean hasOver(double amount) { + return this.account.hasOver(amount); + } + + public boolean hasUnder(double amount) { + return (this.balance() < amount); + } + + public boolean isNegative() { + return this.account.isNegative(); + } + + public boolean remove() { + if(this.account == null) return false; + this.account.remove(); + return true; + } + } +} diff --git a/src/com/garbagemule/register/payment/methods/iCo5.java b/src/com/garbagemule/register/payment/methods/iCo5.java new file mode 100644 index 0000000..2e0ede8 --- /dev/null +++ b/src/com/garbagemule/register/payment/methods/iCo5.java @@ -0,0 +1,211 @@ +package com.garbagemule.register.payment.methods; + +import com.garbagemule.register.payment.Method; +import com.iConomy.iConomy; +import com.iConomy.system.Account; +import com.iConomy.system.BankAccount; +import com.iConomy.system.Holdings; +import com.iConomy.util.Constants; + + +import org.bukkit.plugin.Plugin; + +public class iCo5 implements Method { + private iConomy iConomy; + + public iConomy getPlugin() { + return this.iConomy; + } + + public String getName() { + return "iConomy"; + } + + public String getVersion() { + return "5"; + } + + public String format(double amount) { + return this.iConomy.format(amount); + } + + public boolean hasBanks() { + return Constants.Banking; + } + + public boolean hasBank(String bank) { + return (!hasBanks()) ? false : this.iConomy.Banks.exists(bank); + } + + public boolean hasAccount(String name) { + return this.iConomy.hasAccount(name); + } + + public boolean hasBankAccount(String bank, String name) { + return (!hasBank(bank)) ? false : this.iConomy.getBank(bank).hasAccount(name); + } + + public MethodAccount getAccount(String name) { + return new iCoAccount(this.iConomy.getAccount(name)); + } + + public MethodBankAccount getBankAccount(String bank, String name) { + return new iCoBankAccount(this.iConomy.getBank(bank).getAccount(name)); + } + + public boolean isCompatible(Plugin plugin) { + return plugin.getDescription().getName().equalsIgnoreCase("iconomy") && plugin.getClass().getName().equals("com.iConomy.iConomy") && plugin instanceof iConomy; + } + + public void setPlugin(Plugin plugin) { + iConomy = (iConomy)plugin; + } + + public class iCoAccount implements MethodAccount { + private Account account; + private Holdings holdings; + + public iCoAccount(Account account) { + this.account = account; + this.holdings = account.getHoldings(); + } + + public Account getiCoAccount() { + return account; + } + + public double balance() { + return this.holdings.balance(); + } + + public boolean set(double amount) { + if(this.holdings == null) return false; + this.holdings.set(amount); + return true; + } + + public boolean add(double amount) { + if(this.holdings == null) return false; + this.holdings.add(amount); + return true; + } + + public boolean subtract(double amount) { + if(this.holdings == null) return false; + this.holdings.subtract(amount); + return true; + } + + public boolean multiply(double amount) { + if(this.holdings == null) return false; + this.holdings.multiply(amount); + return true; + } + + public boolean divide(double amount) { + if(this.holdings == null) return false; + this.holdings.divide(amount); + return true; + } + + public boolean hasEnough(double amount) { + return this.holdings.hasEnough(amount); + } + + public boolean hasOver(double amount) { + return this.holdings.hasOver(amount); + } + + public boolean hasUnder(double amount) { + return this.holdings.hasUnder(amount); + } + + public boolean isNegative() { + return this.holdings.isNegative(); + } + + public boolean remove() { + if(this.account == null) return false; + this.account.remove(); + return true; + } + } + + public class iCoBankAccount implements MethodBankAccount { + private BankAccount account; + private Holdings holdings; + + public iCoBankAccount(BankAccount account) { + this.account = account; + this.holdings = account.getHoldings(); + } + + public BankAccount getiCoBankAccount() { + return account; + } + + public String getBankName() { + return this.account.getBankName(); + } + + public int getBankId() { + return this.account.getBankId(); + } + + public double balance() { + return this.holdings.balance(); + } + + public boolean set(double amount) { + if(this.holdings == null) return false; + this.holdings.set(amount); + return true; + } + + public boolean add(double amount) { + if(this.holdings == null) return false; + this.holdings.add(amount); + return true; + } + + public boolean subtract(double amount) { + if(this.holdings == null) return false; + this.holdings.subtract(amount); + return true; + } + + public boolean multiply(double amount) { + if(this.holdings == null) return false; + this.holdings.multiply(amount); + return true; + } + + public boolean divide(double amount) { + if(this.holdings == null) return false; + this.holdings.divide(amount); + return true; + } + + public boolean hasEnough(double amount) { + return this.holdings.hasEnough(amount); + } + + public boolean hasOver(double amount) { + return this.holdings.hasOver(amount); + } + + public boolean hasUnder(double amount) { + return this.holdings.hasUnder(amount); + } + + public boolean isNegative() { + return this.holdings.isNegative(); + } + + public boolean remove() { + if(this.account == null) return false; + this.account.remove(); + return true; + } + } +}