formatting

This commit is contained in:
Charlie 2014-07-28 11:53:28 -04:00
parent 4deb7589ae
commit 52d335ddf6
5 changed files with 908 additions and 912 deletions

View File

@ -26,502 +26,500 @@ import org.bukkit.util.Vector;
public class DiscoParty { public class DiscoParty {
// Static properties // Static properties
static int defaultDuration = 300; // ticks for entire party static int defaultDuration = 300; // ticks for entire party
static int defaultPeriod = 10; // ticks per state change static int defaultPeriod = 10; // ticks per state change
static int defaultRadius = 5; static int defaultRadius = 5;
static int defaultSheep = 10; static int defaultSheep = 10;
static float defaultSheepJump = 0.35f; static float defaultSheepJump = 0.35f;
static int maxDuration = 2400; // 120 seconds static int maxDuration = 2400; // 120 seconds
static int maxSheep = 100; static int maxSheep = 100;
static int maxRadius = 100; static int maxRadius = 100;
static int minPeriod = 5; // 0.25 seconds static int minPeriod = 5; // 0.25 seconds
static int maxPeriod = 40; // 2.0 seconds static int maxPeriod = 40; // 2.0 seconds
private static HashMap<String, Integer> defaultGuestNumbers = new HashMap<String, Integer>(); private static HashMap<String, Integer> defaultGuestNumbers = new HashMap<String, Integer>();
private static HashMap<String, Integer> maxGuestNumbers = new HashMap<String, Integer>(); private static HashMap<String, Integer> maxGuestNumbers = new HashMap<String, Integer>();
private static final DyeColor[] discoColours = { private static final DyeColor[] discoColours = {
DyeColor.RED, DyeColor.RED,
DyeColor.ORANGE, DyeColor.ORANGE,
DyeColor.YELLOW, DyeColor.YELLOW,
DyeColor.GREEN, DyeColor.GREEN,
DyeColor.BLUE, DyeColor.BLUE,
DyeColor.LIGHT_BLUE, DyeColor.LIGHT_BLUE,
DyeColor.PINK, DyeColor.PINK,
DyeColor.MAGENTA, DyeColor.MAGENTA,
DyeColor.LIME, DyeColor.LIME,
DyeColor.CYAN, DyeColor.CYAN,
DyeColor.PURPLE, DyeColor.PURPLE,
DyeColor.BLACK, DyeColor.BLACK,
DyeColor.WHITE DyeColor.WHITE
}; };
private static final float[] pentatonicNotes = { private static final float[] pentatonicNotes = {
1.0f, 1.0f,
1.125f, 1.125f,
1.25f, 1.25f,
1.5f, 1.5f,
1.667f, 1.667f,
2.0f 2.0f
}; };
// Instance properties // Instance properties
private Random r = new Random(); private Random r = new Random();
private PartyEvents partyEvents; private PartyEvents partyEvents;
private DiscoSheep parent; private DiscoSheep parent;
private Player player; private Player player;
private ArrayList<Sheep> sheepList = new ArrayList<Sheep>(); private ArrayList<Sheep> sheepList = new ArrayList<Sheep>();
private ArrayList<Entity> guestList = new ArrayList<Entity>(); private ArrayList<Entity> guestList = new ArrayList<Entity>();
private ArrayList<BlockState> floorBlockCache = new ArrayList<BlockState>(); private ArrayList<BlockState> floorBlockCache = new ArrayList<BlockState>();
private ArrayList<Block> floorBlocks = new ArrayList<Block>(); private ArrayList<Block> floorBlocks = new ArrayList<Block>();
private HashMap<String, Integer> guestNumbers = new HashMap<String, Integer>(); private HashMap<String, Integer> guestNumbers = new HashMap<String, Integer>();
private boolean doFireworks = false; private boolean doFireworks = false;
private boolean doJump = true; private boolean doJump = true;
private boolean doLightning = false; private boolean doLightning = false;
private int duration, period, radius, sheep; private int duration, period, radius, sheep;
private int state = 0; // basically our own tick system private int state = 0; // basically our own tick system
private DiscoUpdater updater; private DiscoUpdater updater;
public DiscoParty(DiscoSheep parent, Player player) { public DiscoParty(DiscoSheep parent, Player player) {
this(parent); this(parent);
this.player = player; this.player = player;
} }
public DiscoParty(DiscoSheep parent) { public DiscoParty(DiscoSheep parent) {
this.parent = parent; this.parent = parent;
this.duration = DiscoParty.defaultDuration; this.duration = DiscoParty.defaultDuration;
this.period = DiscoParty.defaultPeriod; this.period = DiscoParty.defaultPeriod;
this.radius = DiscoParty.defaultRadius; this.radius = DiscoParty.defaultRadius;
this.sheep = DiscoParty.defaultSheep; this.sheep = DiscoParty.defaultSheep;
this.guestNumbers = new HashMap<String, Integer>(DiscoParty.defaultGuestNumbers); this.guestNumbers = new HashMap<String, Integer>(DiscoParty.defaultGuestNumbers);
r = new Random(); r = new Random();
} }
// copy but with new player // copy but with new player
// used for /ds other and /ds all // used for /ds other and /ds all
public DiscoParty clone(Player player) { public DiscoParty clone(Player player) {
DiscoParty newParty; DiscoParty newParty;
newParty = new DiscoParty(this.parent, player); newParty = new DiscoParty(this.parent, player);
newParty.doFireworks = this.doFireworks; newParty.doFireworks = this.doFireworks;
newParty.duration = this.duration; newParty.duration = this.duration;
newParty.period = this.period; newParty.period = this.period;
newParty.radius = this.radius; newParty.radius = this.radius;
newParty.sheep = this.sheep; newParty.sheep = this.sheep;
newParty.doLightning = this.doLightning; newParty.doLightning = this.doLightning;
newParty.guestNumbers = this.getGuestNumbers(); newParty.guestNumbers = this.getGuestNumbers();
return newParty; return newParty;
} }
ArrayList<Sheep> getSheepList() { ArrayList<Sheep> getSheepList() {
return sheepList; return sheepList;
} }
ArrayList<Entity> getGuestList() { ArrayList<Entity> getGuestList() {
return guestList; return guestList;
} }
ArrayList<BlockState> getFloorCache() { ArrayList<BlockState> getFloorCache() {
return this.floorBlockCache; return this.floorBlockCache;
} }
ArrayList<Block> getFloorBlocks() { ArrayList<Block> getFloorBlocks() {
return this.floorBlocks; return this.floorBlocks;
} }
public static HashMap<String, Integer> getDefaultGuestNumbers() { public static HashMap<String, Integer> getDefaultGuestNumbers() {
return defaultGuestNumbers; return defaultGuestNumbers;
} }
public HashMap<String, Integer> getGuestNumbers() { public HashMap<String, Integer> getGuestNumbers() {
return guestNumbers; return guestNumbers;
} }
public static HashMap<String, Integer> getMaxGuestNumbers() { public static HashMap<String, Integer> getMaxGuestNumbers() {
return maxGuestNumbers; return maxGuestNumbers;
} }
public int getSheep() { public int getSheep() {
return this.sheep; return this.sheep;
} }
public DiscoParty setPlayer(Player player) { public DiscoParty setPlayer(Player player) {
if (player != null) { if (player != null) {
this.player = player; this.player = player;
return this; return this;
} else { } else {
throw new NullPointerException(); throw new NullPointerException();
} }
} }
public DiscoParty setDuration(int duration) throws IllegalArgumentException { public DiscoParty setDuration(int duration) throws IllegalArgumentException {
if (duration <= DiscoParty.maxDuration && duration > 0) { if (duration <= DiscoParty.maxDuration && duration > 0) {
this.duration = duration; this.duration = duration;
return this; return this;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
public DiscoParty setPeriod(int period) throws IllegalArgumentException { public DiscoParty setPeriod(int period) throws IllegalArgumentException {
if (period >= DiscoParty.minPeriod && period <= DiscoParty.maxPeriod) { if (period >= DiscoParty.minPeriod && period <= DiscoParty.maxPeriod) {
this.period = period; this.period = period;
return this; return this;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
public DiscoParty setRadius(int radius) throws IllegalArgumentException { public DiscoParty setRadius(int radius) throws IllegalArgumentException {
if (radius <= DiscoParty.maxRadius && radius > 0) { if (radius <= DiscoParty.maxRadius && radius > 0) {
this.radius = radius; this.radius = radius;
return this; return this;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
public DiscoParty setDenseRadius(int sheepNo) throws IllegalArgumentException { public DiscoParty setDenseRadius(int sheepNo) throws IllegalArgumentException {
Integer rand = (int) Math.floor(Math.sqrt(sheep / Math.PI)); Integer rand = (int) Math.floor(Math.sqrt(sheep / Math.PI));
if (rand > DiscoParty.maxRadius) { if (rand > DiscoParty.maxRadius) {
rand = DiscoParty.maxRadius; rand = DiscoParty.maxRadius;
} }
if (rand < 1) { if (rand < 1) {
rand = 1; rand = 1;
} }
this.setRadius(rand); this.setRadius(rand);
return this; return this;
} }
public DiscoParty setSheep(int sheep) throws IllegalArgumentException { public DiscoParty setSheep(int sheep) throws IllegalArgumentException {
if (sheep <= DiscoParty.maxSheep && sheep > 0) { if (sheep <= DiscoParty.maxSheep && sheep > 0) {
this.sheep = sheep; this.sheep = sheep;
return this; return this;
} else { } else {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
} }
public DiscoParty setDoFireworks(boolean doFireworks) { public DiscoParty setDoFireworks(boolean doFireworks) {
this.doFireworks = doFireworks; this.doFireworks = doFireworks;
return this; return this;
} }
public DiscoParty setDoLightning(boolean doLightning) { public DiscoParty setDoLightning(boolean doLightning) {
this.doLightning = doLightning; this.doLightning = doLightning;
return this; return this;
} }
public DiscoParty setGuestNumber(String key, int n) throws IllegalArgumentException { public DiscoParty setGuestNumber(String key, int n) throws IllegalArgumentException {
if (getMaxGuestNumbers().containsKey(key.toUpperCase())) { if (getMaxGuestNumbers().containsKey(key.toUpperCase())) {
if (n <= getMaxGuestNumbers().get(key.toUpperCase()) && n >= 0) { // so that /ds defaults can take 0 as arg if (n <= getMaxGuestNumbers().get(key.toUpperCase()) && n >= 0) { // so that /ds defaults can take 0 as arg
getGuestNumbers().put(key, n); getGuestNumbers().put(key, n);
return this; return this;
} }
} }
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
// use current settings as new defaults // use current settings as new defaults
public DiscoParty setDefaultsFromCurrent() { public DiscoParty setDefaultsFromCurrent() {
DiscoParty.defaultDuration = this.duration; DiscoParty.defaultDuration = this.duration;
DiscoParty.defaultPeriod = this.period; DiscoParty.defaultPeriod = this.period;
DiscoParty.defaultRadius = this.radius; DiscoParty.defaultRadius = this.radius;
DiscoParty.defaultSheep = this.sheep; DiscoParty.defaultSheep = this.sheep;
DiscoParty.defaultGuestNumbers = new HashMap<String, Integer>(this.getGuestNumbers()); DiscoParty.defaultGuestNumbers = new HashMap<String, Integer>(this.getGuestNumbers());
return this; return this;
} }
Location getRandomSpawnLocation(double x, double z, World world, int spawnRadius) { Location getRandomSpawnLocation(double x, double z, World world, int spawnRadius) {
Location loc; Location loc;
double y; double y;
/* random point on circle with polar coordinates /* random point on circle with polar coordinates
* random number must be square rooted to obtain uniform distribution * random number must be square rooted to obtain uniform distribution
* otherwise the sheep are biased toward the centre */ * otherwise the sheep are biased toward the centre */
double rand = Math.sqrt(r.nextDouble()) * spawnRadius; double rand = Math.sqrt(r.nextDouble()) * spawnRadius;
double azimuth = r.nextDouble() * 2 * Math.PI; // radians double azimuth = r.nextDouble() * 2 * Math.PI; // radians
x += rand * Math.cos(azimuth); x += rand * Math.cos(azimuth);
z += rand * Math.sin(azimuth); z += rand * Math.sin(azimuth);
y = this.player.getLocation().getY(); y = this.player.getLocation().getY();
loc = new Location(world, x, y, z); loc = new Location(world, x, y, z);
loc.setPitch(r.nextFloat() * 360 - 180); loc.setPitch(r.nextFloat() * 360 - 180);
loc.setYaw(0); loc.setYaw(0);
return loc; return loc;
} }
// Spawn some number of guests next to given player // Spawn some number of guests next to given player
void spawnAll(int sheep, int spawnRadius) { void spawnAll(int sheep, int spawnRadius) {
Location loc; Location loc;
World world = player.getWorld(); World world = player.getWorld();
double x = player.getLocation().getX();
double z = player.getLocation().getZ();
for (int i = 0; i < sheep; i++) {
loc = getRandomSpawnLocation(x, z, world, spawnRadius);
spawnSheep(world, loc);
}
double x = player.getLocation().getX(); // loop through hashmap of other guests and spawn accordingly
double z = player.getLocation().getZ(); for (Map.Entry entry : guestNumbers.entrySet()) {
for (int i = 0; i < sheep; i++) { EntityType ent = EntityType.valueOf((String) entry.getKey());
loc = getRandomSpawnLocation(x, z, world, spawnRadius); int num = (Integer) entry.getValue();
spawnSheep(world, loc);
}
// loop through hashmap of other guests and spawn accordingly for (int i = 0; i < num; i++) {
for (Map.Entry entry : guestNumbers.entrySet()) { loc = getRandomSpawnLocation(x, z, world, spawnRadius);
EntityType ent = EntityType.valueOf((String) entry.getKey()); spawnGuest(world, loc, ent);
int num = (Integer) entry.getValue(); }
}
for (int i = 0; i < num; i++) { loc = player.getLocation();
loc = getRandomSpawnLocation(x, z, world, spawnRadius); //this.spawnFloor(world, new Location(world, loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ()));
spawnGuest(world, loc, ent); }
}
}
loc = player.getLocation(); void spawnSheep(World world, Location loc) {
//this.spawnFloor(world, new Location(world, loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())); Sheep newSheep = (Sheep) world.spawnEntity(loc, EntityType.SHEEP);
} newSheep.setColor(discoColours[(r.nextInt(discoColours.length))]);
newSheep.setBreed(false); // this prevents breeding - no event listener required
newSheep.teleport(loc); // teleport is needed to set orientation
getSheepList().add(newSheep);
if (doLightning) {
world.strikeLightningEffect(loc);
}
}
void spawnSheep(World world, Location loc) { void spawnGuest(World world, Location loc, EntityType type) {
Sheep newSheep = (Sheep) world.spawnEntity(loc, EntityType.SHEEP); Entity newGuest = loc.getWorld().spawnEntity(loc, type);
newSheep.setColor(discoColours[(r.nextInt(discoColours.length))]); getGuestList().add(newGuest);
newSheep.setBreed(false); // this prevents breeding - no event listener required if (doLightning) {
newSheep.teleport(loc); // teleport is needed to set orientation world.strikeLightningEffect(loc);
getSheepList().add(newSheep); }
if (doLightning) { }
world.strikeLightningEffect(loc);
}
}
void spawnGuest(World world, Location loc, EntityType type) { void spawnFloor(World world, Location loc) {
Entity newGuest = loc.getWorld().spawnEntity(loc, type); // First we'll save the floor state
getGuestList().add(newGuest); for (int x = loc.getBlockX() - this.radius; x < loc.getX() + this.radius; ++x) {
if (doLightning) { for (int z = loc.getBlockZ() - this.radius; z < loc.getZ() + this.radius; ++z) {
world.strikeLightningEffect(loc); Block block = world.getBlockAt(x, loc.getBlockY(), z);
} if (block.getType() != Material.WOOL) {
} this.getFloorCache().add(block.getState());
block.setType(Material.WOOL);
this.getFloorBlocks().add(block);
}
}
}
}
void spawnFloor(World world, Location loc) { // Mark all guests for removal, then clear the array
// First we'll save the floor state void removeAll() {
for (int x = loc.getBlockX() - this.radius; x < loc.getX() + this.radius; ++x) { for (Sheep sheeple : getSheepList()) {
for (int z = loc.getBlockZ() - this.radius; z < loc.getZ() + this.radius; ++z) { sheeple.remove();
Block block = world.getBlockAt(x, loc.getBlockY(), z); }
if (block.getType() != Material.WOOL) { for (Entity guest : getGuestList()) {
this.getFloorCache().add(block.getState()); guest.remove();
block.setType(Material.WOOL); }
this.getFloorBlocks().add(block); for (BlockState block : this.floorBlockCache) {
} block.update(true);
} }
} getSheepList().clear();
} getGuestList().clear();
floorBlockCache.clear();
}
// Mark all guests for removal, then clear the array // Set a random colour for all sheep in array
void removeAll() { void randomizeSheepColour(Sheep sheep) {
for (Sheep sheeple : getSheepList()) { sheep.setColor(discoColours[(r.nextInt(discoColours.length))]);
sheeple.remove(); }
}
for (Entity guest : getGuestList()) {
guest.remove();
}
for (BlockState block : this.floorBlockCache) {
block.update(true);
}
getSheepList().clear();
getGuestList().clear();
floorBlockCache.clear();
}
// Set a random colour for all sheep in array void randomizeFloor(Block block) {
void randomizeSheepColour(Sheep sheep) { block.setType(Material.WOOL);
sheep.setColor(discoColours[(r.nextInt(discoColours.length))]); block.setData(discoColours[(r.nextInt(discoColours.length))].getData());
} }
void randomizeFloor(Block block) { void jump(Entity entity) {
block.setType(Material.WOOL); Vector orgVel = entity.getVelocity();
block.setData(discoColours[(r.nextInt(discoColours.length))].getData()); Vector newVel = (new Vector()).copy(orgVel);
} newVel.add(new Vector(0, defaultSheepJump, 0));
entity.setVelocity(newVel);
}
void jump(Entity entity) { // WHY ISN'T THERE A Color.getValue() ?!?!?!?!
Vector orgVel = entity.getVelocity(); private Color getColor(int i) {
Vector newVel = (new Vector()).copy(orgVel); Color c = null;
newVel.add(new Vector(0, defaultSheepJump, 0)); if (i == 1) {
entity.setVelocity(newVel); c = Color.AQUA;
} }
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
// WHY ISN'T THERE A Color.getValue() ?!?!?!?! return c;
private Color getColor(int i) { }
Color c = null;
if (i == 1) {
c = Color.AQUA;
}
if (i == 2) {
c = Color.BLACK;
}
if (i == 3) {
c = Color.BLUE;
}
if (i == 4) {
c = Color.FUCHSIA;
}
if (i == 5) {
c = Color.GRAY;
}
if (i == 6) {
c = Color.GREEN;
}
if (i == 7) {
c = Color.LIME;
}
if (i == 8) {
c = Color.MAROON;
}
if (i == 9) {
c = Color.NAVY;
}
if (i == 10) {
c = Color.OLIVE;
}
if (i == 11) {
c = Color.ORANGE;
}
if (i == 12) {
c = Color.PURPLE;
}
if (i == 13) {
c = Color.RED;
}
if (i == 14) {
c = Color.SILVER;
}
if (i == 15) {
c = Color.TEAL;
}
if (i == 16) {
c = Color.WHITE;
}
if (i == 17) {
c = Color.YELLOW;
}
return c; void updateAll() {
} for (Sheep sheeple : getSheepList()) {
randomizeSheepColour(sheeple);
void updateAll() { if (doFireworks && state % 8 == 0) {
for (Sheep sheeple : getSheepList()) { if (r.nextDouble() < 0.50) {
randomizeSheepColour(sheeple); spawnRandomFireworkAtSheep(sheeple);
}
}
if (doFireworks && state % 8 == 0) { if (doJump) {
if (r.nextDouble() < 0.50) { if (state % 2 == 0 && r.nextDouble() < 0.5) {
spawnRandomFireworkAtSheep(sheeple); jump(sheeple);
} }
} }
}
if (doJump) { for (Entity guest : getGuestList()) {
if (state % 2 == 0 && r.nextDouble() < 0.5) { if (doJump) {
jump(sheeple); if (state % 2 == 0 && r.nextDouble() < 0.5) {
} jump(guest);
} }
} }
}
for (Entity guest : getGuestList()) { /* for (Block block : this.floorBlocks) {
if (doJump) { this.randomizeFloor(block);
if (state % 2 == 0 && r.nextDouble() < 0.5) { }*/
jump(guest); }
}
}
}
/* for (Block block : this.floorBlocks) { private float getPentatonicNote() {
this.randomizeFloor(block); return DiscoParty.pentatonicNotes[r.nextInt(pentatonicNotes.length)];
}*/ }
} void playSounds() {
player.playSound(player.getLocation(), Sound.NOTE_BASS_DRUM, 0.75f, 1.0f);
if (this.state % 2 == 0) {
player.playSound(player.getLocation(), Sound.NOTE_SNARE_DRUM, 0.8f, 1.0f);
}
private float getPentatonicNote() { if ((this.state + 1) % 8 == 0) {
return DiscoParty.pentatonicNotes[r.nextInt(pentatonicNotes.length)]; player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1.0f, 1.0f);
} }
}
void playSounds() { void randomizeFirework(Firework firework) {
player.playSound(player.getLocation(), Sound.NOTE_BASS_DRUM, 0.75f, 1.0f); Builder effect = FireworkEffect.builder();
if (this.state % 2 == 0) { FireworkMeta meta = firework.getFireworkMeta();
player.playSound(player.getLocation(), Sound.NOTE_SNARE_DRUM, 0.8f, 1.0f);
}
if ((this.state + 1) % 8 == 0) { // construct [1, 3] random colours
player.playSound(player.getLocation(), Sound.NOTE_STICKS, 1.0f, 1.0f); int numColours = r.nextInt(3) + 1;
} Color[] colourArray = new Color[numColours];
} for (int i = 0; i < numColours; i++) {
colourArray[i] = getColor(r.nextInt(17) + 1);
}
void randomizeFirework(Firework firework) { // randomize effects
Builder effect = FireworkEffect.builder(); effect.withColor(colourArray);
FireworkMeta meta = firework.getFireworkMeta(); effect.flicker(r.nextDouble() < 0.5);
effect.trail(r.nextDouble() < 0.5);
effect.with(FireworkEffect.Type.values()[r.nextInt(FireworkEffect.Type.values().length)]);
// construct [1, 3] random colours // set random effect and randomize power
int numColours = r.nextInt(3) + 1; meta.addEffect(effect.build());
Color[] colourArray = new Color[numColours]; meta.setPower(r.nextInt(2) + 1);
for (int i = 0; i < numColours; i++) {
colourArray[i] = getColor(r.nextInt(17) + 1);
}
// randomize effects // apply it to the given firework
effect.withColor(colourArray); firework.setFireworkMeta(meta);
effect.flicker(r.nextDouble() < 0.5); }
effect.trail(r.nextDouble() < 0.5);
effect.with(FireworkEffect.Type.values()[r.nextInt(FireworkEffect.Type.values().length)]);
// set random effect and randomize power void spawnRandomFireworkAtSheep(Sheep sheep) {
meta.addEffect(effect.build()); Firework firework = (Firework) sheep.getWorld().spawnEntity(sheep.getEyeLocation(), EntityType.FIREWORK);
meta.setPower(r.nextInt(2) + 1); randomizeFirework(firework);
}
// apply it to the given firework void update() {
firework.setFireworkMeta(meta); if (duration > 0) {
} updateAll();
playSounds();
duration -= period;
this.scheduleUpdate();
this.state = (this.state + 1) % 10000;
} else {
this.stopDisco();
}
}
void spawnRandomFireworkAtSheep(Sheep sheep) { void scheduleUpdate() {
Firework firework = (Firework) sheep.getWorld().spawnEntity(sheep.getEyeLocation(), EntityType.FIREWORK); updater = new DiscoUpdater();
randomizeFirework(firework); updater.runTaskLater(parent, this.period);
} }
void update() { void startDisco() {
if (duration > 0) { this.spawnAll(sheep, radius);
updateAll(); this.scheduleUpdate();
playSounds(); parent.getPartyMap().put(this.player.getName(), this);
duration -= period; // start listening
this.scheduleUpdate(); this.partyEvents = new PartyEvents(this.parent, this);
this.state = (this.state + 1) % 10000; parent.getServer().getPluginManager().registerEvents(this.partyEvents, this.parent);
} else { }
this.stopDisco();
}
}
void scheduleUpdate() { void stopDisco() {
updater = new DiscoUpdater(); removeAll();
updater.runTaskLater(parent, this.period); this.duration = 0;
} if (updater != null) {
updater.cancel();
}
updater = null;
parent.getPartyMap().remove(this.player.getName());
// stop listening
HandlerList.unregisterAll(this.partyEvents);
}
void startDisco() { class DiscoUpdater extends BukkitRunnable {
this.spawnAll(sheep, radius);
this.scheduleUpdate();
parent.getPartyMap().put(this.player.getName(), this);
// start listening
this.partyEvents = new PartyEvents(this.parent, this);
parent.getServer().getPluginManager().registerEvents(this.partyEvents, this.parent);
}
void stopDisco() { @Override
removeAll(); public void run() {
this.duration = 0; update();
if (updater != null) { }
updater.cancel(); }
}
updater = null;
parent.getPartyMap().remove(this.player.getName());
// stop listening
HandlerList.unregisterAll(this.partyEvents);
}
class DiscoUpdater extends BukkitRunnable {
@Override
public void run() {
update();
}
}
} }

View File

@ -12,302 +12,300 @@ import org.bukkit.plugin.java.JavaPlugin;
public final class DiscoSheep extends JavaPlugin { public final class DiscoSheep extends JavaPlugin {
static final String PERMISSION_PARTY = "discosheep.party.me"; static final String PERMISSION_PARTY = "discosheep.party.me";
static final String PERMISSION_ALL = "discosheep.party.all"; static final String PERMISSION_ALL = "discosheep.party.all";
static final String PERMISSION_FIREWORKS = "discosheep.party.fireworks"; static final String PERMISSION_FIREWORKS = "discosheep.party.fireworks";
static final String PERMISSION_STOPALL = "discosheep.admin.stopall"; static final String PERMISSION_STOPALL = "discosheep.admin.stopall";
static final String PERMISSION_RELOAD = "discosheep.admin.reload"; static final String PERMISSION_RELOAD = "discosheep.admin.reload";
static final String PERMISSION_OTHER = "discosheep.party.other"; static final String PERMISSION_OTHER = "discosheep.party.other";
static final String PERMISSION_CHANGEPERIOD = "discosheep.party.changeperiod"; static final String PERMISSION_CHANGEPERIOD = "discosheep.party.changeperiod";
static final String PERMISSION_CHANGEDEFAULTS = "discosheep.admin.changedefaults"; static final String PERMISSION_CHANGEDEFAULTS = "discosheep.admin.changedefaults";
static final String PERMISSION_SAVECONFIG = "discosheep.admin.saveconfig"; static final String PERMISSION_SAVECONFIG = "discosheep.admin.saveconfig";
static final String PERMISSION_ONJOIN = "discosheep.party.onjoin"; static final String PERMISSION_ONJOIN = "discosheep.party.onjoin";
static final String PERMISSION_SPAWNGUESTS = "discosheep.party.spawnguests"; static final String PERMISSION_SPAWNGUESTS = "discosheep.party.spawnguests";
static final String PERMISSION_TOGGLEPARTYONJOIN = "discosheep.admin.toggleonjoin"; static final String PERMISSION_TOGGLEPARTYONJOIN = "discosheep.admin.toggleonjoin";
static final String PERMISSION_LIGHTNING = "discosheep.party.lightning"; static final String PERMISSION_LIGHTNING = "discosheep.party.lightning";
static boolean partyOnJoin = false; static boolean partyOnJoin = false;
Map<String, DiscoParty> parties = new HashMap<String, DiscoParty>(); Map<String, DiscoParty> parties = new HashMap<String, DiscoParty>();
@Override @Override
public void onEnable() { public void onEnable() {
getCommand("ds").setExecutor(new DiscoSheepCommandExecutor(this)); getCommand("ds").setExecutor(new DiscoSheepCommandExecutor(this));
getServer().getPluginManager().registerEvents(new GlobalEvents(this), this); getServer().getPluginManager().registerEvents(new GlobalEvents(this), this);
getConfig().addDefault("on-join.enabled", partyOnJoin); getConfig().addDefault("on-join.enabled", partyOnJoin);
getConfig().addDefault("max.sheep", DiscoParty.maxSheep); getConfig().addDefault("max.sheep", DiscoParty.maxSheep);
getConfig().addDefault("max.radius", DiscoParty.maxRadius); getConfig().addDefault("max.radius", DiscoParty.maxRadius);
getConfig().addDefault("max.duration", toSeconds_i(DiscoParty.maxDuration)); getConfig().addDefault("max.duration", toSeconds_i(DiscoParty.maxDuration));
getConfig().addDefault("max.period-ticks", DiscoParty.maxPeriod); getConfig().addDefault("max.period-ticks", DiscoParty.maxPeriod);
getConfig().addDefault("min.period-ticks", DiscoParty.minPeriod); getConfig().addDefault("min.period-ticks", DiscoParty.minPeriod);
getConfig().addDefault("default.sheep", DiscoParty.defaultSheep); getConfig().addDefault("default.sheep", DiscoParty.defaultSheep);
getConfig().addDefault("default.radius", DiscoParty.defaultRadius); getConfig().addDefault("default.radius", DiscoParty.defaultRadius);
getConfig().addDefault("default.duration", toSeconds_i(DiscoParty.defaultDuration)); getConfig().addDefault("default.duration", toSeconds_i(DiscoParty.defaultDuration));
getConfig().addDefault("default.period-ticks", DiscoParty.defaultPeriod); getConfig().addDefault("default.period-ticks", DiscoParty.defaultPeriod);
/*
* Iterate through all live entities and create default configuration values for them
* excludes bosses and other mobs that throw NPE
*/
/* for (EntityType ent : EntityType.values()) {
if (ent.isAlive()
&& !ent.equals(EntityType.ENDER_DRAGON)
&& !ent.equals(EntityType.WITHER)
&& !ent.equals(EntityType.PIG_ZOMBIE)
&& !ent.equals(EntityType.OCELOT)
&& !ent.equals(EntityType.CAVE_SPIDER)
&& !ent.equals(EntityType.MAGMA_CUBE)
&& !ent.equals(EntityType.MUSHROOM_COW)
&& !ent.equals(EntityType.IRON_GOLEM)
&& !ent.equals(EntityType.PLAYER)) {
getConfig().addDefault("default.guests." + ent.toString(), 0);
getConfig().addDefault("max.guests." + ent.toString(), 0);
}
}*/
loadConfigFromDisk();
}
void loadConfigFromDisk() { /*
getConfig().options().copyDefaults(true); * Iterate through all live entities and create default configuration values for them
saveConfig(); * excludes bosses and other mobs that throw NPE
*/
/* for (EntityType ent : EntityType.values()) {
if (ent.isAlive()
&& !ent.equals(EntityType.ENDER_DRAGON)
&& !ent.equals(EntityType.WITHER)
&& !ent.equals(EntityType.PIG_ZOMBIE)
&& !ent.equals(EntityType.OCELOT)
&& !ent.equals(EntityType.CAVE_SPIDER)
&& !ent.equals(EntityType.MAGMA_CUBE)
&& !ent.equals(EntityType.MUSHROOM_COW)
&& !ent.equals(EntityType.IRON_GOLEM)
&& !ent.equals(EntityType.PLAYER)) {
getConfig().addDefault("default.guests." + ent.toString(), 0);
getConfig().addDefault("max.guests." + ent.toString(), 0);
}
}*/
loadConfigFromDisk();
}
partyOnJoin = getConfig().getBoolean("on-join.enabled"); void loadConfigFromDisk() {
DiscoParty.maxSheep = getConfig().getInt("max.sheep"); getConfig().options().copyDefaults(true);
DiscoParty.maxRadius = getConfig().getInt("max.radius"); saveConfig();
DiscoParty.maxDuration = toTicks(getConfig().getInt("max.duration"));
DiscoParty.maxPeriod = getConfig().getInt("max.period-ticks");
DiscoParty.minPeriod = getConfig().getInt("min.period-ticks");
DiscoParty.defaultSheep = getConfig().getInt("default.sheep");
DiscoParty.defaultRadius = getConfig().getInt("default.radius");
DiscoParty.defaultDuration = toTicks(getConfig().getInt("default.duration"));
DiscoParty.defaultPeriod = getConfig().getInt("default.period-ticks");
/* for (String key : getConfig().getConfigurationSection("default.guests").getKeys(false)) { partyOnJoin = getConfig().getBoolean("on-join.enabled");
DiscoParty.getDefaultGuestNumbers().put(key, getConfig().getInt("default.guests." + key)); DiscoParty.maxSheep = getConfig().getInt("max.sheep");
} DiscoParty.maxRadius = getConfig().getInt("max.radius");
DiscoParty.maxDuration = toTicks(getConfig().getInt("max.duration"));
DiscoParty.maxPeriod = getConfig().getInt("max.period-ticks");
DiscoParty.minPeriod = getConfig().getInt("min.period-ticks");
DiscoParty.defaultSheep = getConfig().getInt("default.sheep");
DiscoParty.defaultRadius = getConfig().getInt("default.radius");
DiscoParty.defaultDuration = toTicks(getConfig().getInt("default.duration"));
DiscoParty.defaultPeriod = getConfig().getInt("default.period-ticks");
/* for (String key : getConfig().getConfigurationSection("default.guests").getKeys(false)) {
DiscoParty.getDefaultGuestNumbers().put(key, getConfig().getInt("default.guests." + key));
}
for (String key : getConfig().getConfigurationSection("max.guests").getKeys(false)) { for (String key : getConfig().getConfigurationSection("max.guests").getKeys(false)) {
DiscoParty.getMaxGuestNumbers().put(key, getConfig().getInt("max.guests." + key)); DiscoParty.getMaxGuestNumbers().put(key, getConfig().getInt("max.guests." + key));
}*/ }*/
}
} void reloadConfigFromDisk() {
reloadConfig();
loadConfigFromDisk();
}
void reloadConfigFromDisk() { void saveConfigToDisk() {
reloadConfig(); getConfig().set("on-join.enabled", partyOnJoin);
loadConfigFromDisk(); getConfig().set("default.sheep", DiscoParty.defaultSheep);
} getConfig().set("default.radius", DiscoParty.defaultRadius);
getConfig().set("default.duration", toSeconds_i(DiscoParty.defaultDuration));
getConfig().set("default.period-ticks", DiscoParty.defaultPeriod);
void saveConfigToDisk() { /* for (Map.Entry<String, Integer> entry : DiscoParty.getDefaultGuestNumbers().entrySet()) {
getConfig().set("on-join.enabled", partyOnJoin); getConfig().set("default.guests." + entry.getKey(), entry.getValue());
getConfig().set("default.sheep", DiscoParty.defaultSheep); }*/
getConfig().set("default.radius", DiscoParty.defaultRadius); saveConfig();
getConfig().set("default.duration", toSeconds_i(DiscoParty.defaultDuration)); }
getConfig().set("default.period-ticks", DiscoParty.defaultPeriod);
/* for (Map.Entry<String, Integer> entry : DiscoParty.getDefaultGuestNumbers().entrySet()) { @Override
getConfig().set("default.guests." + entry.getKey(), entry.getValue()); public void onDisable() {
}*/ this.stopAllParties(); // or else the parties will continue FOREVER
}
saveConfig(); static int toTicks(double seconds) {
} return (int) Math.round(seconds * 20.0);
}
@Override static double toSeconds(int ticks) {
public void onDisable() { return (double) Math.round(ticks / 20.0);
this.stopAllParties(); // or else the parties will continue FOREVER }
}
static int toTicks(double seconds) { static int toSeconds_i(int ticks) {
return (int) Math.round(seconds * 20.0); return (int) Math.round(ticks / 20.0);
} }
static double toSeconds(int ticks) { public synchronized Map<String, DiscoParty> getPartyMap() {
return (double) Math.round(ticks / 20.0); return this.parties;
} }
static int toSeconds_i(int ticks) { public synchronized ArrayList<DiscoParty> getParties() {
return (int) Math.round(ticks / 20.0); return new ArrayList<DiscoParty>(this.getPartyMap().values());
} }
public synchronized Map<String, DiscoParty> getPartyMap() { public void stopParty(String name) {
return this.parties; if (this.hasParty(name)) {
} this.getParty(name).stopDisco();
}
}
public synchronized ArrayList<DiscoParty> getParties() { public void stopAllParties() {
return new ArrayList<DiscoParty>(this.getPartyMap().values()); for (DiscoParty party : this.getParties()) {
} party.stopDisco();
}
}
public void stopParty(String name) { public boolean hasParty(String name) {
if (this.hasParty(name)) { return this.getPartyMap().containsKey(name);
this.getParty(name).stopDisco(); }
}
}
public void stopAllParties() { public DiscoParty getParty(String name) {
for (DiscoParty party : this.getParties()) { return this.getPartyMap().get(name);
party.stopDisco(); }
}
}
public boolean hasParty(String name) { public void removeParty(String name) {
return this.getPartyMap().containsKey(name); if (this.hasParty(name)) {
} this.getPartyMap().remove(name);
}
}
public DiscoParty getParty(String name) { /*-- Actual commands begin here --*/
return this.getPartyMap().get(name); boolean helpCommand(CommandSender sender) {
} sender.sendMessage(ChatColor.YELLOW
+ "DiscoSheep Help\n"
+ ChatColor.GRAY
+ " Subcommands\n"
+ ChatColor.WHITE + "me, stop, all, stopall, save, reload, togglejoin\n"
+ "other <players>: start a party for the space-delimited list of players\n"
+ "defaults: Change the default settings for parties (takes normal arguments)\n"
+ ChatColor.GRAY + " Arguments\n"
+ ChatColor.WHITE + "-n <integer>: set the number of sheep per player that spawn\n"
+ "-t <integer>: set the party duration in seconds\n"
+ "-p <ticks>: set the number of ticks between each disco beat\n"
+ "-r <integer>: set radius of the area in which sheep can spawn\n"
//+ "-g <mob> <number>: set spawns for other mobs\n"
+ "-l: enables lightning\n"
+ "-fw: enables fireworks");
return true;
}
public void removeParty(String name) { boolean stopMeCommand(CommandSender sender) {
if (this.hasParty(name)) { stopParty(sender.getName());
this.getPartyMap().remove(name); return true;
} }
}
/*-- Actual commands begin here --*/ boolean stopAllCommand(CommandSender sender) {
boolean helpCommand(CommandSender sender) { if (sender.hasPermission(PERMISSION_STOPALL)) {
sender.sendMessage(ChatColor.YELLOW stopAllParties();
+ "DiscoSheep Help\n" return true;
+ ChatColor.GRAY } else {
+ " Subcommands\n" return noPermsMessage(sender, PERMISSION_STOPALL);
+ ChatColor.WHITE + "me, stop, all, stopall, save, reload, togglejoin\n" }
+ "other <players>: start a party for the space-delimited list of players\n" }
+ "defaults: Change the default settings for parties (takes normal arguments)\n"
+ ChatColor.GRAY + " Arguments\n"
+ ChatColor.WHITE + "-n <integer>: set the number of sheep per player that spawn\n"
+ "-t <integer>: set the party duration in seconds\n"
+ "-p <ticks>: set the number of ticks between each disco beat\n"
+ "-r <integer>: set radius of the area in which sheep can spawn\n"
//+ "-g <mob> <number>: set spawns for other mobs\n"
+ "-l: enables lightning\n"
+ "-fw: enables fireworks");
return true;
}
boolean stopMeCommand(CommandSender sender) { boolean partyCommand(Player player, DiscoParty party) {
stopParty(sender.getName()); if (player.hasPermission(PERMISSION_PARTY)) {
return true; if (!hasParty(player.getName())) {
} party.setPlayer(player);
party.startDisco();
} else {
player.sendMessage(ChatColor.RED + "You already have a party. Are you underground?");
}
return true;
} else {
return noPermsMessage(player, PERMISSION_PARTY);
}
}
boolean stopAllCommand(CommandSender sender) { boolean reloadCommand(CommandSender sender) {
if (sender.hasPermission(PERMISSION_STOPALL)) { if (sender.hasPermission(PERMISSION_RELOAD)) {
stopAllParties(); reloadConfigFromDisk();
return true; sender.sendMessage(ChatColor.GREEN + "DiscoSheep config reloaded from disk");
} else { return true;
return noPermsMessage(sender, PERMISSION_STOPALL); } else {
} return noPermsMessage(sender, PERMISSION_RELOAD);
} }
}
boolean partyCommand(Player player, DiscoParty party) { @SuppressWarnings("deprecation")
if (player.hasPermission(PERMISSION_PARTY)) { // UUIDs not necessary since DiscoSheep only lasts for one session at most
if (!hasParty(player.getName())) { // and permissions will handle onJoin DiscoSheep
party.setPlayer(player); boolean partyOtherCommand(String[] players, CommandSender sender, DiscoParty party) {
party.startDisco(); if (sender.hasPermission(PERMISSION_OTHER)) {
} else { Player p;
player.sendMessage(ChatColor.RED + "You already have a party. Are you underground?"); for (String playerName : players) {
} p = Bukkit.getServer().getPlayer(playerName);
return true; if (p != null) {
} else { if (!hasParty(p.getName())) {
return noPermsMessage(player, PERMISSION_PARTY); DiscoParty individualParty = party.clone(p);
} individualParty.startDisco();
} }
} else {
sender.sendMessage("Invalid player: " + playerName);
}
}
return true;
} else {
return noPermsMessage(sender, PERMISSION_OTHER);
}
}
boolean reloadCommand(CommandSender sender) { boolean partyAllCommand(CommandSender sender, DiscoParty party) {
if (sender.hasPermission(PERMISSION_RELOAD)) { if (sender.hasPermission(PERMISSION_ALL)) {
reloadConfigFromDisk(); for (Player p : Bukkit.getServer().getOnlinePlayers()) {
sender.sendMessage(ChatColor.GREEN + "DiscoSheep config reloaded from disk"); if (!hasParty(p.getName())) {
return true; DiscoParty individualParty = party.clone(p);
} else { individualParty.startDisco();
return noPermsMessage(sender, PERMISSION_RELOAD); p.sendMessage(ChatColor.RED + "LET'S DISCO!!");
} }
} }
return true;
@SuppressWarnings( "deprecation" ) } else {
// UUIDs not necessary since DiscoSheep only lasts for one session at most return noPermsMessage(sender, PERMISSION_ALL);
// and permissions will handle onJoin DiscoSheep }
boolean partyOtherCommand(String[] players, CommandSender sender, DiscoParty party) { }
if (sender.hasPermission(PERMISSION_OTHER)) {
Player p;
for (String playerName : players) {
p = Bukkit.getServer().getPlayer(playerName);
if (p != null) {
if (!hasParty(p.getName())) {
DiscoParty individualParty = party.clone(p);
individualParty.startDisco();
}
} else {
sender.sendMessage("Invalid player: " + playerName);
}
}
return true;
} else {
return noPermsMessage(sender, PERMISSION_OTHER);
}
}
boolean partyAllCommand(CommandSender sender, DiscoParty party) { void partyOnJoin(Player player) {
if (sender.hasPermission(PERMISSION_ALL)) { if (!partyOnJoin) {
for (Player p : Bukkit.getServer().getOnlinePlayers()) { return;
if (!hasParty(p.getName())) { }
DiscoParty individualParty = party.clone(p); if (player.hasPermission(PERMISSION_ONJOIN)) {
individualParty.startDisco(); DiscoParty party = new DiscoParty(this, player);
p.sendMessage(ChatColor.RED + "LET'S DISCO!!"); party.startDisco();
} }
} }
return true;
} else {
return noPermsMessage(sender, PERMISSION_ALL);
}
}
void partyOnJoin(Player player) { boolean togglePartyOnJoinCommand(CommandSender sender) {
if (!partyOnJoin) { if (!sender.hasPermission(PERMISSION_TOGGLEPARTYONJOIN)) {
return; return noPermsMessage(sender, PERMISSION_TOGGLEPARTYONJOIN);
} }
if (player.hasPermission(PERMISSION_ONJOIN)) { partyOnJoin = !partyOnJoin;
DiscoParty party = new DiscoParty(this, player); if (partyOnJoin) {
party.startDisco(); sender.sendMessage(ChatColor.GREEN + "DiscoSheep party on join functionality enabled.");
} } else {
} sender.sendMessage(ChatColor.GREEN + "DiscoSheep party on join functionality disabled.");
}
return true;
}
boolean togglePartyOnJoinCommand(CommandSender sender) { boolean setDefaultsCommand(CommandSender sender, DiscoParty party) {
if (!sender.hasPermission(PERMISSION_TOGGLEPARTYONJOIN)) { if (sender.hasPermission(PERMISSION_CHANGEDEFAULTS)) {
return noPermsMessage(sender, PERMISSION_TOGGLEPARTYONJOIN); party.setDefaultsFromCurrent();
} sender.sendMessage(ChatColor.GREEN + "DiscoSheep configured with new defaults (not saved to disk yet)");
partyOnJoin = !partyOnJoin; return true;
if (partyOnJoin) { } else {
sender.sendMessage(ChatColor.GREEN + "DiscoSheep party on join functionality enabled."); return noPermsMessage(sender, PERMISSION_CHANGEDEFAULTS);
} else { }
sender.sendMessage(ChatColor.GREEN + "DiscoSheep party on join functionality disabled."); }
}
return true;
}
boolean setDefaultsCommand(CommandSender sender, DiscoParty party) { boolean saveConfigCommand(CommandSender sender) {
if (sender.hasPermission(PERMISSION_CHANGEDEFAULTS)) { if (sender.hasPermission(PERMISSION_SAVECONFIG)) {
party.setDefaultsFromCurrent(); saveConfigToDisk();
sender.sendMessage(ChatColor.GREEN + "DiscoSheep configured with new defaults (not saved to disk yet)"); sender.sendMessage(ChatColor.GREEN + "DiscoSheep config saved to disk");
return true; return true;
} else { } else {
return noPermsMessage(sender, PERMISSION_CHANGEDEFAULTS); return noPermsMessage(sender, PERMISSION_SAVECONFIG);
} }
}
boolean saveConfigCommand(CommandSender sender) { }
if (sender.hasPermission(PERMISSION_SAVECONFIG)) {
saveConfigToDisk();
sender.sendMessage(ChatColor.GREEN + "DiscoSheep config saved to disk");
return true;
} else {
return noPermsMessage(sender, PERMISSION_SAVECONFIG);
}
} boolean clearGuests(DiscoParty party) {
party.getGuestNumbers().clear();
return true;
}
boolean clearGuests(DiscoParty party) { boolean noPermsMessage(CommandSender sender, String permission) {
party.getGuestNumbers().clear(); sender.sendMessage(ChatColor.RED + "You do not have the permission node " + ChatColor.GRAY + permission);
return true; return false;
} }
boolean noPermsMessage(CommandSender sender, String permission) {
sender.sendMessage(ChatColor.RED + "You do not have the permission node " + ChatColor.GRAY + permission);
return false;
}
} }

View File

@ -9,144 +9,144 @@ import org.bukkit.entity.Player;
public class DiscoSheepCommandExecutor implements CommandExecutor { public class DiscoSheepCommandExecutor implements CommandExecutor {
private final DiscoSheep parent; private final DiscoSheep parent;
public DiscoSheepCommandExecutor(DiscoSheep parent) { public DiscoSheepCommandExecutor(DiscoSheep parent) {
this.parent = parent; this.parent = parent;
} }
private boolean parseNextArg(String[] args, int i, String compare) { private boolean parseNextArg(String[] args, int i, String compare) {
if (i < args.length - 1) { if (i < args.length - 1) {
return args[i + 1].equalsIgnoreCase(compare); return args[i + 1].equalsIgnoreCase(compare);
} }
return false; return false;
} }
private String getNextArg(String[] args, int i) { private String getNextArg(String[] args, int i) {
if (i < args.length - 1) { if (i < args.length - 1) {
return args[i + 1]; return args[i + 1];
} else { } else {
return null; return null;
} }
} }
private int getNextIntArg(String[] args, int i) { private int getNextIntArg(String[] args, int i) {
if (i < args.length - 1) { if (i < args.length - 1) {
try { try {
return Integer.parseInt(args[i + 1]); return Integer.parseInt(args[i + 1]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return -1; // so that it fails limit checks elsewhere return -1; // so that it fails limit checks elsewhere
} }
} }
return -1; // ibid return -1; // ibid
} }
private Double getNextDoubleArg(String[] args, int i) { private Double getNextDoubleArg(String[] args, int i) {
if (i < args.length - 1) { if (i < args.length - 1) {
try { try {
return Double.parseDouble(args[i + 1]); return Double.parseDouble(args[i + 1]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return -1.0d; // so that it fais limit checks elsewhere return -1.0d; // so that it fais limit checks elsewhere
} }
} }
return -1.0d; // ibid return -1.0d; // ibid
} }
// return portion of the array that contains space-separated args, // return portion of the array that contains space-separated args,
// stopping at the end of the array or the next -switch // stopping at the end of the array or the next -switch
private String[] getNextArgs(String[] args, int i) { private String[] getNextArgs(String[] args, int i) {
int j = i; int j = i;
while (j < args.length && !args[j].startsWith("-")) { while (j < args.length && !args[j].startsWith("-")) {
j++; j++;
} }
return Arrays.copyOfRange(args, i, j); return Arrays.copyOfRange(args, i, j);
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null; Player player = null;
boolean isPlayer = false; boolean isPlayer = false;
boolean specialRadius = false; boolean specialRadius = false;
// flag to determine if we calculate a radius so that the sheep spawn densely in an area // flag to determine if we calculate a radius so that the sheep spawn densely in an area
if (sender instanceof Player) { if (sender instanceof Player) {
player = (Player) sender; player = (Player) sender;
isPlayer = true; isPlayer = true;
} // check isPlayer before "stop" and "me" commands } // check isPlayer before "stop" and "me" commands
// check for commands that don't need a party // check for commands that don't need a party
// so that we get them out of the way, and // so that we get them out of the way, and
// prevent needless construction of parties // prevent needless construction of parties
if (args.length == 1) { if (args.length == 1) {
if (args[0].equalsIgnoreCase("stopall")) { if (args[0].equalsIgnoreCase("stopall")) {
return parent.stopAllCommand(sender); return parent.stopAllCommand(sender);
} else if (args[0].equalsIgnoreCase("stop") && isPlayer) { } else if (args[0].equalsIgnoreCase("stop") && isPlayer) {
return parent.stopMeCommand(sender); return parent.stopMeCommand(sender);
} else if (args[0].equalsIgnoreCase("help")) { } else if (args[0].equalsIgnoreCase("help")) {
return parent.helpCommand(sender); return parent.helpCommand(sender);
} else if (args[0].equalsIgnoreCase("reload")) { } else if (args[0].equalsIgnoreCase("reload")) {
return parent.reloadCommand(sender); return parent.reloadCommand(sender);
} else if (args[0].equalsIgnoreCase("save") || args[0].equalsIgnoreCase("saveconfig")) { } else if (args[0].equalsIgnoreCase("save") || args[0].equalsIgnoreCase("saveconfig")) {
return parent.saveConfigCommand(sender); return parent.saveConfigCommand(sender);
} else if (args[0].equalsIgnoreCase("togglejoin")) { } else if (args[0].equalsIgnoreCase("togglejoin")) {
return parent.togglePartyOnJoinCommand(sender); return parent.togglePartyOnJoinCommand(sender);
} }
} }
// construct a main party; all other parties will copy from this // construct a main party; all other parties will copy from this
DiscoParty mainParty = new DiscoParty(parent); DiscoParty mainParty = new DiscoParty(parent);
// omg I love argument parsing and I know the best way! // omg I love argument parsing and I know the best way!
for (int i = 1; i < args.length; i++) { for (int i = 1; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-fw")) { if (args[i].equalsIgnoreCase("-fw")) {
if (sender.hasPermission(DiscoSheep.PERMISSION_FIREWORKS)) { if (sender.hasPermission(DiscoSheep.PERMISSION_FIREWORKS)) {
mainParty.setDoFireworks(true); mainParty.setDoFireworks(true);
} else { } else {
return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_FIREWORKS); return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_FIREWORKS);
} }
} else if (args[i].equalsIgnoreCase("-r")) { } else if (args[i].equalsIgnoreCase("-r")) {
if (parseNextArg(args, i, "dense")) { if (parseNextArg(args, i, "dense")) {
specialRadius = true; specialRadius = true;
} }
if (!specialRadius) { if (!specialRadius) {
try { try {
mainParty.setRadius(getNextIntArg(args, i)); mainParty.setRadius(getNextIntArg(args, i));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
sender.sendMessage("Radius must be an integer within the range [1, " sender.sendMessage("Radius must be an integer within the range [1, "
+ DiscoParty.maxRadius + "]"); + DiscoParty.maxRadius + "]");
return false; return false;
} }
} }
} else if (args[i].equalsIgnoreCase("-n")) { } else if (args[i].equalsIgnoreCase("-n")) {
try { try {
mainParty.setSheep(getNextIntArg(args, i)); mainParty.setSheep(getNextIntArg(args, i));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
sender.sendMessage("The number of sheep must be an integer within the range [1, " sender.sendMessage("The number of sheep must be an integer within the range [1, "
+ DiscoParty.maxSheep + "]"); + DiscoParty.maxSheep + "]");
return false; return false;
} }
} else if (args[i].equalsIgnoreCase("-t")) { } else if (args[i].equalsIgnoreCase("-t")) {
try { try {
mainParty.setDuration(parent.toTicks(getNextIntArg(args, i))); mainParty.setDuration(parent.toTicks(getNextIntArg(args, i)));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
sender.sendMessage("The duration in seconds must be an integer within the range [1, " sender.sendMessage("The duration in seconds must be an integer within the range [1, "
+ parent.toSeconds(DiscoParty.maxDuration) + "]"); + parent.toSeconds(DiscoParty.maxDuration) + "]");
return false; return false;
} }
} else if (args[i].equalsIgnoreCase("-p")) { } else if (args[i].equalsIgnoreCase("-p")) {
if (!sender.hasPermission(DiscoSheep.PERMISSION_CHANGEPERIOD)) { if (!sender.hasPermission(DiscoSheep.PERMISSION_CHANGEPERIOD)) {
return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_CHANGEPERIOD); return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_CHANGEPERIOD);
} }
try { try {
mainParty.setPeriod(getNextIntArg(args, i)); mainParty.setPeriod(getNextIntArg(args, i));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
sender.sendMessage( sender.sendMessage(
"The period in ticks must be within the range [" "The period in ticks must be within the range ["
+ DiscoParty.minPeriod + ", " + DiscoParty.minPeriod + ", "
+ DiscoParty.maxPeriod + "]"); + DiscoParty.maxPeriod + "]");
return false; return false;
} }
// } else if (args[i].equalsIgnoreCase("-g")) { // } else if (args[i].equalsIgnoreCase("-g")) {
// if (!sender.hasPermission(DiscoSheep.PERMISSION_SPAWNGUESTS)) { // if (!sender.hasPermission(DiscoSheep.PERMISSION_SPAWNGUESTS)) {
// return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_SPAWNGUESTS); // return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_SPAWNGUESTS);
@ -167,33 +167,33 @@ public class DiscoSheepCommandExecutor implements CommandExecutor {
// } // }
// j += 2; // skip over two arguments, since they come in pairs of entity-number // j += 2; // skip over two arguments, since they come in pairs of entity-number
// } // }
} else if (args[i].equalsIgnoreCase("-l")) { } else if (args[i].equalsIgnoreCase("-l")) {
if (!sender.hasPermission(DiscoSheep.PERMISSION_LIGHTNING)) { if (!sender.hasPermission(DiscoSheep.PERMISSION_LIGHTNING)) {
return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_LIGHTNING); return parent.noPermsMessage(sender, DiscoSheep.PERMISSION_LIGHTNING);
} }
mainParty.setDoLightning(true); mainParty.setDoLightning(true);
} }
} }
if (specialRadius) { if (specialRadius) {
mainParty.setDenseRadius(mainParty.getSheep()); mainParty.setDenseRadius(mainParty.getSheep());
} }
if (args.length > 0) { if (args.length > 0) {
if (args[0].equalsIgnoreCase("all")) { if (args[0].equalsIgnoreCase("all")) {
return parent.partyAllCommand(sender, mainParty); return parent.partyAllCommand(sender, mainParty);
} else if (args[0].equalsIgnoreCase("me") && isPlayer) { } else if (args[0].equalsIgnoreCase("me") && isPlayer) {
return parent.partyCommand(player, mainParty); return parent.partyCommand(player, mainParty);
} else if (args[0].equalsIgnoreCase("other")) { } else if (args[0].equalsIgnoreCase("other")) {
return parent.partyOtherCommand(getNextArgs(args, 1), sender, mainParty); return parent.partyOtherCommand(getNextArgs(args, 1), sender, mainParty);
} else if (args[0].equalsIgnoreCase("defaults")) { } else if (args[0].equalsIgnoreCase("defaults")) {
return parent.setDefaultsCommand(sender, mainParty); return parent.setDefaultsCommand(sender, mainParty);
} else { } else {
sender.sendMessage(ChatColor.RED + "Invalid argument (certain commands do not work from console)."); sender.sendMessage(ChatColor.RED + "Invalid argument (certain commands do not work from console).");
return false; return false;
} }
} }
return false; return false;
} }
} }

View File

@ -14,22 +14,22 @@ import org.bukkit.event.player.PlayerQuitEvent;
public class GlobalEvents implements Listener { public class GlobalEvents implements Listener {
DiscoSheep parent; DiscoSheep parent;
public GlobalEvents(DiscoSheep parent) { public GlobalEvents(DiscoSheep parent) {
this.parent = parent; this.parent = parent;
} }
@EventHandler (priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuitEvent(PlayerQuitEvent e) { public void onPlayerQuitEvent(PlayerQuitEvent e) {
String name = e.getPlayer().getName(); String name = e.getPlayer().getName();
parent.stopParty(name); parent.stopParty(name);
// stop party on player quit or else it will CONTINUE FOR ETERNITY // stop party on player quit or else it will CONTINUE FOR ETERNITY
} }
@EventHandler (priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoinEvent(PlayerJoinEvent e) { public void onPlayerJoinEvent(PlayerJoinEvent e) {
Player player = e.getPlayer(); Player player = e.getPlayer();
parent.partyOnJoin(player); parent.partyOnJoin(player);
} }
} }

View File

@ -14,58 +14,58 @@ import org.bukkit.event.player.PlayerShearEntityEvent;
*/ */
public class PartyEvents implements Listener { public class PartyEvents implements Listener {
DiscoSheep parent; DiscoSheep parent;
DiscoParty party; DiscoParty party;
/* /*
* There will be multiple instances of PartyEvents, * There will be multiple instances of PartyEvents,
* and each instance will only listen for its own party. * and each instance will only listen for its own party.
* That way, we don't have multiple instances iterating through * That way, we don't have multiple instances iterating through
* the entire parties hashmap redundantly, yet we can still * the entire parties hashmap redundantly, yet we can still
* unregister the listeners when no parties are running. * unregister the listeners when no parties are running.
*/ */
public PartyEvents(DiscoSheep parent, DiscoParty party) { public PartyEvents(DiscoSheep parent, DiscoParty party) {
this.parent = parent; this.parent = parent;
this.party = party; this.party = party;
} }
// prevent sheep shearing // prevent sheep shearing
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerShear(PlayerShearEntityEvent e) { public void onPlayerShear(PlayerShearEntityEvent e) {
if (e.getEntity() instanceof Sheep) { if (e.getEntity() instanceof Sheep) {
if (party.getSheepList().contains((Sheep) e.getEntity())) { if (party.getSheepList().contains((Sheep) e.getEntity())) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }
// actually make sheep and other guests invincible // actually make sheep and other guests invincible
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onLivingEntityDamageEvent(EntityDamageEvent e) { public void onLivingEntityDamageEvent(EntityDamageEvent e) {
if (e.getEntity() instanceof Sheep) { if (e.getEntity() instanceof Sheep) {
if (party.getSheepList().contains((Sheep) e.getEntity())) { if (party.getSheepList().contains((Sheep) e.getEntity())) {
{ {
party.jump(e.getEntity()); // for kicks party.jump(e.getEntity()); // for kicks
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }
if (party.getGuestList().contains(e.getEntity())) { if (party.getGuestList().contains(e.getEntity())) {
party.jump(e.getEntity()); party.jump(e.getEntity());
e.setCancelled(true); e.setCancelled(true);
} }
} }
// prevent uninvited guests from targetting players // prevent uninvited guests from targetting players
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityTargetLivingEntityEvent(EntityTargetEvent e) { public void onEntityTargetLivingEntityEvent(EntityTargetEvent e) {
if (party.getGuestList().contains(e.getEntity())) { if (party.getGuestList().contains(e.getEntity())) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }