Fucking hate git...

This commit is contained in:
garbagemule 2012-03-01 00:12:14 +01:00
parent 050cb5a408
commit 2e76b93837
29 changed files with 297 additions and 1540 deletions

127
build.xml
View File

@ -1,88 +1,121 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="MobArena" default="dist" basedir="."> <project name="MobArena" default="dist" basedir=".">
<property name="pluginname" value="MobArena" /> <property name="pluginname" value="MobArena" />
<!-- Folders -->
<property name="src" location="src" />
<property name="bin" location="build" />
<property name="lib" location="lib" />
<property name="res" location="resources" />
<property name="server" location="D:\General\Java\Minecraft\Minecraft Server\plugins" /> <property name="server" location="D:\General\Java\Minecraft\Minecraft Server\plugins" />
<property name="src" location="src" /> <property name="ability-src" location="abilities" />
<property name="test" location="test" /> <property name="ability-dest" location="${res}/res/abilities" />
<property name="bin" location="build" />
<property name="lib" location="lib" /> <!-- Dependency variables -->
<property name="res" location="resources" /> <property name="cbver" value="1.1-R4" />
<property name="cbjar" value="craftbukkit-${cbver}.jar" />
<property name="cburl" value="http://repo.bukkit.org/content/repositories/releases/org/bukkit/craftbukkit/${cbver}/${cbjar}" />
<property name="vltver" value="1.2.10" />
<property name="vltjar" value="Vault-${vltver}-SNAPSHOT.jar" />
<property name="vlturl" value="http://ci.milkbowl.net/job/Vault/Recommended%20Build/artifact/target/${vltjar}" />
<property name="herojar" value="Heroes.jar" />
<property name="herourl" value="http://ci.milkbowl.net/job/Heroes/Heroic%20Build/artifact/build/${herojar}" />
<property name="sptjar" value="SpoutPluginAPI.jar" />
<property name="spturl" value="http://ci.spout.org/job/SpoutPluginAPI/Recommended/artifact/target/${sptjar}" />
<property name="msjar" value="MagicSpells.jar" />
<property name="msurl" value="http://dev.bukkit.org/media/files/575/866/${msjar}" />
<path id="classpath"> <path id="classpath">
<fileset dir="${lib}" includes="**/*.jar" /> <fileset dir="${lib}" includes="*.jar" />
<fileset dir="${res}" includes="**/*.*" /> <!--<fileset dir="${res}" includes="**/*.*" />-->
<pathelement location="${bin}" /> <pathelement location="${bin}" />
</path> </path>
<fileset id="" dir="${src}">
</fileset>
<target name="clean"> <target name="clean">
<delete dir="${bin}" /> <delete dir="${bin}" />
</target> </target>
<target name="prepare"> <target name="prepare-bin">
<mkdir dir="${bin}" /> <mkdir dir="${bin}" />
</target> </target>
<!-- Compile the source and put in the bin-folder --> <target name="prepare-lib">
<target name="build-src" depends="prepare"> <mkdir dir="${lib}" />
<javac target="1.6" source="1.6"
srcdir="${src}" destdir="${bin}"
debug="on" debuglevel="lines,vars,source"
includeantruntime="no"
classpathref="classpath"/>
</target> </target>
<target name="build-src-with-deprecation-check" depends="prepare"> <target name="copy-abilities">
<mkdir dir="${ability-dest}" />
<copy toDir="${ability-dest}">
<fileset dir="${ability-src}" />
</copy>
</target>
<target name="cleanup-abilities">
<delete dir="${ability-dest}" />
</target>
<!-- Compile the source and put in the bin-folder -->
<target name="build-src" depends="prepare-bin">
<javac target="1.6" source="1.6" <javac target="1.6" source="1.6"
srcdir="${src}" destdir="${bin}" srcdir="${src}" destdir="${bin}"
debug="on" debuglevel="lines,vars,source" debug="on" debuglevel="lines,vars,source"
includeantruntime="no" includeantruntime="no">
classpathref="classpath"> <compilerarg value="-Xbootclasspath/p:${toString:classpath}"/>
<compilerarg value="-Xlint:deprecation"/>
</javac> </javac>
</target> </target>
<target name="build-test" depends="build-src"> <target name="build-src-with-deprecation-check" depends="prepare-bin">
<javac target="1.6" source="1.6" <javac target="1.6" source="1.6"
srcdir="${test}" destdir="${bin}" srcdir="${src}" destdir="${bin}"
debug="on" debuglevel="lines,vars,source" debug="on" debuglevel="lines,vars,source"
includeantruntime="no" classpathref="classpath" /> includeantruntime="no">
<compilerarg value="-Xlint:deprecation"/>
<compilerarg value="-Xbootclasspath/p:${toString:classpath}"/>
</javac>
</target> </target>
<!-- Build a .jar and copy to server's plugins-folder --> <!-- Build a .jar and copy to server's plugins-folder -->
<target name="dist" depends="build-src"> <target name="dist" depends="build-src-with-deprecation-check, copy-abilities">
<delete file="${pluginname}.jar" /> <delete file="${pluginname}.jar" />
<jar jarfile="${pluginname}.jar"> <jar jarfile="${pluginname}.jar">
<!-- Include the class-files (bin) and the resources (res) --> <!-- Include the class-files (bin) and the resources (res) -->
<fileset dir="${bin}" /> <fileset dir="${bin}" />
<fileset dir="${res}" /> <fileset dir="${res}" />
<!-- Set up the classpath so MobArena can find JDOM if needed -->
<manifest>
<attribute name="Main-Class" value="com.garbagemule.MobArena.MobArena" />
<attribute name="Class-Path" value="plugins/MobArena/lib/jdom.jar MobArena/lib/jdom.jar" />
</manifest>
</jar> </jar>
<!-- Copy to server and clean up --> <!-- Copy to server -->
<copy file="${pluginname}.jar" tofile="${server}/${pluginname}.jar" /> <copy file="${pluginname}.jar" tofile="${server}/${pluginname}.jar" />
<!--<delete dir="${bin}"/>--> <delete dir="${ability-dest}" />
</target> </target>
<target name="test-config" depends="build-test"> <!-- Download all dependency jars from the given URLs -->
<java classname="org.junit.runner.JUnitCore"> <target name="download-dependencies" depends="prepare-lib">
<arg value="garbagemule.mobarena.standard.config.TestNewConfigVsOldConfig" /> <get src="${cburl}"
<arg value="garbagemule.mobarena.standard.config.TestAdditionalConfigMethods" /> dest="${lib}/${cbjar}"
<arg value="garbagemule.mobarena.standard.config.TestConfigCorrectness" /> usetimestamp="true"
<classpath refid="classpath" /> skipexisting="true" />
</java> <get src="${vlturl}"
dest="${lib}/${vltjar}"
usetimestamp="true"
skipexisting="true" />
<get src="${herourl}"
dest="${lib}/${herojar}"
usetimestamp="true"
skipexisting="true" />
<get src="${spturl}"
dest="${lib}/${sptjar}"
usetimestamp="true"
skipexisting="true" />
<get src="${msurl}"
dest="${lib}/${msjar}"
usetimestamp="true"
skipexisting="true" />
</target> </target>
<target name="test-commands" depends="build-test">
<java classname="org.junit.runner.JUnitCore">
<arg value="garbagemule.mobarena.standard.TestUserCommands" />
<classpath refid="classpath" />
</java>
</target>
<target name="test" depends="test-config,
test-commands" />
</project> </project>

View File

@ -211,8 +211,8 @@ public class ArenaClass
String perm = entry.getKey() + ":" + entry.getValue(); String perm = entry.getKey() + ":" + entry.getValue();
String player = p.getName(); String player = p.getName();
plugin.warning("[PERM00] Failed to attach permission '" + perm + "' to player '" + player + " with class " + this.name Messenger.warning("[PERM00] Failed to attach permission '" + perm + "' to player '" + player + " with class " + this.name
+ "'.\nPlease verify that your class permissions are well-formed."); + "'.\nPlease verify that your class permissions are well-formed.");
} }
} }
return pa; return pa;

View File

@ -13,8 +13,9 @@ import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.ContainerBlock; import org.bukkit.block.ContainerBlock;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
//import org.bukkit.entity.EntityType; TODO USE THIS
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item; import org.bukkit.entity.Item;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -93,7 +94,7 @@ public class ArenaImpl implements Arena
private Map<Integer,List<ItemStack>> everyWaveMap, afterWaveMap; private Map<Integer,List<ItemStack>> everyWaveMap, afterWaveMap;
// Misc // Misc
private ArenaListenerImpl eventListener; private ArenaListener eventListener;
private List<ItemStack> entryFee; private List<ItemStack> entryFee;
//private ArenaLog log; //private ArenaLog log;
private TimeStrategy timeStrategy; private TimeStrategy timeStrategy;
@ -150,7 +151,7 @@ public class ArenaImpl implements Arena
this.afterWaveMap = MAUtils.getArenaRewardMap(plugin, config, name, "after"); this.afterWaveMap = MAUtils.getArenaRewardMap(plugin, config, name, "after");
// Misc // Misc
this.eventListener = new ArenaListenerImpl(this, plugin); this.eventListener = new ArenaListener(this, plugin);
this.entryFee = ItemParser.parseItems(settings.getString("entry-fee", "")); this.entryFee = ItemParser.parseItems(settings.getString("entry-fee", ""));
this.allowMonsters = world.getAllowMonsters(); this.allowMonsters = world.getAllowMonsters();
this.allowAnimals = world.getAllowAnimals(); this.allowAnimals = world.getAllowAnimals();
@ -295,7 +296,7 @@ public class ArenaImpl implements Arena
} }
@Override @Override
public ArenaListenerImpl getEventListener() { public ArenaListener getEventListener() {
return eventListener; return eventListener;
} }
@ -669,6 +670,7 @@ public class ArenaImpl implements Arena
p.getInventory().removeItem(new ItemStack(Material.BONE, petAmount)); p.getInventory().removeItem(new ItemStack(Material.BONE, petAmount));
for (int i = 0; i < petAmount; i++) { for (int i = 0; i < petAmount; i++) {
//Wolf wolf = (Wolf) world.spawnCreature(p.getLocation(), EntityType.WOLF); TODO USE THIS
Wolf wolf = (Wolf) world.spawnCreature(p.getLocation(), CreatureType.WOLF); Wolf wolf = (Wolf) world.spawnCreature(p.getLocation(), CreatureType.WOLF);
wolf.setTamed(true); wolf.setTamed(true);
wolf.setOwner(p); wolf.setOwner(p);
@ -937,7 +939,7 @@ public class ArenaImpl implements Arena
{ {
if (classes.isEmpty()) if (classes.isEmpty())
{ {
plugin.info("Player '" + p.getName() + "' has no class permissions!"); Messenger.info("Player '" + p.getName() + "' has no class permissions!");
playerLeave(p); playerLeave(p);
return; return;
} }
@ -972,8 +974,8 @@ public class ArenaImpl implements Arena
String perm = entry.getKey() + ":" + entry.getValue(); String perm = entry.getKey() + ":" + entry.getValue();
String name = p.getName(); String name = p.getName();
plugin.warning("[PERM01] Failed to remove permission attachment '" + perm + "' from player '" + name Messenger.warning("[PERM01] Failed to remove permission attachment '" + perm + "' from player '" + name
+ "'.\nThis should not be a big issue, but please verify that the player doesn't have any permissions they shouldn't have."); + "'.\nThis should not be a big issue, but please verify that the player doesn't have any permissions they shouldn't have.");
} }
} }
p.recalculatePermissions(); p.recalculatePermissions();

View File

@ -1,789 +0,0 @@
package com.garbagemule.MobArena;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.ContainerBlock;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Wolf;
import org.bukkit.event.Event.Result;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.EntityTargetEvent.TargetReason;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Attachable;
import org.bukkit.material.Bed;
import org.bukkit.material.Door;
import org.bukkit.material.Redstone;
import com.garbagemule.MobArena.MAUtils;
import com.garbagemule.MobArena.MobArena;
import com.garbagemule.MobArena.Msg;
import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.framework.ArenaListener;
import com.garbagemule.MobArena.leaderboards.Leaderboard;
import com.garbagemule.MobArena.region.ArenaRegion;
import com.garbagemule.MobArena.region.RegionPoint;
import com.garbagemule.MobArena.repairable.*;
import com.garbagemule.MobArena.util.TextUtils;
import com.garbagemule.MobArena.util.config.ConfigSection;
import com.garbagemule.MobArena.waves.MABoss;
public class ArenaListenerImpl implements ArenaListener
{
private MobArena plugin;
private Arena arena;
private ArenaRegion region;
private MonsterManager monsters;
private boolean softRestore,
softRestoreDrops,
protect;
private boolean monsterExp,
monsterInfight,
pvpEnabled,
foodRegen,
lockFoodLevel;
private boolean allowTeleport,
canShare,
allowMonsters;
private Set<Player> banned;
public ArenaListenerImpl(Arena arena, MobArena plugin) {
this.plugin = plugin;
this.arena = arena;
this.region = arena.getRegion();
this.monsters = arena.getMonsterManager();
/*
* TODO: Figure out if this is really a good idea + It saves needing all
* those methods in Arena.java + It is relatively simple + It would be
* fairly easy to implement an observer pattern - More private fields -
* Uglier code
*/
ConfigSection s = arena.getSettings();
this.softRestore = s.getBoolean("soft-restore", false);
this.softRestoreDrops = s.getBoolean("soft-restore-drops", false);
this.protect = s.getBoolean("protect", true);
this.monsterExp = s.getBoolean("monster-exp", false);
this.monsterInfight = s.getBoolean("monster-infight", false);
this.pvpEnabled = s.getBoolean("pvp-enabled", false);
this.foodRegen = s.getBoolean("food-regen", false);
this.lockFoodLevel = s.getBoolean("lock-food-level", true);
this.allowTeleport = s.getBoolean("allow-teleporting", false);
this.canShare = s.getBoolean("share-items-in-arena", true);
this.allowMonsters = arena.getWorld().getAllowMonsters();
this.banned = new HashSet<Player>();
}
public void onBlockBreak(BlockBreakEvent event) {
if (onBlockDestroy(event))
return;
event.setCancelled(true);
}
public void onBlockBurn(BlockBurnEvent event) {
if (onBlockDestroy(event))
return;
event.setCancelled(true);
}
private boolean onBlockDestroy(BlockEvent event) {
if (!arena.getRegion().contains(event.getBlock().getLocation()) || arena.inEditMode() || (!arena.isProtected() && arena.isRunning()))
return true;
Block b = event.getBlock();
if (arena.removeBlock(b) || b.getType() == Material.TNT)
return true;
if (softRestore && arena.isRunning()) {
BlockState state = b.getState();
Repairable r = null;
if (state instanceof ContainerBlock)
r = new RepairableContainer(state);
else if (state instanceof Sign)
r = new RepairableSign(state);
else if (state.getData() instanceof Attachable)
r = new RepairableAttachable(state);
else
r = new RepairableBlock(state);
arena.addRepairable(r);
if (!softRestoreDrops)
b.setTypeId(0);
return true;
}
return false;
}
public void onBlockPlace(BlockPlaceEvent event) {
Block b = event.getBlock();
// If the event didn't happen in the region, or if in edit mode, ignore
if (!arena.getRegion().contains(b.getLocation()) || arena.inEditMode()) {
return;
}
// If the arena isn't running, or if the player isn't in the arena,
// cancel.
if (!arena.isRunning() || !arena.inArena(event.getPlayer())) {
event.setCancelled(true);
return;
}
// Otherwise, block was placed during a session.
arena.addBlock(b);
switch (b.getType()){
// For doors, add the block just above (so we get both halves)
case WOODEN_DOOR:
case IRON_DOOR_BLOCK:
arena.addBlock(b.getRelative(0, 1, 0));
break;
}
}
public void onBlockForm(BlockFormEvent event) {
if (!arena.getRegion().contains(event.getBlock().getLocation()))
return;
// If a snowman forms some snow on its path, add the block
if (event.getNewState().getType() == Material.SNOW)
arena.addBlock(event.getBlock());
}
public void onBlockIgnite(BlockIgniteEvent event) {
if (!arena.getRegion().contains(event.getBlock().getLocation()))
return;
switch (event.getCause()){
case LIGHTNING:
case SPREAD:
event.setCancelled(true);
break;
case FLINT_AND_STEEL:
if (arena.isRunning())
arena.addBlock(event.getBlock().getRelative(BlockFace.UP));
else
event.setCancelled(true);
break;
default:
break;
}
}
public void onSignChange(SignChangeEvent event) {
arena.setLeaderboard(new Leaderboard(plugin, arena, event.getBlock().getLocation()));
arena.getRegion().set(RegionPoint.LEADERBOARD, event.getBlock().getLocation());
Messenger.tellPlayer(event.getPlayer(), "Leaderboard made. Now set up the stat signs!");
}
public void onCreatureSpawn(CreatureSpawnEvent event) {
if (!arena.getRegion().contains(event.getLocation())) {
if (!event.isCancelled()) {
event.setCancelled(!allowMonsters);
}
return;
}
if (event.getSpawnReason() != SpawnReason.CUSTOM) {
event.setCancelled(true);
return;
}
LivingEntity entity = (LivingEntity) event.getEntity();
if (arena.isRunning() && entity instanceof Slime)
monsters.addMonster(entity);
// If running == true, setCancelled(false), and vice versa.
event.setCancelled(!arena.isRunning());
}
public void onEntityExplode(EntityExplodeEvent event) {
if (!monsters.getMonsters().contains(event.getEntity()) && !arena.getRegion().contains(event.getLocation(), 10))
return;
monsters.removeMonster(event.getEntity());
// Cancel if the arena isn't running
if (!arena.isRunning()) {
event.setCancelled(true);
return;
}
// Uncancel, just in case.
event.setCancelled(false);
// If the arena isn't destructible, just clear the blocklist.
if (!softRestore && protect) {
List<Block> blocks = new LinkedList<Block>(arena.getBlocks());
event.blockList().retainAll(blocks);
return;
}
if (!softRestoreDrops)
event.setYield(0);
// Handle all the blocks in the block list.
for (Block b : event.blockList()) {
BlockState state = b.getState();
if (state.getData() instanceof Door && ((Door) state.getData()).isTopHalf()) {
state = b.getRelative(BlockFace.DOWN).getState();
}
else if (state.getData() instanceof Bed && ((Bed) state.getData()).isHeadOfBed()) {
state = b.getRelative(((Bed) state.getData()).getFacing().getOppositeFace()).getState();
}
// Create a Repairable from the block.
Repairable r = null;
if (state instanceof ContainerBlock)
r = new RepairableContainer(state);
else if (state instanceof Sign)
r = new RepairableSign(state);
else if (state.getData() instanceof Bed)
r = new RepairableBed(state);
else if (state.getData() instanceof Door)
r = new RepairableDoor(state);
else if (state.getData() instanceof Attachable || state.getData() instanceof Redstone)
r = new RepairableAttachable(state);
else
r = new RepairableBlock(state);
// Cakes and liquids should just get removed. If player-placed block, drop as item.
Material mat = state.getType();
if (mat == Material.CAKE_BLOCK || mat == Material.WATER || mat == Material.LAVA)
arena.removeBlock(b);
else if (arena.removeBlock(b))
arena.getWorld().dropItemNaturally(b.getLocation(), new ItemStack(state.getTypeId(), 1));
else if (softRestore)
arena.addRepairable(r);
else
arena.queueRepairable(r);
}
}
/******************************************************
*
* DEATH LISTENERS
*
******************************************************/
public void onEntityDeath(EntityDeathEvent event) {
if (event instanceof PlayerDeathEvent) {
onPlayerDeath((PlayerDeathEvent) event, (Player) event.getEntity());
}
else if (monsters.removeMonster(event.getEntity())) {
onMonsterDeath(event);
}
}
private void onPlayerDeath(PlayerDeathEvent event, Player player) {
if (arena.inArena(player) || arena.inLobby(player)) {
event.getDrops().clear();
event.setDroppedExp(0);
event.setKeepLevel(true);
arena.playerDeath(player);
}
}
public boolean onPlayerRespawn(PlayerRespawnEvent event) {
Player p = event.getPlayer();
if (!arena.isDead(p)) {
return false;
}
Location loc = arena.getRespawnLocation(p);
event.setRespawnLocation(loc);
arena.playerRespawn(p);
return true;
}
private void onMonsterDeath(EntityDeathEvent event) {
EntityDamageEvent e1 = event.getEntity().getLastDamageCause();
EntityDamageByEntityEvent e2 = (e1 instanceof EntityDamageByEntityEvent) ? (EntityDamageByEntityEvent) e1 : null;
Entity damager = (e2 != null) ? e2.getDamager() : null;
// Make sure to grab the owner of a projectile/pet
if (damager instanceof Projectile) {
damager = ((Projectile) damager).getShooter();
}
else if (damager instanceof Wolf && arena.hasPet(damager)) {
damager = (Player) ((Wolf) damager).getOwner();
}
// If the damager was a player, add to kills.
if (damager instanceof Player) {
ArenaPlayer ap = arena.getArenaPlayer((Player) damager);
if (ap != null) {
ArenaPlayerStatistics stats = ap.getStats();
if (stats != null) {
ap.getStats().inc("kills");
}
}
}
if (!monsterExp)
event.setDroppedExp(0);
event.getDrops().clear();
List<ItemStack> loot = monsters.getLoot(event.getEntity());
if (loot != null && !loot.isEmpty()) {
event.getDrops().add(getRandomItem(loot));
}
return;
}
private ItemStack getRandomItem(List<ItemStack> stacks) {
return stacks.get((new Random()).nextInt(stacks.size()));
}
/******************************************************
*
* DAMAGE LISTENERS
*
******************************************************/
public void onEntityDamage(EntityDamageEvent event) {
Entity damagee = event.getEntity();
if (!arena.isRunning() || !arena.getRegion().contains(damagee.getLocation())) {
return;
}
EntityDamageByEntityEvent edbe = (event instanceof EntityDamageByEntityEvent) ? (EntityDamageByEntityEvent) event : null;
Entity damager = null;
if (edbe != null) {
damager = edbe.getDamager();
if (damager instanceof Projectile) {
damager = ((Projectile) damager).getShooter();
}
else if (damager instanceof Wolf && arena.hasPet(damager)) {
damager = (Player) ((Wolf) damager).getOwner();
}
}
// Pet wolf
if (damagee instanceof Wolf && arena.hasPet(damagee)) {
onPetDamage(event, (Wolf) damagee, damager);
}
// Player
else if (damagee instanceof Player) {
onPlayerDamage(event, (Player) damagee, damager);
}
// Boss
else if (monsters.getBossMonsters().contains(damagee)) {
onBossDamage(event, (LivingEntity) damagee, damager);
}
// Regular monster
else if (monsters.getMonsters().contains(damagee)) {
onMonsterDamage(event, damagee, damager);
}
}
private void onPlayerDamage(EntityDamageEvent event, Player player, Entity damager) {
// Cancel all damage in the lobby and spec area
if (arena.inLobby(player) || arena.inSpec(player)) {
event.setCancelled(true);
return;
}
// If PvP is disabled and damager is a player, cancel damage
else if (arena.inArena(player)) {
if (!pvpEnabled && damager instanceof Player) {
event.setCancelled(true);
return;
}
event.setCancelled(false);
arena.getArenaPlayer(player).getStats().add("dmgTaken", event.getDamage());
}
}
private void onPetDamage(EntityDamageEvent event, Wolf pet, Entity damager) {
event.setCancelled(true);
}
private void onMonsterDamage(EntityDamageEvent event, Entity monster, Entity damager) {
if (damager instanceof Player) {
Player p = (Player) damager;
if (!arena.inArena(p)) {
event.setCancelled(true);
return;
}
ArenaPlayerStatistics aps = arena.getArenaPlayer(p).getStats();
aps.add("dmgDone", event.getDamage());
aps.inc("hits");
}
else if (damager instanceof Wolf && arena.hasPet(damager)) {
event.setDamage(1);
Player p = (Player) ((Wolf) damager).getOwner();
ArenaPlayerStatistics aps = arena.getArenaPlayer(p).getStats();
aps.add("dmgDone", event.getDamage());
// arena.getArenaPlayer(p).getStats().dmgDone += event.getDamage();
}
else if (damager instanceof LivingEntity) {
if (!monsterInfight)
event.setCancelled(true);
}
}
private void onBossDamage(EntityDamageEvent event, LivingEntity monster, Entity damager) {
// Health the boss back up.
monster.setHealth(monster.getMaxHealth());
// Damage the underlying MABoss.
MABoss boss = monsters.getBoss(monster);
boss.damage(event.getDamage());
// If it died, remove it from the arena.
if (boss.isDead()) {
monsters.removeBoss(monster);
monster.damage(10000);
}
// And "cancel out" the damage.
event.setDamage(1);
}
public void onEntityCombust(EntityCombustEvent event) {
if (monsters.getMonsters().contains(event.getEntity()))
event.setCancelled(true);
}
public void onEntityTarget(EntityTargetEvent event) {
if (!arena.isRunning() || event.isCancelled())
return;
if (arena.hasPet(event.getEntity())) {
if (event.getReason() != TargetReason.TARGET_ATTACKED_OWNER && event.getReason() != TargetReason.OWNER_ATTACKED_TARGET)
return;
if (!(event.getTarget() instanceof Player))
return;
// If the target is a player, cancel.
event.setCancelled(true);
}
else if (monsters.getMonsters().contains(event.getEntity())) {
if (event.getReason() == TargetReason.FORGOT_TARGET)
event.setTarget(MAUtils.getClosestPlayer(plugin, event.getEntity(), arena));
else if (event.getReason() == TargetReason.TARGET_DIED)
event.setTarget(MAUtils.getClosestPlayer(plugin, event.getEntity(), arena));
else if (event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY)
if (arena.hasPet(event.getTarget()))
event.setCancelled(true);
else if (event.getReason() == TargetReason.CLOSEST_PLAYER)
if (!arena.inArena((Player) event.getTarget()))
event.setCancelled(true);
}
}
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (arena.getRegion().contains(event.getBlock().getLocation()))
event.setCancelled(true);
}
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (!arena.isRunning())
return;
if (!(event.getEntity() instanceof Player) || !arena.inArena((Player) event.getEntity()))
return;
if (!foodRegen && event.getRegainReason() == RegainReason.SATIATED) {
event.setCancelled(true);
}
}
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (!arena.isRunning())
return;
if (!(event.getEntity() instanceof Player) || !arena.inArena((Player) event.getEntity()))
return;
// If the food level is locked, cancel all changes.
if (lockFoodLevel)
event.setCancelled(true);
}
public void onPlayerAnimation(PlayerAnimationEvent event) {
if (!arena.isRunning() || !arena.inArena(event.getPlayer()))
return;
arena.getArenaPlayer(event.getPlayer()).getStats().inc("swings");
}
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player p = event.getPlayer();
// If the player is active in the arena, only cancel if sharing is not
// allowed
if (arena.inArena(p)) {
if (!canShare) {
Messenger.tellPlayer(p, Msg.LOBBY_DROP_ITEM);
event.setCancelled(true);
}
}
// Else, if the player is in the lobby or a spectator, just cancel
else if (arena.inLobby(p) || arena.inSpec(p)) {
Messenger.tellPlayer(p, Msg.LOBBY_DROP_ITEM);
event.setCancelled(true);
}
/*
* If the player is not in the arena in any way (as arena player, lobby
* player or a spectator), but they -are- in the region, it must mean
* they are trying to drop items when not allowed
*/
else if (region.contains(p.getLocation())) {
Messenger.tellPlayer(p, Msg.LOBBY_DROP_ITEM);
event.setCancelled(true);
}
/*
* If the player is in the banned set, it means they got kicked or
* disconnected during a session, meaning they are more than likely
* trying to steal items, if a PlayerDropItemEvent is fired.
*/
else if (banned.contains(p)) {
plugin.warning("Player " + p.getName() + " tried to steal class items!");
event.setCancelled(true);
}
}
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (!arena.getReadyPlayersInLobby().contains(event.getPlayer()) && !arena.inArena(event.getPlayer()))
return;
if (!arena.isRunning()) {
event.getBlockClicked().getRelative(event.getBlockFace()).setTypeId(0);
event.setCancelled(true);
return;
}
Block liquid = event.getBlockClicked().getRelative(event.getBlockFace());
arena.addBlock(liquid);
}
public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
if (arena.inArena(p) || !arena.inLobby(p))
return;
// Player is in the lobby, so disallow using items.
Action a = event.getAction();
if (a == Action.RIGHT_CLICK_AIR || a == Action.RIGHT_CLICK_BLOCK) {
event.setUseItemInHand(Result.DENY);
event.setCancelled(true);
}
// If there's no block involved, just return.
if (!event.hasBlock())
return;
// Iron block
if (event.getClickedBlock().getTypeId() == 42) {
handleReadyBlock(p);
}
// Sign
else if (event.getClickedBlock().getState() instanceof Sign) {
Sign sign = (Sign) event.getClickedBlock().getState();
handleSign(sign, p);
}
}
private void handleReadyBlock(Player p) {
if (arena.getArenaPlayer(p).getArenaClass() != null) {
Messenger.tellPlayer(p, Msg.LOBBY_PLAYER_READY);
arena.playerReady(p);
}
else {
Messenger.tellPlayer(p, Msg.LOBBY_PICK_CLASS);
}
}
private void handleSign(Sign sign, Player p) {
// Check if the first line is a class name.
String className = ChatColor.stripColor(sign.getLine(0)).toLowerCase();
if (!arena.getClasses().containsKey(className) && !className.equals("random"))
return;
// Check for permission.
if (!plugin.has(p, "mobarena.classes." + className) && !className.equals("random")) {
Messenger.tellPlayer(p, Msg.LOBBY_CLASS_PERMISSION);
return;
}
// Delay the inventory stuff to ensure that right-clicking works.
delayAssignClass(p, className);
}
private void delayAssignClass(final Player p, final String className) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin,new Runnable() {
public void run() {
arena.assignClass(p, className);
if (!className.equalsIgnoreCase("random"))
Messenger.tellPlayer(p, Msg.LOBBY_CLASS_PICKED, TextUtils.camelCase(className), arena.getClassLogo(className));
else
Messenger.tellPlayer(p, Msg.LOBBY_CLASS_RANDOM);
}
});
}
public void onPlayerQuit(PlayerQuitEvent event) {
Player p = event.getPlayer();
if (!arena.isEnabled() || (!arena.inArena(p) && !arena.inLobby(p)))
return;
arena.playerLeave(p);
banned.add(p);
scheduleUnban(p, 20);
}
public void onPlayerKick(PlayerKickEvent event) {
Player p = event.getPlayer();
if (!arena.isEnabled() || (!arena.inArena(p) && !arena.inLobby(p))) {
return;
}
arena.playerLeave(p);
banned.add(p);
scheduleUnban(p, 20);
}
private void scheduleUnban(final Player p, int ticks) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
banned.remove(p);
}
}, ticks);
}
public TeleportResponse onPlayerTeleport(PlayerTeleportEvent event) {
if (!arena.isEnabled() || !region.isSetup() || arena.inEditMode() || allowTeleport) {
return TeleportResponse.IDGAF;
}
Location to = event.getTo();
Location from = event.getFrom();
Player p = event.getPlayer();
if (region.contains(from)) {
// Players not in the arena are free to warp out.
if (!arena.inArena(p) && !arena.inLobby(p) && !arena.inSpec(p)) {
return TeleportResponse.ALLOW;
}
// Covers the case in which both locations are in the arena.
if (region.contains(to) || region.isWarp(to) || to.equals(arena.getPlayerEntry(p))) {
return TeleportResponse.ALLOW;
}
Messenger.tellPlayer(p, Msg.WARP_FROM_ARENA);
return TeleportResponse.REJECT;
}
else if (region.contains(to)) {
if (region.isWarp(from) || region.isWarp(to) || to.equals(arena.getPlayerEntry(p))) {
return TeleportResponse.ALLOW;
}
Messenger.tellPlayer(p, Msg.WARP_TO_ARENA);
return TeleportResponse.REJECT;
}
return TeleportResponse.IDGAF;
}
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player p = event.getPlayer();
if (event.isCancelled() || (!arena.inArena(p) && !arena.inLobby(p))) {
return;
}
// This is safe, because commands will always have at least one element.
String base = event.getMessage().split(" ")[0];
// Check if the entire base command is allowed.
if (plugin.getArenaMaster().isAllowed(base)) {
return;
}
// If not, check if the specific command is allowed.
String noslash = event.getMessage().substring(1);
if (plugin.getArenaMaster().isAllowed(noslash)) {
return;
}
// This is dirty, but it ensures that commands are indeed blocked.
event.setMessage("/");
// Cancel the event regardless.
event.setCancelled(true);
Messenger.tellPlayer(p, Msg.MISC_COMMAND_NOT_ALLOWED);
}
}

View File

@ -294,7 +294,7 @@ public class ArenaMasterImpl implements ArenaMaster
// If the section doesn't exist, the class doesn't either. // If the section doesn't exist, the class doesn't either.
if (section == null) { if (section == null) {
plugin.error("Failed to load class '" + TextUtils.camelCase(className) + "'."); Messenger.severe("Failed to load class '" + TextUtils.camelCase(className) + "'.");
return null; return null;
} }
@ -489,14 +489,14 @@ public class ArenaMasterImpl implements ArenaMaster
world = plugin.getServer().getWorld(worldName); world = plugin.getServer().getWorld(worldName);
if (world == null) { if (world == null) {
plugin.error("The world '" + worldName + "' for arena '" + arenaName + "' does not exist!"); Messenger.severe("The world '" + worldName + "' for arena '" + arenaName + "' does not exist!");
return null; return null;
} }
} }
// Otherwise, use the default world. // Otherwise, use the default world.
else { else {
world = plugin.getServer().getWorlds().get(0); world = plugin.getServer().getWorlds().get(0);
plugin.warning("Could not find the world for arena '" + arenaName + "'. Using default world ('" + world.getName() + "')! Check the config-file!"); Messenger.warning("Could not find the world for arena '" + arenaName + "'. Using default world ('" + world.getName() + "')! Check the config-file!");
} }
// Assert all settings nodes. // Assert all settings nodes.

View File

@ -49,7 +49,7 @@ public class MAMessages
return true; return true;
} }
catch (Exception e) { catch (Exception e) {
plugin.warning("Couldn't initialize announcements-file. Using defaults."); Messenger.warning("Couldn't initialize announcements-file. Using defaults.");
return false; return false;
} }
} }
@ -74,7 +74,7 @@ public class MAMessages
} }
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
plugin.warning("Problem with announcements-file. Using defaults."); Messenger.warning("Problem with announcements-file. Using defaults.");
return; return;
} }
} }
@ -92,7 +92,7 @@ public class MAMessages
// Split the string by the equals-sign. // Split the string by the equals-sign.
String[] split = s.split("="); String[] split = s.split("=");
if (split.length != 2) { if (split.length != 2) {
plugin.warning("Couldn't parse \"" + s + "\". Check announcements-file."); Messenger.warning("Couldn't parse \"" + s + "\". Check announcements-file.");
return; return;
} }
@ -110,7 +110,7 @@ public class MAMessages
msg.setSpout(spoutVal); msg.setSpout(spoutVal);
} }
catch (Exception e) { catch (Exception e) {
plugin.warning(key + " is not a valid key. Check announcements-file."); Messenger.warning(key + " is not a valid key. Check announcements-file.");
return; return;
} }
} }

View File

@ -296,14 +296,14 @@ public class MASpawnThread implements Runnable
if (reward == null) { if (reward == null) {
Messenger.tellPlayer(p, "ERROR! Problem with rewards. Notify server host!"); Messenger.tellPlayer(p, "ERROR! Problem with rewards. Notify server host!");
plugin.warning("Could not add null reward. Please check the config-file!"); Messenger.warning("Could not add null reward. Please check the config-file!");
} }
else if (reward.getTypeId() == MobArena.ECONOMY_MONEY_ID) { else if (reward.getTypeId() == MobArena.ECONOMY_MONEY_ID) {
if (plugin.giveMoney(p, reward.getAmount())) { if (plugin.giveMoney(p, reward.getAmount())) {
Messenger.tellPlayer(p, Msg.WAVE_REWARD, plugin.economyFormat(reward.getAmount())); Messenger.tellPlayer(p, Msg.WAVE_REWARD, plugin.economyFormat(reward.getAmount()));
} }
else { else {
plugin.warning("Tried to add money, but no economy plugin detected!"); Messenger.warning("Tried to add money, but no economy plugin detected!");
} }
} }
else { else {

View File

@ -157,7 +157,7 @@ public class MAUtils
//for (Player p : arena.livePlayers) //for (Player p : arena.livePlayers)
for (Player p : arena.getPlayersInArena()) { for (Player p : arena.getPlayersInArena()) {
if (!arena.getWorld().equals(p.getWorld())) { if (!arena.getWorld().equals(p.getWorld())) {
plugin.info("Player '" + p.getName() + "' is not in the right world. Kicking..."); Messenger.info("Player '" + p.getName() + "' is not in the right world. Kicking...");
p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)"); p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)");
Messenger.tellPlayer(p, "You warped out of the arena world."); Messenger.tellPlayer(p, "You warped out of the arena world.");
continue; continue;
@ -179,7 +179,7 @@ public class MAUtils
catch (Exception e) { catch (Exception e) {
p.kickPlayer("Banned for life! No, but stop trying to cheat in MobArena!"); p.kickPlayer("Banned for life! No, but stop trying to cheat in MobArena!");
if (plugin != null) { if (plugin != null) {
plugin.warning(p.getName() + " tried to cheat in MobArena and has been kicked."); Messenger.warning(p.getName() + " tried to cheat in MobArena and has been kicked.");
} }
return Double.MAX_VALUE; return Double.MAX_VALUE;
} }
@ -247,7 +247,7 @@ public class MAUtils
buffy.append(", "); buffy.append(", ");
} }
else { else {
plugin.warning("Tried to do some money stuff, but no economy plugin was detected!"); Messenger.warning("Tried to do some money stuff, but no economy plugin was detected!");
return buffy.toString(); return buffy.toString();
} }
continue; continue;
@ -343,7 +343,7 @@ public class MAUtils
catch (Exception e) catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
plugin.warning("Couldn't create backup file. Aborting auto-generate..."); Messenger.warning("Couldn't create backup file. Aborting auto-generate...");
return false; return false;
} }
@ -481,7 +481,7 @@ public class MAUtils
} }
catch (Exception e) catch (Exception e)
{ {
if (error) plugin.warning("Couldn't find backup file for arena '" + name + "'"); if (error) Messenger.warning("Couldn't find backup file for arena '" + name + "'");
return false; return false;
} }

View File

@ -2,6 +2,7 @@ package com.garbagemule.MobArena;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Logger;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
@ -14,6 +15,12 @@ import com.garbagemule.MobArena.framework.Arena;
public class Messenger public class Messenger
{ {
private static final Logger log = Logger.getLogger("Minecraft");
private static final String prefix = "[MobArena] ";
private Messenger() {}
public static boolean tellSpoutPlayer(Player p, Msg msg, String s, Material logo) { public static boolean tellSpoutPlayer(Player p, Msg msg, String s, Material logo) {
// Grab the SpoutPlayer. // Grab the SpoutPlayer.
SpoutPlayer sp = MobArena.hasSpout ? SpoutManager.getPlayer(p) : null; SpoutPlayer sp = MobArena.hasSpout ? SpoutManager.getPlayer(p) : null;
@ -100,4 +107,16 @@ public class Messenger
public static void tellAll(Arena arena, Msg msg) { public static void tellAll(Arena arena, Msg msg) {
tellAll(arena, msg, null, false); tellAll(arena, msg, null, false);
} }
public static void info(String msg) {
log.info(prefix + msg);
}
public static void warning(String msg) {
log.warning(prefix + msg);
}
public static void severe(String msg) {
log.severe(prefix + msg);
}
} }

View File

@ -33,6 +33,7 @@ import com.garbagemule.MobArena.util.FileUtils;
import com.garbagemule.MobArena.util.config.Config; import com.garbagemule.MobArena.util.config.Config;
import com.garbagemule.MobArena.util.config.ConfigUtils; import com.garbagemule.MobArena.util.config.ConfigUtils;
import com.garbagemule.MobArena.util.inventory.InventoryManager; import com.garbagemule.MobArena.util.inventory.InventoryManager;
import com.garbagemule.MobArena.waves.ability.AbilityManager;
/** /**
* MobArena * MobArena
@ -62,11 +63,11 @@ public class MobArena extends JavaPlugin
public void onEnable() { public void onEnable() {
// Create default files and initialize config-file // Create default files and initialize config-file
FileUtils.extractDefaults(this, "config.yml"); FileUtils.extractResource(this.getDataFolder(), "config.yml");
loadConfigFile(); loadConfigFile();
// Download external libraries if needed. // Load boss abilities
FileUtils.fetchLibs(this, config); loadAbilities();
// Set up soft dependencies // Set up soft dependencies
setupVault(); setupVault();
@ -89,7 +90,7 @@ public class MobArena extends JavaPlugin
registerListeners(); registerListeners();
// Announce enable! // Announce enable!
info("v" + this.getDescription().getVersion() + " enabled."); Messenger.info("v" + this.getDescription().getVersion() + " enabled.");
} }
public void onDisable() { public void onDisable() {
@ -103,7 +104,7 @@ public class MobArena extends JavaPlugin
} }
arenaMaster.resetArenaMap(); arenaMaster.resetArenaMap();
info("disabled."); Messenger.info("disabled.");
} }
private void loadConfigFile() { private void loadConfigFile() {
@ -145,15 +146,10 @@ public class MobArena extends JavaPlugin
return has((Player) sender, s); return has((Player) sender, s);
} }
// Console printing
public void info(String msg) { getServer().getLogger().info("[MobArena] " + msg); }
public void warning(String msg) { getServer().getLogger().warning("[MobArena] " + msg); }
public void error(String msg) { getServer().getLogger().severe("[MobArena] " + msg); }
private void setupVault() { private void setupVault() {
Plugin vaultPlugin = this.getServer().getPluginManager().getPlugin("Vault"); Plugin vaultPlugin = this.getServer().getPluginManager().getPlugin("Vault");
if (vaultPlugin == null) { if (vaultPlugin == null) {
warning("Vault was not found. Economy rewards will not work!"); Messenger.warning("Vault was not found. Economy rewards will not work!");
return; return;
} }
@ -163,7 +159,7 @@ public class MobArena extends JavaPlugin
if (e != null) { if (e != null) {
economy = e.getProvider(); economy = e.getProvider();
} else { } else {
warning("Vault found, but no economy plugin detected. Economy rewards will not work!"); Messenger.warning("Vault found, but no economy plugin detected. Economy rewards will not work!");
} }
} }
@ -192,6 +188,13 @@ public class MobArena extends JavaPlugin
healthStrategy = (hasHeroes ? new HealthStrategyHeroes() : new HealthStrategyStandard()); healthStrategy = (hasHeroes ? new HealthStrategyHeroes() : new HealthStrategyStandard());
} }
private void loadAbilities() {
File dir = new File(this.getDataFolder(), "abilities");
if (!dir.exists()) dir.mkdir();
AbilityManager.loadAbilities(dir);
}
public HealthStrategy getHealthStrategy() { public HealthStrategy getHealthStrategy() {
return healthStrategy; return healthStrategy;
} }

View File

@ -8,8 +8,6 @@ import com.garbagemule.MobArena.framework.Arena;
public class ArenaEndEvent extends Event implements Cancellable public class ArenaEndEvent extends Event implements Cancellable
{ {
private static final long serialVersionUID = -492437066028367597L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;

View File

@ -8,8 +8,6 @@ import com.garbagemule.MobArena.framework.Arena;
public class ArenaPlayerDeathEvent extends Event public class ArenaPlayerDeathEvent extends Event
{ {
private static final long serialVersionUID = 8945689670354700831L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Player player; private Player player;
private Arena arena; private Arena arena;

View File

@ -9,8 +9,6 @@ import com.garbagemule.MobArena.framework.Arena;
public class ArenaPlayerJoinEvent extends Event implements Cancellable public class ArenaPlayerJoinEvent extends Event implements Cancellable
{ {
private static final long serialVersionUID = -1205905192685201064L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Player player; private Player player;
private Arena arena; private Arena arena;

View File

@ -9,8 +9,6 @@ import com.garbagemule.MobArena.framework.Arena;
public class ArenaPlayerLeaveEvent extends Event implements Cancellable public class ArenaPlayerLeaveEvent extends Event implements Cancellable
{ {
private static final long serialVersionUID = -8942511403871825734L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Player player; private Player player;
private Arena arena; private Arena arena;

View File

@ -8,8 +8,6 @@ import com.garbagemule.MobArena.framework.Arena;
public class ArenaStartEvent extends Event implements Cancellable public class ArenaStartEvent extends Event implements Cancellable
{ {
private static final long serialVersionUID = 4414065978731456440L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;

View File

@ -9,8 +9,6 @@ import com.garbagemule.MobArena.waves.Wave;
public class NewWaveEvent extends Event implements Cancellable public class NewWaveEvent extends Event implements Cancellable
{ {
private static final long serialVersionUID = -8743818273565357180L;
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Arena arena; private Arena arena;
private boolean cancelled; private boolean cancelled;

View File

@ -11,7 +11,7 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.garbagemule.MobArena.ArenaClass; import com.garbagemule.MobArena.ArenaClass;
import com.garbagemule.MobArena.ArenaListenerImpl; import com.garbagemule.MobArena.ArenaListener;
import com.garbagemule.MobArena.ArenaPlayer; import com.garbagemule.MobArena.ArenaPlayer;
import com.garbagemule.MobArena.MASpawnThread; import com.garbagemule.MobArena.MASpawnThread;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MobArena;
@ -75,7 +75,7 @@ public interface Arena
public Location getPlayerEntry(Player p); public Location getPlayerEntry(Player p);
public ArenaListenerImpl getEventListener(); public ArenaListener getEventListener();
public void setLeaderboard(Leaderboard leaderboard); public void setLeaderboard(Leaderboard leaderboard);

View File

@ -1,44 +0,0 @@
package com.garbagemule.MobArena.framework;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
public interface ArenaListener
{
public enum TeleportResponse {
ALLOW, REJECT, IDGAF
}
public void onBlockBreak(BlockBreakEvent event);
public void onBlockPlace(BlockPlaceEvent event);
public void onBlockIgnite(BlockIgniteEvent event);
public void onCreatureSpawn(CreatureSpawnEvent event);
public void onEntityExplode(EntityExplodeEvent event);
public void onEntityCombust(EntityCombustEvent event);
public void onEntityTarget(EntityTargetEvent event);
public void onEntityRegainHealth(EntityRegainHealthEvent event);
public void onEntityDeath(EntityDeathEvent event);
public void onEntityDamage(EntityDamageEvent event);
public void onPlayerDropItem(PlayerDropItemEvent event);
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event);
public void onPlayerInteract(PlayerInteractEvent event);
public void onPlayerQuit(PlayerQuitEvent event);
public void onPlayerKick(PlayerKickEvent event);
public TeleportResponse onPlayerTeleport(PlayerTeleportEvent event);
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event);
}

View File

@ -12,6 +12,7 @@ import org.bukkit.block.Sign;
import com.garbagemule.MobArena.ArenaPlayer; import com.garbagemule.MobArena.ArenaPlayer;
import com.garbagemule.MobArena.ArenaPlayerStatistics; import com.garbagemule.MobArena.ArenaPlayerStatistics;
import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MobArena;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
@ -122,7 +123,7 @@ public class Leaderboard
if (!(state instanceof Sign)) if (!(state instanceof Sign))
{ {
plugin.error("Leaderboards for '" + arena.configName() + "' could not be established!"); Messenger.severe("Leaderboards for '" + arena.configName() + "' could not be established!");
return false; return false;
} }

View File

@ -13,7 +13,6 @@ import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MobArena;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.framework.ArenaMaster; import com.garbagemule.MobArena.framework.ArenaMaster;
import com.garbagemule.MobArena.framework.ArenaListener.TeleportResponse;
import com.garbagemule.MobArena.leaderboards.Stats; import com.garbagemule.MobArena.leaderboards.Stats;
import com.garbagemule.MobArena.util.VersionChecker; import com.garbagemule.MobArena.util.VersionChecker;
@ -251,6 +250,10 @@ public class MAGlobalListener implements Listener
plugin.restoreInventory(event.getPlayer()); plugin.restoreInventory(event.getPlayer());
} }
public enum TeleportResponse {
ALLOW, REJECT, IDGAF
}
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void playerTeleport(PlayerTeleportEvent event) { public void playerTeleport(PlayerTeleportEvent event) {
if (!am.isEnabled()) return; if (!am.isEnabled()) return;
@ -275,4 +278,11 @@ public class MAGlobalListener implements Listener
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler(priority = EventPriority.NORMAL)
public void playerPreLogin(PlayerPreLoginEvent event) {
for (Arena arena : am.getArenas()) {
arena.getEventListener().onPlayerPreLogin(event);
}
}
} }

View File

@ -25,7 +25,7 @@ public class MagicSpellsListener implements Listener
this.plugin = plugin; this.plugin = plugin;
// Set up the MagicSpells config-file. // Set up the MagicSpells config-file.
File spellFile = FileUtils.extractFile(plugin, plugin.getDataFolder(), "magicspells.yml"); File spellFile = FileUtils.extractResource(plugin.getDataFolder(), "magicspells.yml");
Config spellConfig = new Config(spellFile); Config spellConfig = new Config(spellFile);
spellConfig.load(); spellConfig.load();
setupSpells(spellConfig); setupSpells(spellConfig);

View File

@ -3,224 +3,89 @@ package com.garbagemule.MobArena.util;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.util.ArrayList;
import java.lang.reflect.Method; import java.util.List;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
//import org.bukkit.util.config.Configuration;
import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MobArena;
import com.garbagemule.MobArena.util.config.Config;
import com.garbagemule.MobArena.waves.WaveUtils;
public class FileUtils public class FileUtils
{ {
public static enum Library /**
{ * Extracts all of the given resources to the given directory.
XML("jdom.jar", "http://mirrors.ibiblio.org/pub/mirrors/maven2/org/jdom/jdom/1.1/jdom-1.1.jar", "http://garbagemule.binhoster.com/Minecraft/MobArena/jdom-1.1.jar");//"org.jdom.Content"); * Note that even if the resources have different paths, they will all
* be extracted to the given directory.
* @param dir a directory
* @param resources an array of resources to extract
* @return a list of all the files that were written
*/
public static List<File> extractResources(File dir, String... resources) {
List<File> files = new ArrayList<File>();
public String filename, url, backup; for (String resource : resources) {
File file = extractResource(dir, resource);
private Library(String filename, String url, String backup) if (file != null) {
{ files.add(file);
this.filename = filename; }
this.url = url;
this.backup = backup;
}
public static Library fromString(String string)
{
return WaveUtils.getEnumFromString(Library.class, string);
} }
return files;
} }
/** /**
* Download all necessary libraries. * Extracts the given resource to the given directory.
* @param config The MobArena config-file * @param dir a directory
* @param resource a resource to extract
* @return the file that was written, or null
*/ */
public static void fetchLibs(MobArena plugin, Config config) public static File extractResource(File dir, String resource) {
{ if (!dir.exists()) dir.mkdirs();
// Get all arenas
Set<String> arenas = config.getKeys("arenas");
if (arenas == null) return;
// Add all the logging types // Set up our new file.
Set<Library> libs = new HashSet<Library>(); String filename = getFilename(resource);
for (String a : arenas)
{
String type = config.getString("arenas." + a + ".settings.logging", "").toLowerCase();
Library lib = Library.fromString(type.toUpperCase());
if (lib != null)
libs.add(lib);
}
// Download all libraries
for (Library lib : libs)
if (!libraryExists(plugin, lib))
fetchLib(plugin, lib);
}
/**
* Download a given library.
* @param lib The Library to download
*/
private static synchronized void fetchLib(MobArena plugin, Library lib)
{
plugin.info("Downloading library '" + lib.filename + "' for log-method '" + lib.name().toLowerCase() + "'...");
URLConnection con = null;
InputStream in = null;
OutputStream out = null;
// Open a connection
try
{
con = new URL(lib.url).openConnection();
con.setConnectTimeout(2000);
con.setUseCaches(true);
}
catch (Exception e)
{
if (lib.backup == null)
{
e.printStackTrace();
plugin.warning("Connection issues");
return;
}
try
{
con = new URL(lib.backup).openConnection();
con.setConnectTimeout(2000);
con.setUseCaches(true);
}
catch (Exception e2)
{
e2.printStackTrace();
plugin.warning("Connection issues");
return;
}
}
try
{
File libdir = new File(plugin.getDataFolder(), "lib");
libdir.mkdir();
File file = new File(libdir, lib.filename);
long startTime = System.currentTimeMillis();
// Set up the streams
in = con.getInputStream();
out = new FileOutputStream(file);
if (in == null || out == null) return;
byte[] buffer = new byte[65536];
int length = 0;
// Write the library to disk
while ((length = in.read(buffer)) > 0)
out.write(buffer, 0, length);
// Announce successful download
plugin.info(lib.filename + " downloaded in " + ((System.currentTimeMillis()-startTime)/1000.0) + " seconds.");
addLibraryToClassLoader(file);
}
catch (Exception e)
{
e.printStackTrace();
plugin.warning("Couldn't download library: " + lib.filename);
}
finally
{
try
{
if (in != null) in.close();
if (out != null) out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
private static boolean libraryExists(JavaPlugin plugin, Library lib) {
return new File(plugin.getDataFolder() + File.separator + "lib", lib.filename).exists();
}
private static void addLibraryToClassLoader(File file) {
try {
// Grab the class loader and its addURL method
URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class });
addURL.setAccessible(true);
// Add the library
addURL.invoke(cl, new Object[]{file.toURI().toURL()});
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create default files from the res/ directory, if they exist.
* @param filenames Files to be created.
*/
public static void extractDefaults(MobArena plugin, String... filenames) {
File dir = plugin.getDataFolder();
if (!dir.exists()) dir.mkdir();
for (String filename : filenames)
extractFile(plugin, dir, filename);
}
public static File extractFile(MobArena plugin, File dir, String filename) {
// Skip if file exists
File file = new File(dir, filename); File file = new File(dir, filename);
// If the file already exists, don't do anything.
if (file.exists()) return file; if (file.exists()) return file;
// Skip if there is no resource with that name // Grab the resource input stream.
InputStream in = MobArena.class.getResourceAsStream("/res/" + filename); InputStream in = MobArena.class.getResourceAsStream("/res/" + resource);
if (in == null) return null; if (in == null) return null;
try { try {
// Set up an output stream // Set up an output stream.
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[8192]; byte[] buffer = new byte[4096];
int length = 0;
// Write the resource data to the file // Read into the buffer and write it out to the file.
while ((length = in.read(buffer)) > 0) int read = 0;
out.write(buffer, 0, length); while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
if (in != null) in.close(); // Close stuff.
if (out != null) out.close(); in.close();
out.close();
// Return the new file.
return file; return file;
} }
catch (Exception e) { catch (Exception e) {}
e.printStackTrace();
plugin.warning("Problem creating file '" + filename + "'!");
}
return null; return null;
} }
private static String getFilename(String resource) {
int slash = resource.lastIndexOf("/");
return (slash < 0 ? resource : resource.substring(slash + 1));
}
public static YamlConfiguration getConfig(MobArena plugin, String filename) { public static YamlConfiguration getConfig(MobArena plugin, String filename) {
InputStream in = MobArena.class.getResourceAsStream("/res/" + filename); InputStream in = MobArena.class.getResourceAsStream("/res/" + filename);
if (in == null) { if (in == null) {
plugin.error("Failed to load '" + filename + "', the server must be restarted!"); Messenger.severe("Failed to load '" + filename + "', the server must be restarted!");
return null; return null;
} }
@ -232,7 +97,7 @@ public class FileUtils
} }
catch (Exception e) { catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
plugin.warning("Couldn't load '" + filename + "' as stream!"); Messenger.warning("Couldn't load '" + filename + "' as stream!");
} }
return null; return null;

View File

@ -1,376 +0,0 @@
package com.garbagemule.MobArena.waves;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.garbagemule.MobArena.MAUtils;
import com.garbagemule.MobArena.MobArena;
import com.garbagemule.MobArena.framework.Arena;
public enum BossAbility
{
ARROWS("Arrow")
{
public void run(Arena arena, LivingEntity boss)
{
boss.shootArrow();
}
},
FIREBALLS("Fireball")
{
public void run(Arena arena, LivingEntity boss)
{
Location bLoc = boss.getLocation();
Location loc = bLoc.add(bLoc.getDirection().normalize().multiply(2).toLocation(boss.getWorld(), bLoc.getYaw(), bLoc.getPitch()));
Fireball fireball = boss.getWorld().spawn(loc, Fireball.class);
fireball.setFireTicks(100);
fireball.setIsIncendiary(false);
}
},
FIREAURA("Fire Aura")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getNearbyPlayers(arena, boss, 5))
p.setFireTicks(20);
}
},
LIGHTNINGAURA("Lightning Aura")
{
public void run(Arena arena, LivingEntity boss)
{
Location base = boss.getLocation();
Location ne = base.getBlock().getRelative( 2, 0, 2).getLocation();
Location nw = base.getBlock().getRelative(-2, 0, 2).getLocation();
Location se = base.getBlock().getRelative( 2, 0, -2).getLocation();
Location sw = base.getBlock().getRelative(-2, 0, -2).getLocation();
arena.getWorld().strikeLightning(ne);
arena.getWorld().strikeLightning(nw);
arena.getWorld().strikeLightning(se);
arena.getWorld().strikeLightning(sw);
}
},
LIVINGBOMB("Living Bomb")
{
public void run(final Arena arena, LivingEntity boss) {
final LivingEntity target = getTarget(boss);
if (target == null) return;
// Set the target on fire
target.setFireTicks(60);
// Create an explosion after 3 seconds
arena.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(arena.getPlugin(),
new Runnable() {
public void run() {
if (!arena.inArena((Player) target)) {
return;
}
// If the player put out the fire, don't explode.
if (target.getFireTicks() <= 0) {
return;
}
arena.getWorld().createExplosion(target.getLocation(), 2F);
for (Player p : getNearbyPlayers(arena, target, 3)) {
p.setFireTicks(40);
}
}
}, 59);
}
},
CHAINLIGHTNING("Chain Lightning")
{
public void run(Arena arena, LivingEntity boss)
{
final LivingEntity target = getTarget(boss);
if (target == null) return;
strikeLightning(arena, (Player) target, new LinkedList<Player>());
}
private void strikeLightning(final Arena arena, final Player p, final List<Player> done)
{
arena.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(arena.getPlugin(),
new Runnable()
{
public void run()
{
if (!arena.getPlayersInArena().contains(p))
return;
// Smite the target
arena.getWorld().strikeLightning(p.getLocation());
done.add(p);
// Grab all nearby players
List<Player> nearby = getNearbyPlayers(arena, p, 4);
// Remove all that are "done", and return if empty
nearby.removeAll(done);
if (nearby.isEmpty()) return;
// Otherwise, smite the next target!
strikeLightning(arena, nearby.get(0), done);
}
}, 8);
}
},
DISORIENTTARGET("Disorient Target")
{
public void run(Arena arena, LivingEntity boss)
{
LivingEntity target = getTarget(boss);
if (target == null) return;
Location loc = target.getLocation();
loc.setYaw(loc.getYaw() + 45 + MobArena.random.nextInt(270));
target.teleport(loc);
}
},
DISORIENTNEARBY("Disorient Nearby")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getNearbyPlayers(arena, boss, 5)) {
Location loc = p.getLocation();
loc.setYaw(loc.getYaw() + 45 + MobArena.random.nextInt(270));
p.teleport(loc);
}
}
},
DISORIENTDISTANT("Disorient Distant")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getDistantPlayers(arena, boss, 8)) {
Location loc = p.getLocation();
loc.setYaw(loc.getYaw() + 45 + MobArena.random.nextInt(270));
p.teleport(loc);
}
}
},
ROOTTARGET("Root Target")
{
public void run(final Arena arena, LivingEntity boss)
{
final LivingEntity target = getTarget(boss);
if (target == null) return;
final Location loc = target.getLocation();
final int freezeTaskId = arena.getPlugin().getServer().getScheduler().scheduleSyncRepeatingTask(arena.getPlugin(),
new Runnable()
{
public void run()
{
if (arena.getPlayersInArena().contains(target))
target.teleport(loc);
}
}, 3, 3);
arena.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(arena.getPlugin(),
new Runnable()
{
public void run()
{
arena.getPlugin().getServer().getScheduler().cancelTask(freezeTaskId);
}
}, 45);
}
},
WARPTOPLAYER("Warp")
{
public void run(Arena arena, LivingEntity boss)
{
List<Player> list = new ArrayList<Player>(arena.getPlayersInArena());
boss.teleport(list.get((new Random()).nextInt(list.size())));
}
},
SHUFFLEPOSITIONS("Shuffle Positions")
{
public void run(Arena arena, LivingEntity boss)
{
// Grab the players and add the boss
List<LivingEntity> entities = new ArrayList<LivingEntity>(arena.getPlayersInArena());
entities.add(boss);
// Grab the locations
List<Location> locations = new LinkedList<Location>();
for (LivingEntity e : entities)
locations.add(e.getLocation());
// Shuffle the entities, and then begin warping.
Collections.shuffle(entities);
while (!entities.isEmpty() && !locations.isEmpty())
entities.remove(0).teleport(locations.remove(0));
}
},
FLOOD("Flood")
{
public void run(Arena arena, LivingEntity boss)
{
List<Player> players = new ArrayList<Player>(arena.getPlayersInArena());
Block block = players.get(MobArena.random.nextInt(players.size())).getLocation().getBlock();
if (block.getTypeId() == 0)
{
block.setTypeId(8);
arena.addBlock(block);
}
}
},
THROWTARGET("Throw Target")
{
public void run(Arena arena, LivingEntity boss)
{
LivingEntity target = getTarget(boss);
if (target == null) return;
Location bLoc = boss.getLocation();
Location loc = target.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
target.setVelocity(v.normalize().setY(0.8));
}
},
THROWNEARBY("Throw Nearby Players")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getNearbyPlayers(arena, boss, 5))
{
Location bLoc = boss.getLocation();
Location loc = p.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
p.setVelocity(v.normalize().setY(0.8));
}
}
},
THROWDISTANT("Throw Distant Players")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getDistantPlayers(arena, boss, 8))
{
Location bLoc = boss.getLocation();
Location loc = p.getLocation();
Vector v = new Vector(loc.getX() - bLoc.getX(), 0, loc.getZ() - bLoc.getZ());
p.setVelocity(v.normalize().setY(0.8));
}
}
},
FETCHTARGET("Fetch Target")
{
public void run(Arena arena, LivingEntity boss)
{
LivingEntity target = getTarget(boss);
if (target != null) target.teleport(boss);
}
},
FETCHNEARBY("Fetch Nearby Players")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getNearbyPlayers(arena, boss, 5))
p.teleport(boss);
}
},
FETCHDISTANT("Fetch Distant Players")
{
public void run(Arena arena, LivingEntity boss)
{
for (Player p : getDistantPlayers(arena, boss, 8))
p.teleport(boss);
}
};
private String name;
private BossAbility(String name)
{
this.name = name;
}
/**
* The run-method that all boss abilities must define.
* The method is called in the ability cycle for the given boss.
* @param arena The Arena the boss is in
* @param boss The boss entity
*/
public abstract void run(Arena arena, LivingEntity boss);
/**
* Get the target player of the LivingEntity if possible.
* @param entity The entity whose target to get
* @return The target player, or null
*/
protected LivingEntity getTarget(LivingEntity entity)
{
if (entity instanceof Creature)
{
LivingEntity target = null;
try
{
target = ((Creature) entity).getTarget();
}
catch (Exception e) {}
if (target instanceof Player)
return target;
}
return null;
}
/**
* Get a list of nearby players
* @param arena The arena
* @param boss The boss
* @param x The 'radius' in which to grab players
* @return A list of nearby players
*/
protected List<Player> getNearbyPlayers(Arena arena, Entity boss, int x)
{
List<Player> result = new LinkedList<Player>();
for (Entity e : boss.getNearbyEntities(x, x, x))
if (arena.getPlayersInArena().contains(e))
result.add((Player) e);
return result;
}
/**
* Get a list of distant players
* @param arena The arena
* @param boss The boss
* @param x The 'radius' in which to exclude players
* @return A list of distant players
*/
protected List<Player> getDistantPlayers(Arena arena, Entity boss, int x)
{
List<Player> result = new LinkedList<Player>();
for (Player p : arena.getPlayersInArena())
if (MAUtils.distanceSquared(arena.getPlugin(), p, boss.getLocation()) > (double) (x*x))
result.add(p);
return result;
}
public static BossAbility fromString(String string) {
return WaveUtils.getEnumFromString(BossAbility.class, string.replaceAll("[-_\\.]", ""));
}
public String toString() {
return name;
}
}

View File

@ -4,16 +4,17 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.waves.ability.Ability;
import com.garbagemule.MobArena.waves.types.BossWave; import com.garbagemule.MobArena.waves.types.BossWave;
public class BossAbilityThread implements Runnable public class BossAbilityThread implements Runnable
{ {
private BossWave wave; private BossWave wave;
private List<BossAbility> abilities; private List<Ability> abilities;
private Arena arena; private Arena arena;
private int counter; private int counter;
public BossAbilityThread(BossWave wave, List<BossAbility> abilities, Arena arena) { public BossAbilityThread(BossWave wave, List<Ability> abilities, Arena arena) {
this.wave = wave; this.wave = wave;
this.abilities = abilities; this.abilities = abilities;
this.arena = arena; this.arena = arena;
@ -39,14 +40,15 @@ public class BossAbilityThread implements Runnable
} }
// Get the next ability in the list. // Get the next ability in the list.
BossAbility ability = abilities.get(counter++ % abilities.size()); Ability ability = abilities.get(counter++ % abilities.size());
// And make each boss in this boss wave use it! // And make each boss in this boss wave use it!
for (MABoss boss : bosses) { for (MABoss boss : bosses) {
ability.run(arena, boss.getEntity()); wave.announceAbility(ability, boss, arena);
ability.execute(arena, boss);
} }
// Schedule for another run! // Schedule for another run!
wave.scheduleTask(arena, this, wave.getAbilityInterval()); arena.scheduleTask(this, wave.getAbilityInterval());
} }
} }

View File

@ -8,6 +8,11 @@ public class MABoss
private int health, health25, maxHealth; private int health, health25, maxHealth;
private boolean dead, lowHealth; private boolean dead, lowHealth;
/**
* Create an MABoss from the given entity with the given max health.
* @param entity an entity
* @param maxHealth a max health value
*/
public MABoss(LivingEntity entity, int maxHealth) { public MABoss(LivingEntity entity, int maxHealth) {
this.entity = entity; this.entity = entity;
this.dead = false; this.dead = false;
@ -17,18 +22,57 @@ public class MABoss
this.health25 = maxHealth / 4; this.health25 = maxHealth / 4;
} }
/**
* Get the LivingEntity associated with this MABoss
* @return a LivingEntity
*/
public LivingEntity getEntity() { public LivingEntity getEntity() {
return entity; return entity;
} }
/**
* Get the current health of this MABoss
* @return the current health of the boss
*/
public int getHealth() { public int getHealth() {
return health; return health;
} }
/**
* Get the maximum health of this MABoss
* @return the maximum health of the boss
*/
public int getMaxHealth() { public int getMaxHealth() {
return maxHealth; return maxHealth;
} }
/**
* Set the health of this boss as a percentage between 1 and 100.
* @param percentage an integer percentage
*/
public void setHealth(int percentage) {
if (percentage < 1) {
percentage = 1;
}
else if (percentage > 100) {
percentage = 100;
}
health = maxHealth * percentage / 100;
}
/**
* Heal the boss for the given amount. Useful for "siphon life"-like abilities.
* @param amount the health amount
*/
public void heal(int amount) {
health = Math.min(maxHealth, health + amount);
}
/**
* Damage the boss for the given amount. Used internally by MobArena.
* @param amount the amount.
*/
public void damage(int amount) { public void damage(int amount) {
health -= amount; health -= amount;
@ -42,6 +86,11 @@ public class MABoss
} }
} }
/**
* Check if the boss is dead.
* A boss is dead if it has been damaged such that its health is below 0.
* @return true, if the boss is dead, false otherwise
*/
public boolean isDead() { public boolean isDead() {
return dead; return dead;
} }

View File

@ -3,6 +3,7 @@ package com.garbagemule.MobArena.waves;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.util.config.Config; import com.garbagemule.MobArena.util.config.Config;
import com.garbagemule.MobArena.util.config.ConfigSection; import com.garbagemule.MobArena.util.config.ConfigSection;
@ -55,7 +56,7 @@ public class WaveManager
finalWave = config.getInt("arenas." + arena.configName() + ".settings.final-wave", 0); finalWave = config.getInt("arenas." + arena.configName() + ".settings.final-wave", 0);
if (recurrentWaves.isEmpty()) { if (recurrentWaves.isEmpty()) {
arena.getPlugin().warning(WaveError.NO_RECURRENT_WAVES.format(arena.configName())); Messenger.warning(WaveError.NO_RECURRENT_WAVES.format(arena.configName()));
Wave def = WaveParser.createDefaultWave(); Wave def = WaveParser.createDefaultWave();
recurrentWaves.add(def); recurrentWaves.add(def);

View File

@ -5,11 +5,13 @@ import java.util.*;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.region.ArenaRegion; import com.garbagemule.MobArena.region.ArenaRegion;
import com.garbagemule.MobArena.util.ItemParser; import com.garbagemule.MobArena.util.ItemParser;
import com.garbagemule.MobArena.util.config.ConfigSection; import com.garbagemule.MobArena.util.config.ConfigSection;
import com.garbagemule.MobArena.waves.ability.Ability;
import com.garbagemule.MobArena.waves.ability.AbilityManager;
import com.garbagemule.MobArena.waves.enums.*; import com.garbagemule.MobArena.waves.enums.*;
import com.garbagemule.MobArena.waves.types.BossWave; import com.garbagemule.MobArena.waves.types.BossWave;
import com.garbagemule.MobArena.waves.types.DefaultWave; import com.garbagemule.MobArena.waves.types.DefaultWave;
@ -21,22 +23,19 @@ import com.garbagemule.MobArena.waves.types.UpgradeWave;
public class WaveParser public class WaveParser
{ {
public static TreeSet<Wave> parseWaves(Arena arena, ConfigSection config, WaveBranch branch) { public static TreeSet<Wave> parseWaves(Arena arena, ConfigSection config, WaveBranch branch) {
// Grab the plugin for error reporting.
MobArena plugin = arena.getPlugin();
// Create a TreeSet with the Comparator for the specific branch. // Create a TreeSet with the Comparator for the specific branch.
TreeSet<Wave> result = new TreeSet<Wave>(WaveUtils.getComparator(branch)); TreeSet<Wave> result = new TreeSet<Wave>(WaveUtils.getComparator(branch));
// If the config is null, return the empty set. // If the config is null, return the empty set.
if (config == null) { if (config == null) {
plugin.warning(WaveError.BRANCH_MISSING.format(branch.toString().toLowerCase(), arena.configName())); Messenger.warning(WaveError.BRANCH_MISSING.format(branch.toString().toLowerCase(), arena.configName()));
return result; return result;
} }
// If no waves were found, return the empty set. // If no waves were found, return the empty set.
Set<String> waves = config.getKeys(); Set<String> waves = config.getKeys();
if (waves == null/* || waves.isEmpty()*/) { if (waves == null/* || waves.isEmpty()*/) {
plugin.warning(WaveError.BRANCH_MISSING.format(branch.toString().toLowerCase(), arena.configName())); Messenger.warning(WaveError.BRANCH_MISSING.format(branch.toString().toLowerCase(), arena.configName()));
return result; return result;
} }
@ -57,15 +56,12 @@ public class WaveParser
} }
public static Wave parseWave(Arena arena, String name, ConfigSection config, WaveBranch branch) { public static Wave parseWave(Arena arena, String name, ConfigSection config, WaveBranch branch) {
// Grab the plugin for error reporting.
MobArena plugin = arena.getPlugin();
// Grab the WaveType and verify that it isn't null. // Grab the WaveType and verify that it isn't null.
String t = config.getString("type", null); String t = config.getString("type", null);
WaveType type = WaveType.fromString(t); WaveType type = WaveType.fromString(t);
if (type == null) { if (type == null) {
plugin.warning(WaveError.INVALID_TYPE.format(t, name, arena.configName())); Messenger.warning(WaveError.INVALID_TYPE.format(t, name, arena.configName()));
return null; return null;
} }
@ -96,7 +92,7 @@ public class WaveParser
// Check that the result isn't null // Check that the result isn't null
if (result == null) { if (result == null) {
plugin.warning(WaveError.INVALID_WAVE.format(name, arena.configName())); Messenger.warning(WaveError.INVALID_WAVE.format(name, arena.configName()));
return null; return null;
} }
@ -121,10 +117,10 @@ public class WaveParser
// Recurrent must have priority + frequency, single must have firstWave // Recurrent must have priority + frequency, single must have firstWave
if (branch == WaveBranch.RECURRENT && (priority == -1 || frequency <= 0)) { if (branch == WaveBranch.RECURRENT && (priority == -1 || frequency <= 0)) {
plugin.warning(WaveError.RECURRENT_NODES.format(name, arena.configName())); Messenger.warning(WaveError.RECURRENT_NODES.format(name, arena.configName()));
return null; return null;
} else if (branch == WaveBranch.SINGLE && firstWave <= 0) { } else if (branch == WaveBranch.SINGLE && firstWave <= 0) {
plugin.warning(WaveError.SINGLE_NODES.format(name, arena.configName())); Messenger.warning(WaveError.SINGLE_NODES.format(name, arena.configName()));
return null; return null;
} }
@ -149,7 +145,7 @@ public class WaveParser
// Grab the monster map. // Grab the monster map.
SortedMap<Integer,MACreature> monsters = getMonsterMap(config); SortedMap<Integer,MACreature> monsters = getMonsterMap(config);
if (monsters == null || monsters.isEmpty()) { if (monsters == null || monsters.isEmpty()) {
arena.getPlugin().warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -167,7 +163,7 @@ public class WaveParser
private static Wave parseSpecialWave(Arena arena, String name, ConfigSection config) { private static Wave parseSpecialWave(Arena arena, String name, ConfigSection config) {
SortedMap<Integer,MACreature> monsters = getMonsterMap(config); SortedMap<Integer,MACreature> monsters = getMonsterMap(config);
if (monsters == null || monsters.isEmpty()) { if (monsters == null || monsters.isEmpty()) {
arena.getPlugin().warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -178,7 +174,7 @@ public class WaveParser
private static Wave parseSwarmWave(Arena arena, String name, ConfigSection config) { private static Wave parseSwarmWave(Arena arena, String name, ConfigSection config) {
MACreature monster = getSingleMonster(config); MACreature monster = getSingleMonster(config);
if (monster == null) { if (monster == null) {
arena.getPlugin().warning(WaveError.SINGLE_MONSTER_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.SINGLE_MONSTER_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -195,7 +191,7 @@ public class WaveParser
private static Wave parseSupplyWave(Arena arena, String name, ConfigSection config) { private static Wave parseSupplyWave(Arena arena, String name, ConfigSection config) {
SortedMap<Integer,MACreature> monsters = getMonsterMap(config); SortedMap<Integer,MACreature> monsters = getMonsterMap(config);
if (monsters == null || monsters.isEmpty()) { if (monsters == null || monsters.isEmpty()) {
arena.getPlugin().warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.MONSTER_MAP_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -212,7 +208,7 @@ public class WaveParser
private static Wave parseUpgradeWave(Arena arena, String name, ConfigSection config) { private static Wave parseUpgradeWave(Arena arena, String name, ConfigSection config) {
Map<String,List<ItemStack>> classMap = getUpgradeMap(config); Map<String,List<ItemStack>> classMap = getUpgradeMap(config);
if (classMap == null || classMap.isEmpty()) { if (classMap == null || classMap.isEmpty()) {
arena.getPlugin().warning(WaveError.UPGRADE_MAP_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.UPGRADE_MAP_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -228,7 +224,7 @@ public class WaveParser
private static Wave parseBossWave(Arena arena, String name, ConfigSection config) { private static Wave parseBossWave(Arena arena, String name, ConfigSection config) {
MACreature monster = getSingleMonster(config); MACreature monster = getSingleMonster(config);
if (monster == null) { if (monster == null) {
arena.getPlugin().warning(WaveError.SINGLE_MONSTER_MISSING.format(name, arena.configName())); Messenger.warning(WaveError.SINGLE_MONSTER_MISSING.format(name, arena.configName()));
return null; return null;
} }
@ -244,9 +240,9 @@ public class WaveParser
if (ablts != null) { if (ablts != null) {
String[] parts = ablts.split(","); String[] parts = ablts.split(",");
for (String ability : parts) { for (String ability : parts) {
BossAbility a = BossAbility.fromString(ability.trim()); Ability a = AbilityManager.fromString(ability.trim());
if (a == null) { if (a == null) {
arena.getPlugin().warning(WaveError.BOSS_ABILITY.format(ability.trim(), name, arena.configName())); Messenger.warning(WaveError.BOSS_ABILITY.format(ability.trim(), name, arena.configName()));
continue; continue;
} }
@ -310,7 +306,6 @@ public class WaveParser
} }
private static List<Location> getSpawnpoints(Arena arena, String name, ConfigSection config) { private static List<Location> getSpawnpoints(Arena arena, String name, ConfigSection config) {
MobArena plugin = arena.getPlugin();
List<Location> result = new ArrayList<Location>(); List<Location> result = new ArrayList<Location>();
String spawnString = config.getString("spawnpoints"); String spawnString = config.getString("spawnpoints");
@ -326,7 +321,7 @@ public class WaveParser
Location spawnpoint = region.getSpawnpoint(spawn.trim()); Location spawnpoint = region.getSpawnpoint(spawn.trim());
if (spawnpoint == null) { if (spawnpoint == null) {
plugin.warning("Spawnpoint '" + spawn + "' in wave '" + name + "' for arena '" + arena.configName() + "' could not be parsed!"); Messenger.warning("Spawnpoint '" + spawn + "' in wave '" + name + "' for arena '" + arena.configName() + "' could not be parsed!");
continue; continue;
} }

View File

@ -12,6 +12,7 @@ import org.bukkit.entity.Player;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.waves.enums.*; import com.garbagemule.MobArena.waves.enums.*;
import com.garbagemule.MobArena.MAUtils; import com.garbagemule.MobArena.MAUtils;
import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.MobArena; import com.garbagemule.MobArena.MobArena;
public class WaveUtils public class WaveUtils
@ -41,7 +42,7 @@ public class WaveUtils
// If no spawnpoints in range, just return all of them. // If no spawnpoints in range, just return all of them.
if (result.isEmpty()) { if (result.isEmpty()) {
plugin.warning("Spawnpoints of arena '" + arena.configName() + "' may be too far apart!"); Messenger.warning("Spawnpoints of arena '" + arena.configName() + "' may be too far apart!");
return spawnpoints; return spawnpoints;
} }
return result; return result;
@ -49,7 +50,6 @@ public class WaveUtils
public static Player getClosestPlayer(Arena arena, Entity e) public static Player getClosestPlayer(Arena arena, Entity e)
{ {
MobArena plugin = arena.getPlugin();
// Set up the comparison variable and the result. // Set up the comparison variable and the result.
double dist = 0; double dist = 0;
double current = Double.POSITIVE_INFINITY; double current = Double.POSITIVE_INFINITY;
@ -61,7 +61,7 @@ public class WaveUtils
{ {
if (!arena.getWorld().equals(p.getWorld())) if (!arena.getWorld().equals(p.getWorld()))
{ {
plugin.info("Player '" + p.getName() + "' is not in the right world. Kicking..."); Messenger.info("Player '" + p.getName() + "' is not in the right world. Kicking...");
p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)"); p.kickPlayer("[MobArena] Cheater! (Warped out of the arena world.)");
continue; continue;
} }

View File

@ -7,14 +7,16 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import com.garbagemule.MobArena.Messenger;
import com.garbagemule.MobArena.Msg;
import com.garbagemule.MobArena.framework.Arena; import com.garbagemule.MobArena.framework.Arena;
import com.garbagemule.MobArena.waves.AbstractWave; import com.garbagemule.MobArena.waves.AbstractWave;
import com.garbagemule.MobArena.waves.BossAbility;
import com.garbagemule.MobArena.waves.BossAbilityThread; import com.garbagemule.MobArena.waves.BossAbilityThread;
import com.garbagemule.MobArena.waves.MABoss; import com.garbagemule.MobArena.waves.MABoss;
import com.garbagemule.MobArena.waves.MACreature; import com.garbagemule.MobArena.waves.MACreature;
import com.garbagemule.MobArena.waves.ability.Ability;
import com.garbagemule.MobArena.waves.ability.AbilityInfo;
import com.garbagemule.MobArena.waves.enums.*; import com.garbagemule.MobArena.waves.enums.*;
import com.garbagemule.MobArena.MobArena;
public class BossWave extends AbstractWave public class BossWave extends AbstractWave
{ {
@ -22,7 +24,7 @@ public class BossWave extends AbstractWave
private Set<MABoss> bosses; private Set<MABoss> bosses;
private BossHealth health; private BossHealth health;
private List<BossAbility> abilities; private List<Ability> abilities;
private boolean activated; private boolean activated;
private int abilityInterval; private int abilityInterval;
@ -30,7 +32,7 @@ public class BossWave extends AbstractWave
public BossWave(MACreature monster) { public BossWave(MACreature monster) {
this.monster = monster; this.monster = monster;
this.bosses = new HashSet<MABoss>(); this.bosses = new HashSet<MABoss>();
this.abilities = new ArrayList<BossAbility>(); this.abilities = new ArrayList<Ability>();
this.activated = false; this.activated = false;
this.setType(WaveType.BOSS); this.setType(WaveType.BOSS);
} }
@ -64,7 +66,7 @@ public class BossWave extends AbstractWave
return result; return result;
} }
public void addBossAbility(BossAbility ability) { public void addBossAbility(Ability ability) {
abilities.add(ability); abilities.add(ability);
} }
@ -82,16 +84,12 @@ public class BossWave extends AbstractWave
} }
BossAbilityThread bat = new BossAbilityThread(this, abilities, arena); BossAbilityThread bat = new BossAbilityThread(this, abilities, arena);
scheduleTask(arena, bat, 100); arena.scheduleTask(bat, 100);
activated = true; activated = true;
} }
public void scheduleTask(Arena arena, Runnable r, int delay) { public void announceAbility(Ability ability, MABoss boss, Arena arena) {
MobArena plugin = arena.getPlugin(); AbilityInfo info = ability.getClass().getAnnotation(AbilityInfo.class);
Messenger.tellAll(arena, Msg.WAVE_BOSS_ABILITY, info.name());
plugin.getServer().getScheduler().scheduleSyncDelayedTask(
plugin,
r,
delay);
} }
} }